在 Vim 中,当我在 C++ 文件中键入分号时如何自动格式化当前行

In Vim, how to auto format current line when i typed semicolon in c++ files

例如:当前行是

int i=0

在我输入分号后,

int i = 0;

您需要 ; 上的 inoremap(并且仅限于当前缓冲区 -- :h :map-<buffer>)。在映射中,您必须为(准确地?)一个 = 符号解析当前行。重新格式化并确保将光标移回。

陷阱:

  • 映射应该可以重做吗?在这种情况下,您必须根据需要多次使用 <c-g>U<left><right> 移动光标。否则,简单地使用 getline() + substitute() + setline() 就可以了(实际上非​​常简单)-> :call setline('.', substitute(getline('.'), '\s*[<>!=]\?=\s*', ' = ', 'g')).
  • 如果 UTF-8 字符可以像 auto head = "tête";, you won't be able to usestrlen()` 那样出现。

请注意,clang-format 可能已经能够执行此类操作——但我不能保证它允许生成可重新执行的序列。

" rtp/ftplugin/c/c_reformat_on_semincolon.vim
" The reodable version.
function! s:semicolon() abort
  " let suppose the ';' is at the end of the line... 
  " and that there aren't multiple instructions of the same line
  let res = ''
  let line = getline('.')
  let missing_before = match(line, '\V\S=')
  let c = col('.') - 1
  if missing_before >= 0
     " prefer lh-vim-lib lh#encoding#strlen(line[missing_before : c])
     let offset = c - missing_before " +/- 1 ?
     let res .= repeat("\<c-g>U\<right>", offset)
           \ . ' '
     if line =~ '\V=\S'
         let res .= "\<c-g>U\<left> "
         let offset -= 1 " or 2 ?
     endif
     " let offset +/-= 1 ??
  else
     let offset = c - missing_after" +/- 1 ?
     let res .= repeat("\<c-g>U\<right>", offset)
           \ .  ' '
  endif
  let res .=  repeat("\<c-g>U\<left> ", offset)
  return res
endfunction

inoremap <buffer> ; <c-r>=<sid>semicolon()<cr>

请注意,此代码完全未经测试。您必须调整偏移量,并且可能会修复逻辑。