Vim --根据语法在上下文中改变命令的行为

4ngedf3f  于 2023-05-07  发布在  其他
关注(0)|答案(3)|浏览(126)

我倾向于这样的注解行:

// This is a comment. 
// This is the second line of a comment paragraph.

// This is a second paragraph...

我的光标在这些行的中间,我想开始添加一些东西。通常是在一段的开头加上一句话。点击I将把我带到//之前。这是我想经常做的事情,它让我有点困扰,没有一种快速的方法可以在没有一堆移动命令或像^wi这样笨拙的到达的情况下到达那里。
我想将I命令调整为“smart”,这样只有当光标位于注解语法区域时,我才希望vim执行^wi
我能这么做吗我很确定我可以做到这一点,因为我有一个小命令,它能够告诉我光标所在的语法类型。

w1e3prcc

w1e3prcc1#

你可以用一行代码来实现,但是当涉及到条件语句时,我更喜欢使用函数:

:nnoremap I :call SmartInsert()<CR>

在函数中,可以使用synIDattr()获取活动语法项的名称;参见:help synID()下的示例。然后,您可以根据名称是否包含“注解”来执行不同的操作。根据需要移动光标,然后以:startinsert结束函数。

:help synIDattr()
:help =~?
:help :if
:help :startinsert
:help user-functions

********************我开始写函数了,在这里。真实的方便的。

function! SmartInsert()
    if synIDattr(synID(line("."), col("."), 1), "name") =~ "LineComment$"
        normal! ^w    " Can enhance this with something more general (no need tho)
        startinsert
    else
        call feedkeys('I', 'n')
    endif
endfun

nnoremap I :call SmartInsert()<CR>
w8biq8rn

w8biq8rn2#

您可以保持这样的Map,将光标移动到/之后的第一个单词

nmap <leader>I F/wi

下面是一个小的demo:

(来源:gfycat.com

nbysray5

nbysray53#

正如我在评论中所暗示的,这是lua/treesitter解决方案!

-- http://stackoverflow.com/a/22282505/340947
    local is_comment_ts_hl = function()
      local hl = require'nvim-treesitter-playground.hl-info'.get_treesitter_hl()
      -- loop
      for _, v in ipairs(hl) do
        -- if any contain 'comment': typical values seen are: { "* **@error**", "* **@comment**", "* **@spell**", "* **@spell**" }
        if string.find(v, 'comment') then
          return true
        end
      end
      return false
    end
    
    _G.smart_insert_start_of_line = function()
      if is_comment_ts_hl() then
        vim.cmd[[normal! ^w]]
        vim.cmd[[startinsert]]
      else
        vim.api.nvim_feedkeys('I', 'n', true)
      end
    end
    
    vim.api.nvim_set_keymap('n', 'I', ':lua smart_insert_start_of_line()<CR>', {noremap = true, silent = true})

相关问题