1 " Vim completion script
3 " Maintainer: Mikolaj Machowski ( mikmach AT wp DOT pl )
4 " Last Change: 2006 Jul 18
9 " - allow for closing of xml tags even when data file isn't available
11 " This function will create Dictionary with users namespace strings and values
12 " canonical (system) names of data files. Names should be lowercase,
13 " descriptive to avoid any future conflicts. For example 'xhtml10s' should be
14 " name for data of XHTML 1.0 Strict and 'xhtml10t' for XHTML 1.0 Transitional
15 " User interface will be provided by XMLns command defined in ftplugin/xml.vim
16 " Currently supported canonicals are:
17 " xhtml10s - XHTML 1.0 Strict
19 function! xmlcomplete#CreateConnection(canonical, ...) " {{{
21 " When only one argument provided treat name as default namespace (without
29 " Source data file. Due to suspected errors in autoload do it with
31 " TODO: make it properly (using autoload, that is) later
32 exe "runtime autoload/xml/".a:canonical.".vim"
34 " Remove all traces of unexisting files to return [] when trying
35 " omnicomplete something
36 " TODO: give warning about non-existing canonicals - should it be?
37 if !exists("g:xmldata_".a:canonical)
38 unlet! g:xmldata_connection
42 " We need to initialize Dictionary to add key-value pair
43 if !exists("g:xmldata_connection")
44 let g:xmldata_connection = {}
47 let g:xmldata_connection[users] = a:canonical
52 function! xmlcomplete#CreateEntConnection(...) " {{{
54 let g:xmldata_entconnect = a:1
56 let g:xmldata_entconnect = 'DEFAULT'
61 function! xmlcomplete#CompleteTags(findstart, base)
63 " locate the start of the word
64 let curline = line('.')
65 let line = getline('.')
66 let start = col('.') - 1
67 let compl_begin = col('.') - 2
69 while start >= 0 && line[start - 1] =~ '\(\k\|[:.-]\)'
73 if start >= 0 && line[start - 1] =~ '&'
74 let b:entitiescompl = 1
75 let b:compl_context = ''
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. Up to
85 let context_line = getline(curline-i)
86 if context_line =~ '<[^>]*$'
87 " Yep, this is this line
88 let context_lines = getline(curline-i, curline-1) + [b:compl_context]
89 let b:compl_context = join(context_lines, ' ')
91 elseif context_line =~ '>[^<]*$' || i == curline
92 " Normal tag line, no need for completion at all
93 " OR reached first line without tag at all
94 let b:compl_context = ''
99 " Make sure we don't have counter
102 let b:compl_context = matchstr(b:compl_context, '.*\zs<.*')
104 " Make sure we will have only current namespace
105 unlet! b:xml_namespace
106 let b:xml_namespace = matchstr(b:compl_context, '^<\zs\k*\ze:')
107 if b:xml_namespace == ''
108 let b:xml_namespace = 'DEFAULT'
114 " Initialize base return lists
117 " a:base is very short - we need context
118 if len(b:compl_context) == 0 && !exists("b:entitiescompl")
121 let context = matchstr(b:compl_context, '^<\zs.*')
122 unlet! b:compl_context
123 " There is no connection of namespace and data file.
124 if !exists("g:xmldata_connection") || g:xmldata_connection == {}
125 " There is still possibility we may do something - eg. close tag
126 let b:unaryTagsStack = "base meta link hr br param img area input col"
128 let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
135 " Make entities completion
136 if exists("b:entitiescompl")
137 unlet! b:entitiescompl
139 if !exists("g:xmldata_entconnect") || g:xmldata_entconnect == 'DEFAULT'
140 let values = g:xmldata{'_'.g:xmldata_connection['DEFAULT']}['vimxmlentities']
142 let values = g:xmldata{'_'.g:xmldata_entconnect}['vimxmlentities']
145 " Get only lines with entity declarations but throw out
146 " parameter-entities - they may be completed in future
147 let entdecl = filter(getline(1, "$"), 'v:val =~ "<!ENTITY\\s\\+[^%]"')
150 let intent = map(copy(entdecl), 'matchstr(v:val, "<!ENTITY\\s\\+\\zs\\(\\k\\|[.-:]\\)\\+\\ze")')
151 let values = intent + values
166 call add(res2, m.';')
175 " Generally if context contains > it means we are outside of tag and
176 " should abandon action
180 " find tags matching with "a:base"
181 " If a:base contains white space it is attribute.
182 " It could be also value of attribute...
183 " We have to get first word to offer
188 let tag = split(context)[0]
190 " Get rid of namespace
191 let tag = substitute(tag, '^'.b:xml_namespace.':', '', '')
194 " Get last word, it should be attr name
195 let attr = matchstr(context, '.*\s\zs.*')
196 " Possible situations where any prediction would be difficult:
197 " 1. Events attributes
200 " If attr contains =\s*[\"'] we catched value of attribute
201 if attr =~ "=\s*[\"']" || attr =~ "=\s*$"
202 " Let do attribute specific completion
203 let attrname = matchstr(attr, '.*\ze\s*=')
204 let entered_value = matchstr(attr, ".*=\\s*[\"']\\?\\zs.*")
207 " Return nothing if we are inside of ! or ? tag
210 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, tag) && has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1], attrname)
211 let values = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1][attrname]
221 " We need special version of sbase
222 let attrbase = matchstr(context, ".*[\"']")
223 let attrquote = matchstr(attrbase, '.$')
224 if attrquote !~ "['\"]"
225 let attrquoteopen = '"'
228 let attrquoteopen = ''
232 " This if is needed to not offer all completions as-is
233 " alphabetically but sort them. Those beginning with entered
234 " part will be as first choices
235 if m =~ '^'.entered_value
236 call add(res, attrquoteopen . m . attrquote.' ')
237 elseif m =~ entered_value
238 call add(res2, attrquoteopen . m . attrquote.' ')
247 " Two possible arguments for <?xml> plus variation
248 let attrs = ['encoding', 'version="1.0"', 'version']
250 " Don't make completion at all
254 if !has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, tag)
255 " Abandon when data file isn't complete
258 let attrs = keys(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1])
268 let menu = res + res2
270 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, 'vimxmlattrinfo')
271 for i in range(len(menu))
273 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmlattrinfo'], item)
274 let m_menu = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmlattrinfo'][item][0]
275 let m_info = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmlattrinfo'][item][1]
280 if tag !~ '^[?!]' && len(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1][item]) > 0 && g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1][item][0] =~ '^\(BOOL\|'.item.'\)$'
285 let final_menu += [{'word':item, 'menu':m_menu, 'info':m_info}]
288 for i in range(len(menu))
290 if tag !~ '^[?!]' && len(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1][item]) > 0 && g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1][item][0] =~ '^\(BOOL\|'.item.'\)$'
295 let final_menu += [item]
302 let b:unaryTagsStack = "base meta link hr br param img area input col"
304 let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
308 " Complete elements of XML structure
309 " TODO: #REQUIRED, #IMPLIED, #FIXED, #PCDATA - but these should be detected like
310 " entities - in first run
311 " keywords: CDATA, ID, IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NMTOKENS
312 " are hardly recognizable but keep it in reserve
313 " also: EMPTY ANY SYSTEM PUBLIC DATA
315 let tags = ['!ELEMENT', '!DOCTYPE', '!ATTLIST', '!ENTITY', '!NOTATION', '![CDATA[', '![INCLUDE[', '![IGNORE[']
319 let m = substitute(m, '^!\[\?', '', '')
322 let m = substitute(m, '^!\[\?', '', '')
331 " Complete text declaration
337 call add(res, substitute(m, '^?', '', ''))
339 call add(res, substitute(m, '^?', '', ''))
347 " Deal with tag completion.
348 let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
349 let opentag = substitute(opentag, '^\k*:', '', '')
352 let tags = keys(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]})
353 call filter(tags, 'v:val !~ "^vimxml"')
355 if !has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, opentag)
356 " Abandon when data file isn't complete
359 let tags = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[opentag][0]
362 let context = substitute(context, '^\k*:', '', '')
371 let menu = res + res2
372 if b:xml_namespace == 'DEFAULT'
373 let xml_namespace = ''
375 let xml_namespace = b:xml_namespace.':'
377 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, 'vimxmltaginfo')
379 for i in range(len(menu))
381 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmltaginfo'], item)
382 let m_menu = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmltaginfo'][item][0]
383 let m_info = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmltaginfo'][item][1]
388 let final_menu += [{'word':xml_namespace.item, 'menu':m_menu, 'info':m_info}]
391 let final_menu = map(menu, 'xml_namespace.v:val')
399 " MM: This is severely reduced closetag.vim used with kind permission of Steven
401 " Changes: strip all comments; delete error messages; add checking for
403 " Author: Steven Mueller <diffusor@ugcs.caltech.edu>
404 " Last Modified: Tue May 24 13:29:48 PDT 2005
407 function! xmlcomplete#GetLastOpenTag(unaryTagsStack)
408 let linenum=line('.')
409 let lineend=col('.') - 1 " start: cursor position
410 let first=1 " flag for first line searched
411 let b:TagStack='' " main stack of tags
412 let startInComment=s:InComment()
414 if exists("b:xml_namespace")
415 if b:xml_namespace == 'DEFAULT'
416 let tagpat='</\=\(\k\|[.-]\)\+\|/>'
418 let tagpat='</\='.b:xml_namespace.':\(\k\|[.-]\)\+\|/>'
421 let tagpat='</\=\(\k\|[.-]\)\+\|/>'
424 let line=getline(linenum)
426 let line=strpart(line,0,lineend)
428 let lineend=strlen(line)
430 let b:lineTagStack=''
434 let mpos=matchend(line,tagpat)
436 let b:TagCol=b:TagCol+mpos
437 let tag=matchstr(line,tagpat)
439 if exists('b:closetag_disable_synID') || startInComment==s:InCommentAt(linenum, b:TagCol)
440 let b:TagLine=linenum
441 call s:Push(matchstr(tag,'[^<>]\+'),'b:lineTagStack')
443 let lineend=lineend-mpos
444 let line=strpart(line,mpos,lineend)
447 while (!s:EmptystackP('b:lineTagStack'))
448 let tag=s:Pop('b:lineTagStack')
449 if match(tag, '^/') == 0 "found end tag
450 call s:Push(tag,'b:TagStack')
451 elseif s:EmptystackP('b:TagStack') && !s:Instack(tag, a:unaryTagsStack) "found unclosed tag
454 let endtag=s:Peekstack('b:TagStack')
455 if endtag == '/'.tag || endtag == '/'
456 call s:Pop('b:TagStack') "found a open/close tag pair
457 elseif !s:Instack(tag, a:unaryTagsStack) "we have a mismatch error
462 let linenum=linenum-1 | let first=0
467 function! s:InComment()
468 return synIDattr(synID(line('.'), col('.'), 0), 'name') =~ 'Comment\|String'
471 function! s:InCommentAt(line, col)
472 return synIDattr(synID(a:line, a:col, 0), 'name') =~ 'Comment\|String'
475 function! s:SetKeywords()
476 let g:IsKeywordBak=&iskeyword
477 let &iskeyword='33-255'
480 function! s:RestoreKeywords()
481 let &iskeyword=g:IsKeywordBak
484 function! s:Push(el, sname)
485 if !s:EmptystackP(a:sname)
486 exe 'let '.a:sname."=a:el.' '.".a:sname
488 exe 'let '.a:sname.'=a:el'
492 function! s:EmptystackP(sname)
493 exe 'let stack='.a:sname
494 if match(stack,'^ *$') == 0
501 function! s:Instack(el, sname)
502 exe 'let stack='.a:sname
504 let m=match(stack, '\<'.a:el.'\>')
505 call s:RestoreKeywords()
513 function! s:Peekstack(sname)
515 exe 'let stack='.a:sname
516 let top=matchstr(stack, '\<.\{-1,}\>')
517 call s:RestoreKeywords()
521 function! s:Pop(sname)
522 if s:EmptystackP(a:sname)
525 exe 'let stack='.a:sname
527 let loc=matchend(stack,'\<.\{-1,}\>')
528 exe 'let '.a:sname.'=strpart(stack, loc+1, strlen(stack))'
529 let top=strpart(stack, match(stack, '\<'), loc)
530 call s:RestoreKeywords()
534 function! s:Clearstack(sname)
535 exe 'let '.a:sname."=''"
537 " vim:set foldmethod=marker: