1" Vim completion script
2" Language:	HTML and XHTML
3" Maintainer:	Mikolaj Machowski ( mikmach AT wp DOT pl )
4" Last Change:	2006 Apr 20
5
6function! htmlcomplete#CompleteTags(findstart, base)
7  if a:findstart
8    " locate the start of the word
9    let line = getline('.')
10    let start = col('.') - 1
11	let curline = line('.')
12	let compl_begin = col('.') - 2
13    while start >= 0 && line[start - 1] =~ '\(\k\|[:.-]\)'
14		let start -= 1
15    endwhile
16	" Handling of entities {{{
17	if start >= 0 && line[start - 1] =~ '&'
18		let b:entitiescompl = 1
19		let b:compl_context = ''
20		return start
21	endif
22	" }}}
23	" Handling of <style> tag {{{
24	let stylestart = searchpair('<style\>', '', '<\/style\>', "bnW")
25	let styleend   = searchpair('<style\>', '', '<\/style\>', "nW")
26	if stylestart != 0 && styleend != 0
27		if stylestart <= curline && styleend >= curline
28			let start = col('.') - 1
29			let b:csscompl = 1
30			while start >= 0 && line[start - 1] =~ '\(\k\|-\)'
31				let start -= 1
32			endwhile
33		endif
34	endif
35	" }}}
36	" Handling of <script> tag {{{
37	let scriptstart = searchpair('<script\>', '', '<\/script\>', "bnW")
38	let scriptend   = searchpair('<script\>', '', '<\/script\>', "nW")
39	if scriptstart != 0 && scriptend != 0
40		if scriptstart <= curline && scriptend >= curline
41			let start = col('.') - 1
42			let b:jscompl = 1
43			let b:jsrange = [scriptstart, scriptend]
44			while start >= 0 && line[start - 1] =~ '\k'
45				let start -= 1
46			endwhile
47			" We are inside of <script> tag. But we should also get contents
48			" of all linked external files and (secondary, less probably) other <script> tags
49			" This logic could possible be done in separate function - may be
50			" reused in events scripting (also with option could be reused for
51			" CSS
52			let b:js_extfiles = []
53			let l = line('.')
54			let c = col('.')
55			call cursor(1,1)
56			while search('<\@<=script\>', 'W') && line('.') <= l
57				if synIDattr(synID(line('.'),col('.')-1,0),"name") !~? 'comment'
58					let sname = matchstr(getline('.'), '<script[^>]*src\s*=\s*\([''"]\)\zs.\{-}\ze\1')
59					if filereadable(sname)
60						let b:js_extfiles += readfile(sname)
61					endif
62				endif
63			endwhile
64			call cursor(1,1)
65			let js_scripttags = []
66			while search('<script\>', 'W') && line('.') < l
67				if matchstr(getline('.'), '<script[^>]*src') == ''
68					let js_scripttag = getline(line('.'), search('</script>', 'W'))
69					let js_scripttags += js_scripttag
70				endif
71			endwhile
72			let b:js_extfiles += js_scripttags
73			call cursor(l,c)
74			unlet! l c
75		endif
76	endif
77	" }}}
78	if !exists("b:csscompl") && !exists("b:jscompl")
79		let b:compl_context = getline('.')[0:(compl_begin)]
80		if b:compl_context !~ '<[^>]*$'
81			" Look like we may have broken tag. Check previous lines.
82			let i = 1
83			while 1
84				let context_line = getline(curline-i)
85				if context_line =~ '<[^>]*$'
86					" Yep, this is this line
87					let context_lines = getline(curline-i, curline)
88					let b:compl_context = join(context_lines, ' ')
89					break
90				elseif context_line =~ '>[^<]*$' || i == curline
91					" We are in normal tag line, no need for completion at all
92					" OR reached first line without tag at all
93					let b:compl_context = ''
94					break
95				endif
96				let i += 1
97				" We reached first line and no tag approached
98				" Prevents endless loop
99				"if i > curline
100					"let b:compl_context = ''
101					"break
102				"endif
103			endwhile
104			" Make sure we don't have counter
105			unlet! i
106		endif
107		let b:compl_context = matchstr(b:compl_context, '.*\zs<.*')
108
109		" Return proper start for on-events. Without that beginning of
110		" completion will be badly reported
111		if b:compl_context =~? 'on[a-z]*\s*=\s*\(''[^'']*\|"[^"]*\)$'
112			let start = col('.') - 1
113			while start >= 0 && line[start - 1] =~ '\k'
114				let start -= 1
115			endwhile
116		endif
117		" If b:compl_context begins with <? we are inside of PHP code. It
118		" wasn't closed so PHP completion passed it to HTML
119		if &filetype =~? 'php' && b:compl_context =~ '^<?'
120			let b:phpcompl = 1
121			let start = col('.') - 1
122			while start >= 0 && line[start - 1] =~ '[a-zA-Z_0-9\x7f-\xff$]'
123				let start -= 1
124			endwhile
125		endif
126	else
127		let b:compl_context = getline('.')[0:compl_begin]
128	endif
129    return start
130  else
131	" Initialize base return lists
132    let res = []
133    let res2 = []
134	" a:base is very short - we need context
135	let context = b:compl_context
136	" Check if we should do CSS completion inside of <style> tag
137	" or JS completion inside of <script> tag or PHP completion in case of <?
138	" tag AND &ft==php
139	if exists("b:csscompl")
140		unlet! b:csscompl
141		let context = b:compl_context
142		unlet! b:compl_context
143		return csscomplete#CompleteCSS(0, context)
144	elseif exists("b:jscompl")
145		unlet! b:jscompl
146		return javascriptcomplete#CompleteJS(0, a:base)
147	elseif exists("b:phpcompl")
148		unlet! b:phpcompl
149		let context = b:compl_context
150		return phpcomplete#CompletePHP(0, a:base)
151	else
152		if len(b:compl_context) == 0 && !exists("b:entitiescompl")
153			return []
154		endif
155		let context = matchstr(b:compl_context, '.\zs.*')
156	endif
157	unlet! b:compl_context
158	" Entities completion {{{
159	if exists("b:entitiescompl")
160		unlet! b:entitiescompl
161
162		if !exists("b:html_omni")
163			"runtime! autoload/xml/xhtml10s.vim
164			call htmlcomplete#LoadData()
165		endif
166
167	    let entities =  b:html_omni['vimxmlentities']
168
169		if len(a:base) == 1
170			for m in entities
171				if m =~ '^'.a:base
172					call add(res, m.';')
173				endif
174			endfor
175			return res
176		else
177			for m in entities
178				if m =~? '^'.a:base
179					call add(res, m.';')
180				elseif m =~? a:base
181					call add(res2, m.';')
182				endif
183			endfor
184
185			return res + res2
186		endif
187
188
189	endif
190	" }}}
191	if context =~ '>'
192		" Generally if context contains > it means we are outside of tag and
193		" should abandon action - with one exception: <style> span { bo
194		if context =~ 'style[^>]\{-}>[^<]\{-}$'
195			return csscomplete#CompleteCSS(0, context)
196		elseif context =~ 'script[^>]\{-}>[^<]\{-}$'
197			let b:jsrange = [line('.'), search('<\/script\>', 'nW')]
198			return javascriptcomplete#CompleteJS(0, context)
199		else
200			return []
201		endif
202	endif
203
204	" If context contains > it means we are already outside of tag and we
205	" should abandon action
206	" If context contains white space it is attribute.
207	" It can be also value of attribute.
208	" We have to get first word to offer proper completions
209	if context == ''
210		let tag = ''
211	else
212		let tag = split(context)[0]
213		if tag =~ '[A-Z]'
214			let uppercase_tag = 1
215			let tag = tolower(tag)
216		else
217			let uppercase_tag = 0
218		endif
219	endif
220	let g:ta = tag
221	" Get last word, it should be attr name
222	let attr = matchstr(context, '.*\s\zs.*')
223	" Possible situations where any prediction would be difficult:
224	" 1. Events attributes
225	if context =~ '\s'
226		" Sort out style, class, and on* cases
227		if context =~? "\\(on[a-z]*\\|id\\|style\\|class\\)\\s*=\\s*[\"']"
228			" Id, class completion {{{
229			if context =~? "\\(id\\|class\\)\\s*=\\s*[\"'][a-zA-Z0-9_ -]*$"
230				if context =~? "class\\s*=\\s*[\"'][a-zA-Z0-9_ -]*$"
231					let search_for = "class"
232				elseif context =~? "id\\s*=\\s*[\"'][a-zA-Z0-9_ -]*$"
233					let search_for = "id"
234				endif
235				" Handle class name completion
236				" 1. Find lines of <link stylesheet>
237				" 1a. Check file for @import
238				" 2. Extract filename(s?) of stylesheet,
239				call cursor(1,1)
240				let head = getline(search('<head\>'), search('<\/head>'))
241				let headjoined = join(copy(head), ' ')
242				if headjoined =~ '<style'
243					" Remove possibly confusing CSS operators
244					let stylehead = substitute(headjoined, '+>\*[,', ' ', 'g')
245					if search_for == 'class'
246						let styleheadlines = split(stylehead)
247						let headclasslines = filter(copy(styleheadlines), "v:val =~ '\\([a-zA-Z0-9:]\\+\\)\\?\\.[a-zA-Z0-9_-]\\+'")
248					else
249						let stylesheet = split(headjoined, '[{}]')
250						" Get all lines which fit id syntax
251						let classlines = filter(copy(stylesheet), "v:val =~ '#[a-zA-Z0-9_-]\\+'")
252						" Filter out possible color definitions
253						call filter(classlines, "v:val !~ ':\\s*#[a-zA-Z0-9_-]\\+'")
254						" Filter out complex border definitions
255						call filter(classlines, "v:val !~ '\\(none\\|hidden\\|dotted\\|dashed\\|solid\\|double\\|groove\\|ridge\\|inset\\|outset\\)\\s*#[a-zA-Z0-9_-]\\+'")
256						let templines = join(classlines, ' ')
257						let headclasslines = split(templines)
258						call filter(headclasslines, "v:val =~ '#[a-zA-Z0-9_-]\\+'")
259					endif
260					let internal = 1
261				else
262					let internal = 0
263				endif
264				let styletable = []
265				let secimportfiles = []
266				let filestable = filter(copy(head), "v:val =~ '\\(@import\\|link.*stylesheet\\)'")
267				for line in filestable
268					if line =~ "@import"
269						let styletable += [matchstr(line, "import\\s\\+\\(url(\\)\\?[\"']\\?\\zs\\f\\+\\ze")]
270					elseif line =~ "<link"
271						let styletable += [matchstr(line, "href\\s*=\\s*[\"']\\zs\\f\\+\\ze")]
272					endif
273				endfor
274				for file in styletable
275					if filereadable(file)
276						let stylesheet = readfile(file)
277						let secimport = filter(copy(stylesheet), "v:val =~ '@import'")
278						if len(secimport) > 0
279							for line in secimport
280								let secfile = matchstr(line, "import\\s\\+\\(url(\\)\\?[\"']\\?\\zs\\f\\+\\ze")
281								let secfile = fnamemodify(file, ":p:h").'/'.secfile
282								let secimportfiles += [secfile]
283							endfor
284						endif
285					endif
286				endfor
287				let cssfiles = styletable + secimportfiles
288				let classes = []
289				for file in cssfiles
290					if filereadable(file)
291						let stylesheet = readfile(file)
292						let stylefile = join(stylesheet, ' ')
293						let stylefile = substitute(stylefile, '+>\*[,', ' ', 'g')
294						if search_for == 'class'
295							let stylesheet = split(stylefile)
296							let classlines = filter(copy(stylesheet), "v:val =~ '\\([a-zA-Z0-9:]\\+\\)\\?\\.[a-zA-Z0-9_-]\\+'")
297						else
298							let stylesheet = split(stylefile, '[{}]')
299							" Get all lines which fit id syntax
300							let classlines = filter(copy(stylesheet), "v:val =~ '#[a-zA-Z0-9_-]\\+'")
301							" Filter out possible color definitions
302							call filter(classlines, "v:val !~ ':\\s*#[a-zA-Z0-9_-]\\+'")
303							" Filter out complex border definitions
304							call filter(classlines, "v:val !~ '\\(none\\|hidden\\|dotted\\|dashed\\|solid\\|double\\|groove\\|ridge\\|inset\\|outset\\)\\s*#[a-zA-Z0-9_-]\\+'")
305							let templines = join(classlines, ' ')
306							let stylelines = split(templines)
307							let classlines = filter(stylelines, "v:val =~ '#[a-zA-Z0-9_-]\\+'")
308
309						endif
310					endif
311					" We gathered classes definitions from all external files
312					let classes += classlines
313				endfor
314				if internal == 1
315					let classes += headclasslines
316				endif
317
318				if search_for == 'class'
319					let elements = {}
320					for element in classes
321						if element =~ '^\.'
322							let class = matchstr(element, '^\.\zs[a-zA-Z][a-zA-Z0-9_-]*\ze')
323							let class = substitute(class, ':.*', '', '')
324							if has_key(elements, 'common')
325								let elements['common'] .= ' '.class
326							else
327								let elements['common'] = class
328							endif
329						else
330							let class = matchstr(element, '[a-zA-Z1-6]*\.\zs[a-zA-Z][a-zA-Z0-9_-]*\ze')
331							let tagname = tolower(matchstr(element, '[a-zA-Z1-6]*\ze.'))
332							if tagname != ''
333								if has_key(elements, tagname)
334									let elements[tagname] .= ' '.class
335								else
336									let elements[tagname] = class
337								endif
338							endif
339						endif
340					endfor
341
342					if has_key(elements, tag) && has_key(elements, 'common')
343						let values = split(elements[tag]." ".elements['common'])
344					elseif has_key(elements, tag) && !has_key(elements, 'common')
345						let values = split(elements[tag])
346					elseif !has_key(elements, tag) && has_key(elements, 'common')
347						let values = split(elements['common'])
348					else
349						return []
350					endif
351
352				elseif search_for == 'id'
353					" Find used IDs
354					" 1. Catch whole file
355					let filelines = getline(1, line('$'))
356					" 2. Find lines with possible id
357					let used_id_lines = filter(filelines, 'v:val =~ "id\\s*=\\s*[\"''][a-zA-Z0-9_-]\\+"')
358					" 3a. Join all filtered lines
359					let id_string = join(used_id_lines, ' ')
360					" 3b. And split them to be sure each id is in separate item
361					let id_list = split(id_string, 'id\s*=\s*')
362					" 4. Extract id values
363					let used_id = map(id_list, 'matchstr(v:val, "[\"'']\\zs[a-zA-Z0-9_-]\\+\\ze")')
364					let joined_used_id = ','.join(used_id, ',').','
365
366					let allvalues = map(classes, 'matchstr(v:val, ".*#\\zs[a-zA-Z0-9_-]\\+")')
367
368					let values = []
369
370					for element in classes
371						if joined_used_id !~ ','.element.','
372							let values += [element]
373						endif
374
375					endfor
376
377				endif
378
379				" We need special version of sbase
380				let classbase = matchstr(context, ".*[\"']")
381				let classquote = matchstr(classbase, '.$')
382
383				let entered_class = matchstr(attr, ".*=\\s*[\"']\\zs.*")
384
385				for m in sort(values)
386					if m =~? '^'.entered_class
387						call add(res, m . classquote)
388					elseif m =~? entered_class
389						call add(res2, m . classquote)
390					endif
391				endfor
392
393				return res + res2
394
395			elseif context =~? "style\\s*=\\s*[\"'][^\"']*$"
396				return csscomplete#CompleteCSS(0, context)
397
398			endif
399			" }}}
400			" Complete on-events {{{
401			if context =~? 'on[a-z]*\s*=\s*\(''[^'']*\|"[^"]*\)$'
402				" We have to:
403				" 1. Find external files
404				let b:js_extfiles = []
405				let l = line('.')
406				let c = col('.')
407				call cursor(1,1)
408				while search('<\@<=script\>', 'W') && line('.') <= l
409					if synIDattr(synID(line('.'),col('.')-1,0),"name") !~? 'comment'
410						let sname = matchstr(getline('.'), '<script[^>]*src\s*=\s*\([''"]\)\zs.\{-}\ze\1')
411						if filereadable(sname)
412							let b:js_extfiles += readfile(sname)
413						endif
414					endif
415				endwhile
416				" 2. Find at least one <script> tag
417				call cursor(1,1)
418				let js_scripttags = []
419				while search('<script\>', 'W') && line('.') < l
420					if matchstr(getline('.'), '<script[^>]*src') == ''
421						let js_scripttag = getline(line('.'), search('</script>', 'W'))
422						let js_scripttags += js_scripttag
423					endif
424				endwhile
425				let b:js_extfiles += js_scripttags
426
427				" 3. Proper call for javascriptcomplete#CompleteJS
428				call cursor(l,c)
429				let js_context = matchstr(a:base, '\k\+$')
430				let js_shortcontext = substitute(a:base, js_context.'$', '', '')
431				let b:compl_context = context
432				let b:jsrange = [l, l]
433				unlet! l c
434				return javascriptcomplete#CompleteJS(0, js_context)
435
436			endif
437
438			" }}}
439			let stripbase = matchstr(context, ".*\\(on[a-zA-Z]*\\|style\\|class\\)\\s*=\\s*[\"']\\zs.*")
440			" Now we have context stripped from all chars up to style/class.
441			" It may fail with some strange style value combinations.
442			if stripbase !~ "[\"']"
443				return []
444			endif
445		endif
446		" Value of attribute completion {{{
447		" If attr contains =\s*[\"'] we catched value of attribute
448		if attr =~ "=\s*[\"']" || attr =~ "=\s*$"
449			" Let do attribute specific completion
450			let attrname = matchstr(attr, '.*\ze\s*=')
451			let entered_value = matchstr(attr, ".*=\\s*[\"']\\?\\zs.*")
452			let values = []
453			if attrname == 'href'
454				" Now we are looking for local anchors defined by name or id
455				if entered_value =~ '^#'
456					let file = join(getline(1, line('$')), ' ')
457					" Split it be sure there will be one id/name element in
458					" item, it will be also first word [a-zA-Z0-9_-] in element
459					let oneelement = split(file, "\\(meta \\)\\@<!\\(name\\|id\\)\\s*=\\s*[\"']")
460					for i in oneelement
461						let values += ['#'.matchstr(i, "^[a-zA-Z][a-zA-Z0-9%_-]*")]
462					endfor
463				endif
464			else
465				if has_key(b:html_omni, tag) && has_key(b:html_omni[tag][1], attrname)
466					let values = b:html_omni[tag][1][attrname]
467				else
468					return []
469				endif
470			endif
471
472			if len(values) == 0
473				return []
474			endif
475
476			" We need special version of sbase
477			let attrbase = matchstr(context, ".*[\"']")
478			let attrquote = matchstr(attrbase, '.$')
479			if attrquote !~ "['\"]"
480				let attrquoteopen = '"'
481				let attrquote = '"'
482			else
483				let attrquoteopen = ''
484			endif
485
486			for m in values
487				" This if is needed to not offer all completions as-is
488				" alphabetically but sort them. Those beginning with entered
489				" part will be as first choices
490				if m =~ '^'.entered_value
491					call add(res, attrquoteopen . m . attrquote.' ')
492				elseif m =~ entered_value
493					call add(res2, attrquoteopen . m . attrquote.' ')
494				endif
495			endfor
496
497			return res + res2
498
499		endif
500		" }}}
501		" Attribute completion {{{
502		" Shorten context to not include last word
503		let sbase = matchstr(context, '.*\ze\s.*')
504
505		" Load data {{{
506		if !exists("b:html_omni_gen")
507			call htmlcomplete#LoadData()
508		endif
509		" }}}
510
511		if has_key(b:html_omni, tag)
512			let attrs = keys(b:html_omni[tag][1])
513		else
514			return []
515		endif
516
517		for m in sort(attrs)
518			if m =~ '^'.attr
519				call add(res, m)
520			elseif m =~ attr
521				call add(res2, m)
522			endif
523		endfor
524		let menu = res + res2
525		if has_key(b:html_omni, 'vimxmlattrinfo')
526			let final_menu = []
527			for i in range(len(menu))
528				let item = menu[i]
529				if has_key(b:html_omni['vimxmlattrinfo'], item)
530					let m_menu = b:html_omni['vimxmlattrinfo'][item][0]
531					let m_info = b:html_omni['vimxmlattrinfo'][item][1]
532					if m_menu !~ 'Bool'
533						let item .= '="'
534					endif
535				else
536					let m_menu = ''
537					let m_info = ''
538					let item .= '="'
539				endif
540				let final_menu += [{'word':item, 'menu':m_menu, 'info':m_info}]
541			endfor
542		else
543			let final_menu = map(menu, 'v:val."=\""')
544		endif
545		return final_menu
546
547	endif
548	" }}}
549	" Close tag {{{
550	let b:unaryTagsStack = "base meta link hr br param img area input col"
551	if context =~ '^\/'
552		if context =~ '^\/.'
553			return []
554		else
555			let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
556			return [opentag.">"]
557		endif
558	endif
559	" }}}
560	" Load data {{{
561	if !exists("b:html_omni")
562		"runtime! autoload/xml/xhtml10s.vim
563		call htmlcomplete#LoadData()
564	endif
565	" }}}
566	" Tag completion {{{
567	" Deal with tag completion.
568	let opentag = tolower(xmlcomplete#GetLastOpenTag("b:unaryTagsStack"))
569	" MM: TODO: GLOT works always the same but with some weird situation it
570	" behaves as intended in HTML but screws in PHP
571	if opentag == '' || &ft == 'php' && !has_key(b:html_omni, opentag)
572		" Hack for sometimes failing GetLastOpenTag.
573		" As far as I tested fail isn't GLOT fault but problem
574		" of invalid document - not properly closed tags and other mish-mash.
575		" Also when document is empty. Return list of *all* tags.
576	    let tags = keys(b:html_omni)
577		call filter(tags, 'v:val !~ "^vimxml"')
578	else
579		if has_key(b:html_omni, opentag)
580			let tags = b:html_omni[opentag][0]
581		else
582			return []
583		endif
584	endif
585	" }}}
586
587	if exists("uppercase_tag") && uppercase_tag == 1
588		let context = tolower(context)
589	endif
590
591	for m in sort(tags)
592		if m =~ '^'.context
593			call add(res, m)
594		elseif m =~ context
595			call add(res2, m)
596		endif
597	endfor
598	let menu = res + res2
599	if has_key(b:html_omni, 'vimxmltaginfo')
600		let final_menu = []
601		for i in range(len(menu))
602			let item = menu[i]
603			if has_key(b:html_omni['vimxmltaginfo'], item)
604				let m_menu = b:html_omni['vimxmltaginfo'][item][0]
605				let m_info = b:html_omni['vimxmltaginfo'][item][1]
606			else
607				let m_menu = ''
608				let m_info = ''
609			endif
610			if &ft == 'html' && exists("uppercase_tag") && uppercase_tag == 1
611				let item = toupper(item)
612			endif
613			let final_menu += [{'word':item, 'menu':m_menu, 'info':m_info}]
614		endfor
615	else
616		let final_menu = menu
617	endif
618	return final_menu
619
620	" }}}
621  endif
622endfunction
623
624function! htmlcomplete#LoadData() " {{{
625	if !exists("b:html_omni_flavor")
626		if &ft == 'html'
627			let b:html_omni_flavor = 'html401t'
628		else
629			let b:html_omni_flavor = 'xhtml10s'
630		endif
631	endif
632	" With that if we still have bloated memory but create new buffer
633	" variables only by linking to existing g:variable, not sourcing whole
634	" file.
635	if exists('g:xmldata_'.b:html_omni_flavor)
636		exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
637	else
638		exe 'runtime! autoload/xml/'.b:html_omni_flavor.'.vim'
639		exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
640	endif
641	" This repetition is necessary because we don't know if
642	" b:html_omni_flavor file exists and was sourced
643	" Proper checking for files would require iterating through 'rtp'
644	" and could introduce OS dependent mess.
645	if !exists("g:xmldata_".b:html_omni_flavor)
646		if &ft == 'html'
647			let b:html_omni_flavor = 'html401t'
648		else
649			let b:html_omni_flavor = 'xhtml10s'
650		endif
651	endif
652	if exists('g:xmldata_'.b:html_omni_flavor)
653		exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
654	else
655		exe 'runtime! autoload/xml/'.b:html_omni_flavor.'.vim'
656		exe 'let b:html_omni = g:xmldata_'.b:html_omni_flavor
657	endif
658endfunction
659" }}}
660" vim:set foldmethod=marker:
661