Indenting entire file in Vim without leaving curre

2019-01-24 11:26发布

I already know that gg=G can indent the entire file on Vim. But this will make me go to the beginning of the file after indent. How can I indent the entire file and maintain the cursor at the same position?

4条回答
We Are One
2楼-- · 2019-01-24 11:41

You can set a bookmark for the current position with the m command followed by a letter. Then after you run the indent command, you can go back to that bookmark with the ` (backtick) command followed by the same letter.

查看更多
混吃等死
3楼-- · 2019-01-24 12:03

In a similar spirit to Alex's answer I use the following mapping in vimrc.

nnoremap g= :let b:PlugView=winsaveview()<CR>gg=G:call winrestview(b:PlugView) <CR>:echo "file indented"<CR>

by pressing g= in normal mode the whole buffer is indented, and the scroll/cursor position is retained.

查看更多
我命由我不由天
4楼-- · 2019-01-24 12:05

See :h ''

This will get you back to the first char on the line you start on:

gg=G''

and this will get you back to the starting line and the starting column:

gg=G``

I assume the second version, with the backtick, is the one you want. In practice I usually just use the double apostrophe version, since the backtick is hard to access on my keyboard.

查看更多
可以哭但决不认输i
5楼-- · 2019-01-24 12:06

Add this to your .vimrc

function! Preserve(command)
  " Preparation: save last search, and cursor position.
  let _s=@/
  let l = line(".")
  let c = col(".")
  " Do the business:
  execute a:command
  " Clean up: restore previous search history, and cursor position
  let @/=_s
  call cursor(l, c)
endfunction
nmap <leader>> :call Preserve("normal gg>G")<CR>

You can also use this on any other command you want, just change the argument to the preserve function. Idea taken from here: http://vimcasts.org/episodes/tidying-whitespace/

查看更多
登录 后发表回答