为了解决vim的文件格式问题,我简单地编写了一个函数:
function FileFormat()
let cursorLine = col(".")
let filetype = &filetype
if filetype == 'json'
%!jq .
execute cursorLine
elseif filetype == 'cpp'
%!astyle --style=attach --pad-oper --lineend=linux -N -C -L -xw -xW -w
execute cursorLine
else
echo "Formatting of " . filetype . " files is not currently supported."
endif
endfunction
并为这个功能映射一个快捷键:
:nnoremap <C-f> :call FileFormat()<cr>
但我发现,格式化文件后,光标仍然位于行的开头。我知道这是因为当neovim进入命令模式时,光标消失了,导致col((函数无法获得有效的行号。
有其他办法解决这个问题吗?
neovim版本:0.6.1
原因是我使用了错误的函数,我不应该使用col
函数,我应该通过line(".")
获取光标行号,此函数不会受到模式切换的影响。