24

I would like Vim to help me indent my XML files like my C code. However, when I use

gg=G

It just sets everything to the left. Do I need to designate a syntax? Is XML recognized as a language?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
IslandCow
  • 3,412
  • 3
  • 19
  • 24

3 Answers3

27

Put

filetype plugin indent on

in your .vimrc to have Vim automatically identify .xml files as xml. You might need to put

set nocompatible

before that.

If the file extension is not .xml, you can make Vim threat it like xml by using

:set filetype=xml

After you do that, Vim's autoindention (and syntax highlighting, and omnicomplete (that in xml just closes tags, but that's still something)) will work properly for xml.

gvlasov
  • 18,638
  • 21
  • 74
  • 110
Idan Arye
  • 12,402
  • 5
  • 49
  • 68
  • 1
    Running Vim in compatible mode is like running old vi... which is kind of the point of compatible mode, but it's just sad that that's the default. – Idan Arye Sep 29 '11 at 18:05
  • 1
    If you are editing FXML in javaFX, the `:set filetype=xml` command brings blessed syntax coloring to your file. Sweet! – ncmathsadist Jan 22 '16 at 15:43
  • or shorter `:setf xml` (found somewhere and it works for me) – tomorrow Mar 23 '23 at 21:04
6

Yep, :set syntax=xml should work. In vim 7.3, this sets :set indentexpr=XmlIndentGet(v:lnum,1).

If you've got a one-line file, you may need to :%s/\(<[^>]*>\)/\1\r/g, to insert newlines after every tag (or split it differently).

Then, gg=G should work.

nobody
  • 4,074
  • 1
  • 23
  • 33
  • I'm running a pretty old version of Fedora Core :( Stuck with vim 7.2, so I don't get auto indent. – IslandCow Sep 29 '11 at 17:54
  • @IslandCow I don't think that this matters. You just need to get `indent/xml.vim` from vim-7.3 runtime if you don't have `XmlIndentGet` function. I don't see anything vim-7.3-specific in this file. – ZyX Sep 29 '11 at 19:57
  • XML syntax seems to work fine in 7.2 on Windows. As a user you shouldn't have to worry about the indentexpr, as long as syntax is set right you should be fine. (Although you might try `:set filetype=xml` instead, too.) – dash-tom-bang Oct 03 '11 at 21:42
  • 1
    For a slightly easier command for individual line splitting, I use: :s/>/>\r/g i.e. substitute(:s) for every >(xml end tag) a >(xml end tag)with a newline(>\r) (g stands for global (in the line)). This will leave a new line after each end tag that already had a new line but is fast and easy to remember. – Daniel Apr 03 '13 at 01:01
  • 1
    I don't want newlines after EVERY tag, just the CLOSING tags. Tweaked regex: `:%s/\(<\/[^>]*>\)/\1\r/g` – roblogic Apr 07 '15 at 23:37
0

add this line to your .vimrc file:

:map <Space>fx :%s/\ </\r</g<cr>:%s/\ android/\randroid/g<cr>:g/^$/d<cr>gg=G`

to format click space fx

challenger
  • 2,184
  • 1
  • 18
  • 25