I sometimes make shortcuts for myself, which run some external command on the current buffer, such as

nnoremap <C-f> :%!clang-format -style=file<C-m>

which formats the buffer with clang's formatter.

However, this makes the cursor jump to the beginning of the file. Is there some way to avoid this? I understand it would be difficult finding the correct line after reformatting, but just the same line number would be good. I assume one could set and use marks in the mapping somehow, but any smarter solution would also be appreciated.

1 Answer 1


See :h getcurpos()

Basically there is an example:

        This can be used to save and restore the cursor position: >
            let save_cursor = getcurpos()
            call setpos('.', save_cursor)

So you can try it with smth like (untested):

nnoremap <C-f> :let save_cursor=getcurpos() <bar> %!clang-format -style=file <bar> call setpos('.', save_cursor)<CR>

Or make it a function:

nnoremap <C-f> :call Clang_format()<CR>

func! Clang_format()
    let save_cursor = getcurpos()
    exe '%!clang-format -style=file'
    call setpos('.', save_cursor)

  • 1
    I would rather suggest to use winsaveview()/winrestview() as this also prevents changes from the viewport. Oct 17, 2019 at 8:23
  • Awesome, that actually works perfectly.
    – oarfish
    Oct 17, 2019 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.