html.vim 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. " Vim indent script for HTML
  2. " Maintainer: Bram Moolenaar
  3. " Original Author: Andy Wokula <anwoku@yahoo.de>
  4. " Last Change: 2022 Jan 31
  5. " Version: 1.0 "{{{
  6. " Description: HTML indent script with cached state for faster indenting on a
  7. " range of lines.
  8. " Supports template systems through hooks.
  9. " Supports Closure stylesheets.
  10. "
  11. " Credits:
  12. " indent/html.vim (2006 Jun 05) from J. Zellner
  13. " indent/css.vim (2006 Dec 20) from N. Weibull
  14. "
  15. " History:
  16. " 2014 June (v1.0) overhaul (Bram)
  17. " 2012 Oct 21 (v0.9) added support for shiftwidth()
  18. " 2011 Sep 09 (v0.8) added HTML5 tags (thx to J. Zuckerman)
  19. " 2008 Apr 28 (v0.6) revised customization
  20. " 2008 Mar 09 (v0.5) fixed 'indk' issue (thx to C.J. Robinson)
  21. "}}}
  22. " Init Folklore, check user settings (2nd time ++)
  23. if exists("b:did_indent") "{{{
  24. finish
  25. endif
  26. " Load the Javascript indent script first, it defines GetJavascriptIndent().
  27. " Undo the rest.
  28. " Load base python indent.
  29. if !exists('*GetJavascriptIndent')
  30. runtime! indent/javascript.vim
  31. endif
  32. let b:did_indent = 1
  33. setlocal indentexpr=HtmlIndent()
  34. setlocal indentkeys=o,O,<Return>,<>>,{,},!^F
  35. " Needed for % to work when finding start/end of a tag.
  36. setlocal matchpairs+=<:>
  37. let b:undo_indent = "setlocal inde< indk<"
  38. " b:hi_indent keeps state to speed up indenting consecutive lines.
  39. let b:hi_indent = {"lnum": -1}
  40. """""" Code below this is loaded only once. """""
  41. if exists("*HtmlIndent") && !exists('g:force_reload_html')
  42. call HtmlIndent_CheckUserSettings()
  43. finish
  44. endif
  45. " Allow for line continuation below.
  46. let s:cpo_save = &cpo
  47. set cpo-=C
  48. "}}}
  49. " Pattern to match the name of a tag, including custom elements.
  50. let s:tagname = '\w\+\(-\w\+\)*'
  51. " Check and process settings from b:html_indent and g:html_indent... variables.
  52. " Prefer using buffer-local settings over global settings, so that there can
  53. " be defaults for all HTML files and exceptions for specific types of HTML
  54. " files.
  55. func HtmlIndent_CheckUserSettings()
  56. "{{{
  57. let inctags = ''
  58. if exists("b:html_indent_inctags")
  59. let inctags = b:html_indent_inctags
  60. elseif exists("g:html_indent_inctags")
  61. let inctags = g:html_indent_inctags
  62. endif
  63. let b:hi_tags = {}
  64. if len(inctags) > 0
  65. call s:AddITags(b:hi_tags, split(inctags, ","))
  66. endif
  67. let autotags = ''
  68. if exists("b:html_indent_autotags")
  69. let autotags = b:html_indent_autotags
  70. elseif exists("g:html_indent_autotags")
  71. let autotags = g:html_indent_autotags
  72. endif
  73. let b:hi_removed_tags = {}
  74. if len(autotags) > 0
  75. call s:RemoveITags(b:hi_removed_tags, split(autotags, ","))
  76. endif
  77. " Syntax names indicating being inside a string of an attribute value.
  78. let string_names = []
  79. if exists("b:html_indent_string_names")
  80. let string_names = b:html_indent_string_names
  81. elseif exists("g:html_indent_string_names")
  82. let string_names = g:html_indent_string_names
  83. endif
  84. let b:hi_insideStringNames = ['htmlString']
  85. if len(string_names) > 0
  86. for s in string_names
  87. call add(b:hi_insideStringNames, s)
  88. endfor
  89. endif
  90. " Syntax names indicating being inside a tag.
  91. let tag_names = []
  92. if exists("b:html_indent_tag_names")
  93. let tag_names = b:html_indent_tag_names
  94. elseif exists("g:html_indent_tag_names")
  95. let tag_names = g:html_indent_tag_names
  96. endif
  97. let b:hi_insideTagNames = ['htmlTag', 'htmlScriptTag']
  98. if len(tag_names) > 0
  99. for s in tag_names
  100. call add(b:hi_insideTagNames, s)
  101. endfor
  102. endif
  103. let indone = {"zero": 0
  104. \,"auto": "indent(prevnonblank(v:lnum-1))"
  105. \,"inc": "b:hi_indent.blocktagind + shiftwidth()"}
  106. let script1 = ''
  107. if exists("b:html_indent_script1")
  108. let script1 = b:html_indent_script1
  109. elseif exists("g:html_indent_script1")
  110. let script1 = g:html_indent_script1
  111. endif
  112. if len(script1) > 0
  113. let b:hi_js1indent = get(indone, script1, indone.zero)
  114. else
  115. let b:hi_js1indent = 0
  116. endif
  117. let style1 = ''
  118. if exists("b:html_indent_style1")
  119. let style1 = b:html_indent_style1
  120. elseif exists("g:html_indent_style1")
  121. let style1 = g:html_indent_style1
  122. endif
  123. if len(style1) > 0
  124. let b:hi_css1indent = get(indone, style1, indone.zero)
  125. else
  126. let b:hi_css1indent = 0
  127. endif
  128. if !exists('b:html_indent_line_limit')
  129. if exists('g:html_indent_line_limit')
  130. let b:html_indent_line_limit = g:html_indent_line_limit
  131. else
  132. let b:html_indent_line_limit = 200
  133. endif
  134. endif
  135. if exists('b:html_indent_attribute')
  136. let b:hi_attr_indent = b:html_indent_attribute
  137. elseif exists('g:html_indent_attribute')
  138. let b:hi_attr_indent = g:html_indent_attribute
  139. else
  140. let b:hi_attr_indent = 2
  141. endif
  142. endfunc "}}}
  143. " Init Script Vars
  144. "{{{
  145. let b:hi_lasttick = 0
  146. let b:hi_newstate = {}
  147. let s:countonly = 0
  148. "}}}
  149. " Fill the s:indent_tags dict with known tags.
  150. " The key is "tagname" or "/tagname". {{{
  151. " The value is:
  152. " 1 opening tag
  153. " 2 "pre"
  154. " 3 "script"
  155. " 4 "style"
  156. " 5 comment start
  157. " 6 conditional comment start
  158. " -1 closing tag
  159. " -2 "/pre"
  160. " -3 "/script"
  161. " -4 "/style"
  162. " -5 comment end
  163. " -6 conditional comment end
  164. let s:indent_tags = {}
  165. let s:endtags = [0,0,0,0,0,0,0] " long enough for the highest index
  166. "}}}
  167. " Add a list of tag names for a pair of <tag> </tag> to "tags".
  168. func s:AddITags(tags, taglist)
  169. "{{{
  170. for itag in a:taglist
  171. let a:tags[itag] = 1
  172. let a:tags['/' . itag] = -1
  173. endfor
  174. endfunc "}}}
  175. " Take a list of tag name pairs that are not to be used as tag pairs.
  176. func s:RemoveITags(tags, taglist)
  177. "{{{
  178. for itag in a:taglist
  179. let a:tags[itag] = 1
  180. let a:tags['/' . itag] = 1
  181. endfor
  182. endfunc "}}}
  183. " Add a block tag, that is a tag with a different kind of indenting.
  184. func s:AddBlockTag(tag, id, ...)
  185. "{{{
  186. if !(a:id >= 2 && a:id < len(s:endtags))
  187. echoerr 'AddBlockTag ' . a:id
  188. return
  189. endif
  190. let s:indent_tags[a:tag] = a:id
  191. if a:0 == 0
  192. let s:indent_tags['/' . a:tag] = -a:id
  193. let s:endtags[a:id] = "</" . a:tag . ">"
  194. else
  195. let s:indent_tags[a:1] = -a:id
  196. let s:endtags[a:id] = a:1
  197. endif
  198. endfunc "}}}
  199. " Add known tag pairs.
  200. " Self-closing tags and tags that are sometimes {{{
  201. " self-closing (e.g., <p>) are not here (when encountering </p> we can find
  202. " the matching <p>, but not the other way around).
  203. " Known self-closing tags: " 'p', 'img', 'source', 'area', 'keygen', 'track',
  204. " 'wbr'.
  205. " Old HTML tags:
  206. call s:AddITags(s:indent_tags, [
  207. \ 'a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big',
  208. \ 'blockquote', 'body', 'button', 'caption', 'center', 'cite', 'code',
  209. \ 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', 'font',
  210. \ 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'html',
  211. \ 'i', 'iframe', 'ins', 'kbd', 'label', 'legend', 'li',
  212. \ 'map', 'menu', 'noframes', 'noscript', 'object', 'ol',
  213. \ 'optgroup', 'q', 's', 'samp', 'select', 'small', 'span', 'strong', 'sub',
  214. \ 'sup', 'table', 'textarea', 'title', 'tt', 'u', 'ul', 'var', 'th', 'td',
  215. \ 'tr', 'tbody', 'tfoot', 'thead'])
  216. " New HTML5 elements:
  217. call s:AddITags(s:indent_tags, [
  218. \ 'article', 'aside', 'audio', 'bdi', 'canvas', 'command', 'data',
  219. \ 'datalist', 'details', 'dialog', 'embed', 'figcaption', 'figure',
  220. \ 'footer', 'header', 'hgroup', 'main', 'mark', 'meter', 'nav', 'output',
  221. \ 'picture', 'progress', 'rp', 'rt', 'ruby', 'section', 'summary',
  222. \ 'svg', 'time', 'video'])
  223. " Tags added for web components:
  224. call s:AddITags(s:indent_tags, [
  225. \ 'content', 'shadow', 'template'])
  226. "}}}
  227. " Add Block Tags: these contain alien content
  228. "{{{
  229. call s:AddBlockTag('pre', 2)
  230. call s:AddBlockTag('script', 3)
  231. call s:AddBlockTag('style', 4)
  232. call s:AddBlockTag('<!--', 5, '-->')
  233. call s:AddBlockTag('<!--[', 6, '![endif]-->')
  234. "}}}
  235. " Return non-zero when "tagname" is an opening tag, not being a block tag, for
  236. " which there should be a closing tag. Can be used by scripts that include
  237. " HTML indenting.
  238. func HtmlIndent_IsOpenTag(tagname)
  239. "{{{
  240. if get(s:indent_tags, a:tagname) == 1
  241. return 1
  242. endif
  243. return get(b:hi_tags, a:tagname) == 1
  244. endfunc "}}}
  245. " Get the value for "tagname", taking care of buffer-local tags.
  246. func s:get_tag(tagname)
  247. "{{{
  248. let i = get(s:indent_tags, a:tagname)
  249. if (i == 1 || i == -1) && get(b:hi_removed_tags, a:tagname) != 0
  250. return 0
  251. endif
  252. if i == 0
  253. let i = get(b:hi_tags, a:tagname)
  254. endif
  255. return i
  256. endfunc "}}}
  257. " Count the number of start and end tags in "text".
  258. func s:CountITags(text)
  259. "{{{
  260. " Store the result in s:curind and s:nextrel.
  261. let s:curind = 0 " relative indent steps for current line [unit &sw]:
  262. let s:nextrel = 0 " relative indent steps for next line [unit &sw]:
  263. let s:block = 0 " assume starting outside of a block
  264. let s:countonly = 1 " don't change state
  265. call substitute(a:text, '<\zs/\=' . s:tagname . '\>\|<!--\[\|\[endif\]-->\|<!--\|-->', '\=s:CheckTag(submatch(0))', 'g')
  266. let s:countonly = 0
  267. endfunc "}}}
  268. " Count the number of start and end tags in text.
  269. func s:CountTagsAndState(text)
  270. "{{{
  271. " Store the result in s:curind and s:nextrel. Update b:hi_newstate.block.
  272. let s:curind = 0 " relative indent steps for current line [unit &sw]:
  273. let s:nextrel = 0 " relative indent steps for next line [unit &sw]:
  274. let s:block = b:hi_newstate.block
  275. let tmp = substitute(a:text, '<\zs/\=' . s:tagname . '\>\|<!--\[\|\[endif\]-->\|<!--\|-->', '\=s:CheckTag(submatch(0))', 'g')
  276. if s:block == 3
  277. let b:hi_newstate.scripttype = s:GetScriptType(matchstr(tmp, '\C.*<SCRIPT\>\zs[^>]*'))
  278. endif
  279. let b:hi_newstate.block = s:block
  280. endfunc "}}}
  281. " Used by s:CountITags() and s:CountTagsAndState().
  282. func s:CheckTag(itag)
  283. "{{{
  284. " Returns an empty string or "SCRIPT".
  285. " a:itag can be "tag" or "/tag" or "<!--" or "-->"
  286. if (s:CheckCustomTag(a:itag))
  287. return ""
  288. endif
  289. let ind = s:get_tag(a:itag)
  290. if ind == -1
  291. " closing tag
  292. if s:block != 0
  293. " ignore itag within a block
  294. return ""
  295. endif
  296. if s:nextrel == 0
  297. let s:curind -= 1
  298. else
  299. let s:nextrel -= 1
  300. endif
  301. elseif ind == 1
  302. " opening tag
  303. if s:block != 0
  304. return ""
  305. endif
  306. let s:nextrel += 1
  307. elseif ind != 0
  308. " block-tag (opening or closing)
  309. return s:CheckBlockTag(a:itag, ind)
  310. " else ind==0 (other tag found): keep indent
  311. endif
  312. return ""
  313. endfunc "}}}
  314. " Used by s:CheckTag(). Returns an empty string or "SCRIPT".
  315. func s:CheckBlockTag(blocktag, ind)
  316. "{{{
  317. if a:ind > 0
  318. " a block starts here
  319. if s:block != 0
  320. " already in a block (nesting) - ignore
  321. " especially ignore comments after other blocktags
  322. return ""
  323. endif
  324. let s:block = a:ind " block type
  325. if s:countonly
  326. return ""
  327. endif
  328. let b:hi_newstate.blocklnr = v:lnum
  329. " save allover indent for the endtag
  330. let b:hi_newstate.blocktagind = b:hi_indent.baseindent + (s:nextrel + s:curind) * shiftwidth()
  331. if a:ind == 3
  332. return "SCRIPT" " all except this must be lowercase
  333. " line is to be checked again for the type attribute
  334. endif
  335. else
  336. let s:block = 0
  337. " we get here if starting and closing a block-tag on the same line
  338. endif
  339. return ""
  340. endfunc "}}}
  341. " Used by s:CheckTag().
  342. func s:CheckCustomTag(ctag)
  343. "{{{
  344. " Returns 1 if ctag is the tag for a custom element, 0 otherwise.
  345. " a:ctag can be "tag" or "/tag" or "<!--" or "-->"
  346. let pattern = '\%\(\w\+-\)\+\w\+'
  347. if match(a:ctag, pattern) == -1
  348. return 0
  349. endif
  350. if matchstr(a:ctag, '\/\ze.\+') == "/"
  351. " closing tag
  352. if s:block != 0
  353. " ignore ctag within a block
  354. return 1
  355. endif
  356. if s:nextrel == 0
  357. let s:curind -= 1
  358. else
  359. let s:nextrel -= 1
  360. endif
  361. else
  362. " opening tag
  363. if s:block != 0
  364. return 1
  365. endif
  366. let s:nextrel += 1
  367. endif
  368. return 1
  369. endfunc "}}}
  370. " Return the <script> type: either "javascript" or ""
  371. func s:GetScriptType(str)
  372. "{{{
  373. if a:str == "" || a:str =~ "java"
  374. return "javascript"
  375. else
  376. return ""
  377. endif
  378. endfunc "}}}
  379. " Look back in the file, starting at a:lnum - 1, to compute a state for the
  380. " start of line a:lnum. Return the new state.
  381. func s:FreshState(lnum)
  382. "{{{
  383. " A state is to know ALL relevant details about the
  384. " lines 1..a:lnum-1, initial calculating (here!) can be slow, but updating is
  385. " fast (incremental).
  386. " TODO: this should be split up in detecting the block type and computing the
  387. " indent for the block type, so that when we do not know the indent we do
  388. " not need to clear the whole state and re-detect the block type again.
  389. " State:
  390. " lnum last indented line == prevnonblank(a:lnum - 1)
  391. " block = 0 a:lnum located within special tag: 0:none, 2:<pre>,
  392. " 3:<script>, 4:<style>, 5:<!--, 6:<!--[
  393. " baseindent use this indent for line a:lnum as a start - kind of
  394. " autoindent (if block==0)
  395. " scripttype = '' type attribute of a script tag (if block==3)
  396. " blocktagind indent for current opening (get) and closing (set)
  397. " blocktag (if block!=0)
  398. " blocklnr lnum of starting blocktag (if block!=0)
  399. " inattr line {lnum} starts with attributes of a tag
  400. let state = {}
  401. let state.lnum = prevnonblank(a:lnum - 1)
  402. let state.scripttype = ""
  403. let state.blocktagind = -1
  404. let state.block = 0
  405. let state.baseindent = 0
  406. let state.blocklnr = 0
  407. let state.inattr = 0
  408. if state.lnum == 0
  409. return state
  410. endif
  411. " Heuristic:
  412. " remember startline state.lnum
  413. " look back for <pre, </pre, <script, </script, <style, </style tags
  414. " remember stopline
  415. " if opening tag found,
  416. " assume a:lnum within block
  417. " else
  418. " look back in result range (stopline, startline) for comment
  419. " \ delimiters (<!--, -->)
  420. " if comment opener found,
  421. " assume a:lnum within comment
  422. " else
  423. " assume usual html for a:lnum
  424. " if a:lnum-1 has a closing comment
  425. " look back to get indent of comment opener
  426. " FI
  427. " look back for a blocktag
  428. let stopline2 = v:lnum + 1
  429. if has_key(b:hi_indent, 'block') && b:hi_indent.block > 5
  430. let [stopline2, stopcol2] = searchpos('<!--', 'bnW')
  431. endif
  432. let [stopline, stopcol] = searchpos('\c<\zs\/\=\%(pre\>\|script\>\|style\>\)', "bnW")
  433. if stopline > 0 && stopline < stopline2
  434. " ugly ... why isn't there searchstr()
  435. let tagline = tolower(getline(stopline))
  436. let blocktag = matchstr(tagline, '\/\=\%(pre\>\|script\>\|style\>\)', stopcol - 1)
  437. if blocktag[0] != "/"
  438. " opening tag found, assume a:lnum within block
  439. let state.block = s:indent_tags[blocktag]
  440. if state.block == 3
  441. let state.scripttype = s:GetScriptType(matchstr(tagline, '\>[^>]*', stopcol))
  442. endif
  443. let state.blocklnr = stopline
  444. " check preceding tags in the line:
  445. call s:CountITags(tagline[: stopcol-2])
  446. let state.blocktagind = indent(stopline) + (s:curind + s:nextrel) * shiftwidth()
  447. return state
  448. elseif stopline == state.lnum
  449. " handle special case: previous line (= state.lnum) contains a
  450. " closing blocktag which is preceded by line-noise;
  451. " blocktag == "/..."
  452. let swendtag = match(tagline, '^\s*</') >= 0
  453. if !swendtag
  454. let [bline, bcol] = searchpos('<'.blocktag[1:].'\>', "bnW")
  455. call s:CountITags(tolower(getline(bline)[: bcol-2]))
  456. let state.baseindent = indent(bline) + (s:curind + s:nextrel) * shiftwidth()
  457. return state
  458. endif
  459. endif
  460. endif
  461. if stopline > stopline2
  462. let stopline = stopline2
  463. let stopcol = stopcol2
  464. endif
  465. " else look back for comment
  466. let [comlnum, comcol, found] = searchpos('\(<!--\[\)\|\(<!--\)\|-->', 'bpnW', stopline)
  467. if found == 2 || found == 3
  468. " comment opener found, assume a:lnum within comment
  469. let state.block = (found == 3 ? 5 : 6)
  470. let state.blocklnr = comlnum
  471. " check preceding tags in the line:
  472. call s:CountITags(tolower(getline(comlnum)[: comcol-2]))
  473. if found == 2
  474. let state.baseindent = b:hi_indent.baseindent
  475. endif
  476. let state.blocktagind = indent(comlnum) + (s:curind + s:nextrel) * shiftwidth()
  477. return state
  478. endif
  479. " else within usual HTML
  480. let text = tolower(getline(state.lnum))
  481. " Check a:lnum-1 for closing comment (we need indent from the opening line).
  482. " Not when other tags follow (might be --> inside a string).
  483. let comcol = stridx(text, '-->')
  484. if comcol >= 0 && match(text, '[<>]', comcol) <= 0
  485. call cursor(state.lnum, comcol + 1)
  486. let [comlnum, comcol] = searchpos('<!--', 'bW')
  487. if comlnum == state.lnum
  488. let text = text[: comcol-2]
  489. else
  490. let text = tolower(getline(comlnum)[: comcol-2])
  491. endif
  492. call s:CountITags(text)
  493. let state.baseindent = indent(comlnum) + (s:curind + s:nextrel) * shiftwidth()
  494. " TODO check tags that follow "-->"
  495. return state
  496. endif
  497. " Check if the previous line starts with end tag.
  498. let swendtag = match(text, '^\s*</') >= 0
  499. " If previous line ended in a closing tag, line up with the opening tag.
  500. if !swendtag && text =~ '</' . s:tagname . '\s*>\s*$'
  501. call cursor(state.lnum, 99999)
  502. normal! F<
  503. let start_lnum = HtmlIndent_FindStartTag()
  504. if start_lnum > 0
  505. let state.baseindent = indent(start_lnum)
  506. if col('.') > 2
  507. " check for tags before the matching opening tag.
  508. let text = getline(start_lnum)
  509. let swendtag = match(text, '^\s*</') >= 0
  510. call s:CountITags(text[: col('.') - 2])
  511. let state.baseindent += s:nextrel * shiftwidth()
  512. if !swendtag
  513. let state.baseindent += s:curind * shiftwidth()
  514. endif
  515. endif
  516. return state
  517. endif
  518. endif
  519. " Else: no comments. Skip backwards to find the tag we're inside.
  520. let [state.lnum, found] = HtmlIndent_FindTagStart(state.lnum)
  521. " Check if that line starts with end tag.
  522. let text = getline(state.lnum)
  523. let swendtag = match(text, '^\s*</') >= 0
  524. call s:CountITags(tolower(text))
  525. let state.baseindent = indent(state.lnum) + s:nextrel * shiftwidth()
  526. if !swendtag
  527. let state.baseindent += s:curind * shiftwidth()
  528. endif
  529. return state
  530. endfunc "}}}
  531. " Indent inside a <pre> block: Keep indent as-is.
  532. func s:Alien2()
  533. "{{{
  534. return -1
  535. endfunc "}}}
  536. " Return the indent inside a <script> block for javascript.
  537. func s:Alien3()
  538. "{{{
  539. let lnum = prevnonblank(v:lnum - 1)
  540. while lnum > 1 && getline(lnum) =~ '^\s*/[/*]'
  541. " Skip over comments to avoid that cindent() aligns with the <script> tag
  542. let lnum = prevnonblank(lnum - 1)
  543. endwhile
  544. if lnum < b:hi_indent.blocklnr
  545. " indent for <script> itself
  546. return b:hi_indent.blocktagind
  547. endif
  548. if lnum == b:hi_indent.blocklnr
  549. " indent for the first line after <script>
  550. return eval(b:hi_js1indent)
  551. endif
  552. if b:hi_indent.scripttype == "javascript"
  553. " indent for further lines
  554. return GetJavascriptIndent()
  555. else
  556. return -1
  557. endif
  558. endfunc "}}}
  559. " Return the indent inside a <style> block.
  560. func s:Alien4()
  561. "{{{
  562. if prevnonblank(v:lnum-1) == b:hi_indent.blocklnr
  563. " indent for first content line
  564. return eval(b:hi_css1indent)
  565. endif
  566. return s:CSSIndent()
  567. endfunc "}}}
  568. " Indending inside a <style> block. Returns the indent.
  569. func s:CSSIndent()
  570. "{{{
  571. " This handles standard CSS and also Closure stylesheets where special lines
  572. " start with @.
  573. " When the line starts with '*' or the previous line starts with "/*"
  574. " and does not end in "*/", use C indenting to format the comment.
  575. " Adopted $VIMRUNTIME/indent/css.vim
  576. let curtext = getline(v:lnum)
  577. if curtext =~ '^\s*[*]'
  578. \ || (v:lnum > 1 && getline(v:lnum - 1) =~ '\s*/\*'
  579. \ && getline(v:lnum - 1) !~ '\*/\s*$')
  580. return cindent(v:lnum)
  581. endif
  582. let min_lnum = b:hi_indent.blocklnr
  583. let prev_lnum = s:CssPrevNonComment(v:lnum - 1, min_lnum)
  584. let [prev_lnum, found] = HtmlIndent_FindTagStart(prev_lnum)
  585. if prev_lnum <= min_lnum
  586. " Just below the <style> tag, indent for first content line after comments.
  587. return eval(b:hi_css1indent)
  588. endif
  589. " If the current line starts with "}" align with its match.
  590. if curtext =~ '^\s*}'
  591. call cursor(v:lnum, 1)
  592. try
  593. normal! %
  594. " Found the matching "{", align with it after skipping unfinished lines.
  595. let align_lnum = s:CssFirstUnfinished(line('.'), min_lnum)
  596. return indent(align_lnum)
  597. catch
  598. " can't find it, try something else, but it's most likely going to be
  599. " wrong
  600. endtry
  601. endif
  602. " add indent after {
  603. let brace_counts = HtmlIndent_CountBraces(prev_lnum)
  604. let extra = brace_counts.c_open * shiftwidth()
  605. let prev_text = getline(prev_lnum)
  606. let below_end_brace = prev_text =~ '}\s*$'
  607. " Search back to align with the first line that's unfinished.
  608. let align_lnum = s:CssFirstUnfinished(prev_lnum, min_lnum)
  609. " Handle continuation lines if aligning with previous line and not after a
  610. " "}".
  611. if extra == 0 && align_lnum == prev_lnum && !below_end_brace
  612. let prev_hasfield = prev_text =~ '^\s*[a-zA-Z0-9-]\+:'
  613. let prev_special = prev_text =~ '^\s*\(/\*\|@\)'
  614. if curtext =~ '^\s*\(/\*\|@\)'
  615. " if the current line is not a comment or starts with @ (used by template
  616. " systems) reduce indent if previous line is a continuation line
  617. if !prev_hasfield && !prev_special
  618. let extra = -shiftwidth()
  619. endif
  620. else
  621. let cur_hasfield = curtext =~ '^\s*[a-zA-Z0-9-]\+:'
  622. let prev_unfinished = s:CssUnfinished(prev_text)
  623. if prev_unfinished
  624. " Continuation line has extra indent if the previous line was not a
  625. " continuation line.
  626. let extra = shiftwidth()
  627. " Align with @if
  628. if prev_text =~ '^\s*@if '
  629. let extra = 4
  630. endif
  631. elseif cur_hasfield && !prev_hasfield && !prev_special
  632. " less indent below a continuation line
  633. let extra = -shiftwidth()
  634. endif
  635. endif
  636. endif
  637. if below_end_brace
  638. " find matching {, if that line starts with @ it's not the start of a rule
  639. " but something else from a template system
  640. call cursor(prev_lnum, 1)
  641. call search('}\s*$')
  642. try
  643. normal! %
  644. " Found the matching "{", align with it.
  645. let align_lnum = s:CssFirstUnfinished(line('.'), min_lnum)
  646. let special = getline(align_lnum) =~ '^\s*@'
  647. catch
  648. let special = 0
  649. endtry
  650. if special
  651. " do not reduce indent below @{ ... }
  652. if extra < 0
  653. let extra += shiftwidth()
  654. endif
  655. else
  656. let extra -= (brace_counts.c_close - (prev_text =~ '^\s*}')) * shiftwidth()
  657. endif
  658. endif
  659. " if no extra indent yet...
  660. if extra == 0
  661. if brace_counts.p_open > brace_counts.p_close
  662. " previous line has more ( than ): add a shiftwidth
  663. let extra = shiftwidth()
  664. elseif brace_counts.p_open < brace_counts.p_close
  665. " previous line has more ) than (: subtract a shiftwidth
  666. let extra = -shiftwidth()
  667. endif
  668. endif
  669. return indent(align_lnum) + extra
  670. endfunc "}}}
  671. " Inside <style>: Whether a line is unfinished.
  672. " tag:
  673. " tag: blah
  674. " tag: blah &&
  675. " tag: blah ||
  676. func s:CssUnfinished(text)
  677. "{{{
  678. return a:text =~ '\(||\|&&\|:\|\k\)\s*$'
  679. endfunc "}}}
  680. " Search back for the first unfinished line above "lnum".
  681. func s:CssFirstUnfinished(lnum, min_lnum)
  682. "{{{
  683. let align_lnum = a:lnum
  684. while align_lnum > a:min_lnum && s:CssUnfinished(getline(align_lnum - 1))
  685. let align_lnum -= 1
  686. endwhile
  687. return align_lnum
  688. endfunc "}}}
  689. " Find the non-empty line at or before "lnum" that is not a comment.
  690. func s:CssPrevNonComment(lnum, stopline)
  691. "{{{
  692. " caller starts from a line a:lnum + 1 that is not a comment
  693. let lnum = prevnonblank(a:lnum)
  694. while 1
  695. let ccol = match(getline(lnum), '\*/')
  696. if ccol < 0
  697. " No comment end thus it's something else.
  698. return lnum
  699. endif
  700. call cursor(lnum, ccol + 1)
  701. " Search back for the /* that starts the comment
  702. let lnum = search('/\*', 'bW', a:stopline)
  703. if indent(".") == virtcol(".") - 1
  704. " The found /* is at the start of the line. Now go back to the line
  705. " above it and again check if it is a comment.
  706. let lnum = prevnonblank(lnum - 1)
  707. else
  708. " /* is after something else, thus it's not a comment line.
  709. return lnum
  710. endif
  711. endwhile
  712. endfunc "}}}
  713. " Check the number of {} and () in line "lnum". Return a dict with the counts.
  714. func HtmlIndent_CountBraces(lnum)
  715. "{{{
  716. let brs = substitute(getline(a:lnum), '[''"].\{-}[''"]\|/\*.\{-}\*/\|/\*.*$\|[^{}()]', '', 'g')
  717. let c_open = 0
  718. let c_close = 0
  719. let p_open = 0
  720. let p_close = 0
  721. for brace in split(brs, '\zs')
  722. if brace == "{"
  723. let c_open += 1
  724. elseif brace == "}"
  725. if c_open > 0
  726. let c_open -= 1
  727. else
  728. let c_close += 1
  729. endif
  730. elseif brace == '('
  731. let p_open += 1
  732. elseif brace == ')'
  733. if p_open > 0
  734. let p_open -= 1
  735. else
  736. let p_close += 1
  737. endif
  738. endif
  739. endfor
  740. return {'c_open': c_open,
  741. \ 'c_close': c_close,
  742. \ 'p_open': p_open,
  743. \ 'p_close': p_close}
  744. endfunc "}}}
  745. " Return the indent for a comment: <!-- -->
  746. func s:Alien5()
  747. "{{{
  748. let curtext = getline(v:lnum)
  749. if curtext =~ '^\s*\zs-->'
  750. " current line starts with end of comment, line up with comment start.
  751. call cursor(v:lnum, 0)
  752. let lnum = search('<!--', 'b')
  753. if lnum > 0
  754. " TODO: what if <!-- is not at the start of the line?
  755. return indent(lnum)
  756. endif
  757. " Strange, can't find it.
  758. return -1
  759. endif
  760. let prevlnum = prevnonblank(v:lnum - 1)
  761. let prevtext = getline(prevlnum)
  762. let idx = match(prevtext, '^\s*\zs<!--')
  763. if idx >= 0
  764. " just below comment start, add a shiftwidth
  765. return indent(prevlnum) + shiftwidth()
  766. endif
  767. " Some files add 4 spaces just below a TODO line. It's difficult to detect
  768. " the end of the TODO, so let's not do that.
  769. " Align with the previous non-blank line.
  770. return indent(prevlnum)
  771. endfunc "}}}
  772. " Return the indent for conditional comment: <!--[ ![endif]-->
  773. func s:Alien6()
  774. "{{{
  775. let curtext = getline(v:lnum)
  776. if curtext =~ '\s*\zs<!\[endif\]-->'
  777. " current line starts with end of comment, line up with comment start.
  778. let lnum = search('<!--', 'bn')
  779. if lnum > 0
  780. return indent(lnum)
  781. endif
  782. endif
  783. return b:hi_indent.baseindent + shiftwidth()
  784. endfunc "}}}
  785. " When the "lnum" line ends in ">" find the line containing the matching "<".
  786. func HtmlIndent_FindTagStart(lnum)
  787. "{{{
  788. " Avoids using the indent of a continuation line.
  789. " Moves the cursor.
  790. " Return two values:
  791. " - the matching line number or "lnum".
  792. " - a flag indicating whether we found the end of a tag.
  793. " This method is global so that HTML-like indenters can use it.
  794. " To avoid matching " > " or " < " inside a string require that the opening
  795. " "<" is followed by a word character and the closing ">" comes after a
  796. " non-white character.
  797. let idx = match(getline(a:lnum), '\S>\s*$')
  798. if idx > 0
  799. call cursor(a:lnum, idx)
  800. let lnum = searchpair('<\w', '' , '\S>', 'bW', '', max([a:lnum - b:html_indent_line_limit, 0]))
  801. if lnum > 0
  802. return [lnum, 1]
  803. endif
  804. endif
  805. return [a:lnum, 0]
  806. endfunc "}}}
  807. " Find the unclosed start tag from the current cursor position.
  808. func HtmlIndent_FindStartTag()
  809. "{{{
  810. " The cursor must be on or before a closing tag.
  811. " If found, positions the cursor at the match and returns the line number.
  812. " Otherwise returns 0.
  813. let tagname = matchstr(getline('.')[col('.') - 1:], '</\zs' . s:tagname . '\ze')
  814. let start_lnum = searchpair('<' . tagname . '\>', '', '</' . tagname . '\>', 'bW')
  815. if start_lnum > 0
  816. return start_lnum
  817. endif
  818. return 0
  819. endfunc "}}}
  820. " Moves the cursor from a "<" to the matching ">".
  821. func HtmlIndent_FindTagEnd()
  822. "{{{
  823. " Call this with the cursor on the "<" of a start tag.
  824. " This will move the cursor to the ">" of the matching end tag or, when it's
  825. " a self-closing tag, to the matching ">".
  826. " Limited to look up to b:html_indent_line_limit lines away.
  827. let text = getline('.')
  828. let tagname = matchstr(text, s:tagname . '\|!--', col('.'))
  829. if tagname == '!--'
  830. call search('--\zs>')
  831. elseif s:get_tag('/' . tagname) != 0
  832. " tag with a closing tag, find matching "</tag>"
  833. call searchpair('<' . tagname, '', '</' . tagname . '\zs>', 'W', '', line('.') + b:html_indent_line_limit)
  834. else
  835. " self-closing tag, find the ">"
  836. call search('\S\zs>')
  837. endif
  838. endfunc "}}}
  839. " Indenting inside a start tag. Return the correct indent or -1 if unknown.
  840. func s:InsideTag(foundHtmlString)
  841. "{{{
  842. if a:foundHtmlString
  843. " Inside an attribute string.
  844. " Align with the opening quote or use an external function.
  845. let lnum = v:lnum - 1
  846. if lnum > 1
  847. if exists('b:html_indent_tag_string_func')
  848. return b:html_indent_tag_string_func(lnum)
  849. endif
  850. " If there is a double quote in the previous line, indent with the
  851. " character after it.
  852. if getline(lnum) =~ '"'
  853. call cursor(lnum, 0)
  854. normal f"
  855. return virtcol('.')
  856. endif
  857. return indent(lnum)
  858. endif
  859. endif
  860. " Should be another attribute: " attr="val". Align with the previous
  861. " attribute start.
  862. let lnum = v:lnum
  863. while lnum > 1
  864. let lnum -= 1
  865. let text = getline(lnum)
  866. " Find a match with one of these, align with "attr":
  867. " attr=
  868. " <tag attr=
  869. " text<tag attr=
  870. " <tag>text</tag>text<tag attr=
  871. " For long lines search for the first match, finding the last match
  872. " gets very slow.
  873. if len(text) < 300
  874. let idx = match(text, '.*\s\zs[_a-zA-Z0-9-]\+="')
  875. else
  876. let idx = match(text, '\s\zs[_a-zA-Z0-9-]\+="')
  877. endif
  878. if idx == -1
  879. " try <tag attr
  880. let idx = match(text, '<' . s:tagname . '\s\+\zs\w')
  881. endif
  882. if idx == -1
  883. " after just "<tag" indent two levels more by default
  884. let idx = match(text, '<' . s:tagname . '$')
  885. if idx >= 0
  886. call cursor(lnum, idx + 1)
  887. return virtcol('.') - 1 + shiftwidth() * b:hi_attr_indent
  888. endif
  889. endif
  890. if idx > 0
  891. " Found the attribute to align with.
  892. call cursor(lnum, idx)
  893. return virtcol('.')
  894. endif
  895. endwhile
  896. return -1
  897. endfunc "}}}
  898. " THE MAIN INDENT FUNCTION. Return the amount of indent for v:lnum.
  899. func HtmlIndent()
  900. "{{{
  901. if prevnonblank(v:lnum - 1) < 1
  902. " First non-blank line has no indent.
  903. return 0
  904. endif
  905. let curtext = tolower(getline(v:lnum))
  906. let indentunit = shiftwidth()
  907. let b:hi_newstate = {}
  908. let b:hi_newstate.lnum = v:lnum
  909. " When syntax HL is enabled, detect we are inside a tag. Indenting inside
  910. " a tag works very differently. Do not do this when the line starts with
  911. " "<", it gets the "htmlTag" ID but we are not inside a tag then.
  912. if curtext !~ '^\s*<'
  913. normal! ^
  914. let stack = synstack(v:lnum, col('.')) " assumes there are no tabs
  915. let foundHtmlString = 0
  916. for synid in reverse(stack)
  917. let name = synIDattr(synid, "name")
  918. if index(b:hi_insideStringNames, name) >= 0
  919. let foundHtmlString = 1
  920. elseif index(b:hi_insideTagNames, name) >= 0
  921. " Yes, we are inside a tag.
  922. let indent = s:InsideTag(foundHtmlString)
  923. if indent >= 0
  924. " Do not keep the state. TODO: could keep the block type.
  925. let b:hi_indent.lnum = 0
  926. return indent
  927. endif
  928. endif
  929. endfor
  930. endif
  931. " does the line start with a closing tag?
  932. let swendtag = match(curtext, '^\s*</') >= 0
  933. if prevnonblank(v:lnum - 1) == b:hi_indent.lnum && b:hi_lasttick == b:changedtick - 1
  934. " use state (continue from previous line)
  935. else
  936. " start over (know nothing)
  937. let b:hi_indent = s:FreshState(v:lnum)
  938. endif
  939. if b:hi_indent.block >= 2
  940. " within block
  941. let endtag = s:endtags[b:hi_indent.block]
  942. let blockend = stridx(curtext, endtag)
  943. if blockend >= 0
  944. " block ends here
  945. let b:hi_newstate.block = 0
  946. " calc indent for REST OF LINE (may start more blocks):
  947. call s:CountTagsAndState(strpart(curtext, blockend + strlen(endtag)))
  948. if swendtag && b:hi_indent.block != 5
  949. let indent = b:hi_indent.blocktagind + s:curind * indentunit
  950. let b:hi_newstate.baseindent = indent + s:nextrel * indentunit
  951. else
  952. let indent = s:Alien{b:hi_indent.block}()
  953. let b:hi_newstate.baseindent = b:hi_indent.blocktagind + s:nextrel * indentunit
  954. endif
  955. else
  956. " block continues
  957. " indent this line with alien method
  958. let indent = s:Alien{b:hi_indent.block}()
  959. endif
  960. else
  961. " not within a block - within usual html
  962. let b:hi_newstate.block = b:hi_indent.block
  963. if swendtag
  964. " The current line starts with an end tag, align with its start tag.
  965. call cursor(v:lnum, 1)
  966. let start_lnum = HtmlIndent_FindStartTag()
  967. if start_lnum > 0
  968. " check for the line starting with something inside a tag:
  969. " <sometag <- align here
  970. " attr=val><open> not here
  971. let text = getline(start_lnum)
  972. let angle = matchstr(text, '[<>]')
  973. if angle == '>'
  974. call cursor(start_lnum, 1)
  975. normal! f>%
  976. let start_lnum = line('.')
  977. let text = getline(start_lnum)
  978. endif
  979. let indent = indent(start_lnum)
  980. if col('.') > 2
  981. let swendtag = match(text, '^\s*</') >= 0
  982. call s:CountITags(text[: col('.') - 2])
  983. let indent += s:nextrel * shiftwidth()
  984. if !swendtag
  985. let indent += s:curind * shiftwidth()
  986. endif
  987. endif
  988. else
  989. " not sure what to do
  990. let indent = b:hi_indent.baseindent
  991. endif
  992. let b:hi_newstate.baseindent = indent
  993. else
  994. call s:CountTagsAndState(curtext)
  995. let indent = b:hi_indent.baseindent
  996. let b:hi_newstate.baseindent = indent + (s:curind + s:nextrel) * indentunit
  997. endif
  998. endif
  999. let b:hi_lasttick = b:changedtick
  1000. call extend(b:hi_indent, b:hi_newstate, "force")
  1001. return indent
  1002. endfunc "}}}
  1003. " Check user settings when loading this script the first time.
  1004. call HtmlIndent_CheckUserSettings()
  1005. let &cpo = s:cpo_save
  1006. unlet s:cpo_save
  1007. " vim: fdm=marker ts=8 sw=2 tw=78