1

I have read Vim indent xml file and Indenting entire file in Vim without leaving current cursor location, but I want to something slightly different:

  • Can I use vim to indent an entire XML file but without changing the file. The only thing that should change is the representation, but not the file itself.

For those interested: I work with books in xml format. If the file is changed, this is usually by adding tabs and/or spaces. This messes up my data (because there might actually be tabs or spaces in the text itself).

Community
  • 1
  • 1
Private
  • 2,626
  • 1
  • 22
  • 39

2 Answers2

1

You have some options:

Change tab width

If your XML has Tab-based indent, you can change the visual appearance of the indent by changing the 'tabstop' value. This doesn't affect the physical <Tab> characters in the file at all.

Pre-/Post-process

You can change the amount of indent after reading, and undo that shortly before the write. Here's an example that halves / doubles spaces:

:autocmd BufReadPost,BufWritePost  * %substitute/^\( \+\)\1/\1/e
:autocmd BufWritePre               * %substitute/^ \+/&&/e
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324
  • The files are not files with 'tab-based' indent. They are just strings of XML that is unindented. Good suggestion, though, but it won't work here. – Private Mar 16 '15 at 20:12
  • Well, you can modify the `:autocmd`s to indent (e.g. via `:normal! gg=G`) after read, and drop all indent `%s/^\s\+//e` before write. – Ingo Karkat Mar 16 '15 at 20:59
1

In Vim, all your editing is done on a buffer, the internal representation of your file. As long as you don't write your changes to disk, your file stays untouched.

But, if you really don't want to take that risk… work on a copy.

romainl
  • 186,200
  • 21
  • 280
  • 313
  • I want to be able to make changes to the file. – Private Mar 16 '15 at 20:11
  • I mean, write to the file when I am done *without* changing the file's initial indentation (thus reverting back any changes related to indentation). – Private Mar 16 '15 at 21:07