Vim:重新映射键以移动到下一个非空行(反之亦然)

时间:2016-11-08 23:32:28

标签: vim viml

我正在寻找一种方法来重新映射一个键,将光标向下移动到下一行,跳过任何只包含\n的行,以及一种只进行下一行的方法。

基本上,我想做与{和}动作相反的事情。

2 个答案:

答案 0 :(得分:5)

Here are alternatives to DJ's mappings that play well with hlsearch:

  • jump to next non-empty line

    nnoremap <key> :<C-u>call search('^.\+')<CR>
    
  • jump to previous non-empty line

    nnoremap <otherkey> :<C-u>call search('^.\+', 'b')<CR>
    
  • extend visual selection to next non-empty line

    xnoremap <key> :<C-u>k`\|call search('^.\+')\|normal! <C-r>=visualmode()<CR>``o<CR>
    
  • extend visual selection to previous non-empty line

    xnoremap <otherkey> :<C-u>k`\|call search('^.\+', 'b')\|normal! <C-r>=visualmode()<CR>``o<CR>
    
  • operate to next non-empty line

    omap <key> :<C-u>normal! v<key><CR>
    
  • operate to previous non-empty line

    omap <otherkey> :<C-u>normal! v<otherkey><CR>
    

Explanation…

With hlsearch enabled, /anything will highlight every match. Since we are not actively searching for non-empty lines but merely moving to them, the resulting highlighting is pointlessly noisy.

By using :help search(), we bypass hlsearchand thus make the mappings a lot less noisy.

<C-u> is used to remove any accidental range before calling our function.

The visual mode mappings work like this:

  1. we define the "previous mark" with :help :k,
  2. we perform the search,
  3. we run the following normal mode commands with :help :normal,
  4. we retrieve the previous visual mode with :help i_ctrl-r, :help "=, and :help visualmode(),
  5. we extend the visual selection to the location of the "previous mark" with :help '',
  6. and finally we move the cursor to the other end of the visual selection with :help v_o.

The operator pending mappings simply reuse the visual mode mappings.

答案 1 :(得分:2)

我不确定你想要映射这两个,所以我只使用{}。怎么样?

nnoremap } /^\S<cr>
nnoremap { ?^\S<cr>

解释非常简单。

/           " Search forward
 ^          " For the start of a line
  \S        " Followed by a non-whitespace character
    <cr>    " Enter

?映射是相同的,除了向后搜索而不是向前搜索。

当然,为了完整性,您需要添加

nnoremap } /^\S<cr>
xnoremap } /^\S<cr>
onoremap } /^\S<cr>
nnoremap { ?^\S<cr>
xnoremap { ?^\S<cr>
onoremap { ?^\S<cr>

这将使其作为运算符(例如d{)和可视模式的参数。

相关问题