【问题标题】:Move to the middle of a block code移动到块代码的中间
【发布时间】:2013-03-18 22:07:49
【问题描述】:

使用 Vim 我试图将光标移动到代码块的中间,但我不知道该怎么做:

//cursor is for instance here.

{
    //or here

    //some code
    // .... **** move cursor here ****
    //some more code 

}

最后的想法是有一个快捷方式,保存当前位置,将光标移动到代码块中间,将当前行设置到屏幕中间(用快捷方式“zz”),然后移动回到保存的位置。

我更喜欢内置的 vim 功能,但插件也可以。

编辑:这是用于 c++ 的,所以我希望它用于括号 {}。

【问题讨论】:

  • 请定义“代码块中间”
  • 您想要一个与语言无关的解决方案吗?或者使用{}作为“标记”的东西?你尝试了什么?
  • 对不起,我忘记了,我编辑了问题。
  • 注意快捷键 'zz','ZZ' 和 ':wq' 一样,所以如果你启用了 capslock,你可以很容易地退出 vim。
  • 不知道ZZ,很高兴知道!

标签: c++ vim vi


【解决方案1】:

我试了一下(又快又脏):

function! Middleize()

  " use ]M to jump to either the end of the current method if we are in it
  " or the start of the next method if we are above the method
  normal! ]M

  " we record the current line number
  let first_line = line('.')

  " we go to the other end of the method
  normal! %

  " we record the current line number
  let second_line = line('.')

  " we started either from the top or from the bottom of the method
  " so we have to take that into account when calculating the number
  " of the line we want to jump to
  if first_line < second_line
    let middle_line = first_line + ((second_line - first_line) / 2)
  else
    let middle_line = ((first_line - second_line) / 2) + second_line
  endif

  " let's go!
  execute "normal! " . middle_line . "Gzz"
endfunction

nnoremap <F5> :call Middleize()<CR>

【讨论】:

  • 我认为这可能是答案。我也在寻求这样的解决方案,但我想念 vim 知识来编写它,所以非常感谢!我尝试了一下,并对其进行了一些定制。谢谢人:)
【解决方案2】:

更多的通用解决方案,但可能有用 - easy-motion 插件可让您以极高的精确度到处跳转。

例如:

&lt;Leader&gt;&lt;Leader&gt;w(默认)-'word motion'

g

然后要跳回来,你只需向后做同样的事情(在这种情况下,&lt;Leader&gt;&lt;Leader&gt;b g

这不会将当前行设置到屏幕中间,尽管您可以:set scrolloff=9999 让屏幕中间跟随您的光标。

【讨论】:

  • 不是我想要的,但这很有趣!这对我来说可能已经足够了,我会试一试!
【解决方案3】:

这不会给你你想要的,但它会在屏幕上得到函数的文本(假设它不是太长)。

  1. ma - 在当前光标位置设置一个标记。
  2. 反复按 }(向前跳一段),直到您可以看到您想要的代码。
  3. `a - 返回您设置的标记。

vim 术语中的“段落”是一组连续的非空行。这是代码块的一个很好的近似值。另请注意,标记命令可以使用任何字母,因此一次最多可以有 52 个处于活动状态。

【讨论】:

  • 感谢您的回复,但这并不是我真正想要的:/ romainl 回答了我的问题,检查一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
相关资源
最近更新 更多