schmmd
schmmd

Reputation: 19468

Format XML and return to the same line in Vim

I would like to map F5 to format the current buffer using xmllint --format and return to the same line. It's easy to do just the formatting.

autocmd FileType xml map <F5> :w<CR>:silent %!xmllint --format -<CR>

I played around with returning to the same line for a while, and from the below snipped it should be obvious I don't know what I'm doing (doesn't work at all).

fun! XmlFormat()
  let @`\" = line(".")
  w<CR>
  silent %!xmllint --format -<CR>
  normal! g`\"
endfun
autocmd FileType xml map <F5> :call XmlFormat()<CR>

Do I need to store the present line in a buffer, or can I use a variable? How can I execute an external command within a function? Lastly, what's the best way to jump to a line number that is stored in a variable?

Upvotes: 0

Views: 435

Answers (1)

lucapette
lucapette

Reputation: 20724

You could use a mapping like:

nnoremap <f5> mmgg=G`m

It uses a mark motion and the = filter command. You could use xmllint setting the equalprg option. I wrote an article about this mapping here if you want a more detailed description.

Upvotes: 4

Related Questions