1 " Vim completion script
3 " Maintainer: Mikolaj Machowski ( mikmach AT wp DOT pl )
4 " Last Change: 2006 Aug 15
9 " - fix closing of namespaced tags (Johannes Weiss)
11 " - allow for closing of xml tags even when data file isn't available
13 " This function will create Dictionary with users namespace strings and values
14 " canonical (system) names of data files. Names should be lowercase,
15 " descriptive to avoid any future conflicts. For example 'xhtml10s' should be
16 " name for data of XHTML 1.0 Strict and 'xhtml10t' for XHTML 1.0 Transitional
17 " User interface will be provided by XMLns command defined in ftplugin/xml.vim
18 " Currently supported canonicals are:
19 " xhtml10s - XHTML 1.0 Strict
21 function! xmlcomplete#CreateConnection(canonical, ...) " {{{
23 " When only one argument provided treat name as default namespace (without
31 " Source data file. Due to suspected errors in autoload do it with
33 " TODO: make it properly (using autoload, that is) later
34 exe "runtime autoload/xml/".a:canonical.".vim"
36 " Remove all traces of unexisting files to return [] when trying
37 " omnicomplete something
38 " TODO: give warning about non-existing canonicals - should it be?
39 if !exists("g:xmldata_".a:canonical)
40 unlet! g:xmldata_connection
44 " We need to initialize Dictionary to add key-value pair
45 if !exists("g:xmldata_connection")
46 let g:xmldata_connection = {}
49 let g:xmldata_connection[users] = a:canonical
54 function! xmlcomplete#CreateEntConnection(...) " {{{
56 let g:xmldata_entconnect = a:1
58 let g:xmldata_entconnect = 'DEFAULT'
63 function! xmlcomplete#CompleteTags(findstart, base)
65 " locate the start of the word
66 let curline = line('.')
67 let line = getline('.')
68 let start = col('.') - 1
69 let compl_begin = col('.') - 2
71 while start >= 0 && line[start - 1] =~ '\(\k\|[:.-]\)'
75 if start >= 0 && line[start - 1] =~ '&'
76 let b:entitiescompl = 1
77 let b:compl_context = ''
81 let b:compl_context = getline('.')[0:(compl_begin)]
82 if b:compl_context !~ '<[^>]*$'
83 " Look like we may have broken tag. Check previous lines. Up to
87 let context_line = getline(curline-i)
88 if context_line =~ '<[^>]*$'
89 " Yep, this is this line
90 let context_lines = getline(curline-i, curline-1) + [b:compl_context]
91 let b:compl_context = join(context_lines, ' ')
93 elseif context_line =~ '>[^<]*$' || i == curline
94 " Normal tag line, no need for completion at all
95 " OR reached first line without tag at all
96 let b:compl_context = ''
101 " Make sure we don't have counter
104 let b:compl_context = matchstr(b:compl_context, '.*\zs<.*')
106 " Make sure we will have only current namespace
107 unlet! b:xml_namespace
108 let b:xml_namespace = matchstr(b:compl_context, '^<\zs\k*\ze:')
109 if b:xml_namespace == ''
110 let b:xml_namespace = 'DEFAULT'
116 " Initialize base return lists
119 " a:base is very short - we need context
120 if len(b:compl_context) == 0 && !exists("b:entitiescompl")
123 let context = matchstr(b:compl_context, '^<\zs.*')
124 unlet! b:compl_context
125 " There is no connection of namespace and data file.
126 if !exists("g:xmldata_connection") || g:xmldata_connection == {}
127 " There is still possibility we may do something - eg. close tag
128 let b:unaryTagsStack = "base meta link hr br param img area input col"
130 let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
137 " Make entities completion
138 if exists("b:entitiescompl")
139 unlet! b:entitiescompl
141 if !exists("g:xmldata_entconnect") || g:xmldata_entconnect == 'DEFAULT'
142 let values = g:xmldata{'_'.g:xmldata_connection['DEFAULT']}['vimxmlentities']
144 let values = g:xmldata{'_'.g:xmldata_entconnect}['vimxmlentities']
147 " Get only lines with entity declarations but throw out
148 " parameter-entities - they may be completed in future
149 let entdecl = filter(getline(1, "$"), 'v:val =~ "<!ENTITY\\s\\+[^%]"')
152 let intent = map(copy(entdecl), 'matchstr(v:val, "<!ENTITY\\s\\+\\zs\\(\\k\\|[.-:]\\)\\+\\ze")')
153 let values = intent + values
168 call add(res2, m.';')
177 " Generally if context contains > it means we are outside of tag and
178 " should abandon action
182 " find tags matching with "a:base"
183 " If a:base contains white space it is attribute.
184 " It could be also value of attribute...
185 " We have to get first word to offer
190 let tag = split(context)[0]
192 " Get rid of namespace
193 let tag = substitute(tag, '^'.b:xml_namespace.':', '', '')
196 " Get last word, it should be attr name
197 let attr = matchstr(context, '.*\s\zs.*')
198 " Possible situations where any prediction would be difficult:
199 " 1. Events attributes
202 " If attr contains =\s*[\"'] we catched value of attribute
203 if attr =~ "=\s*[\"']" || attr =~ "=\s*$"
204 " Let do attribute specific completion
205 let attrname = matchstr(attr, '.*\ze\s*=')
206 let entered_value = matchstr(attr, ".*=\\s*[\"']\\?\\zs.*")
209 " Return nothing if we are inside of ! or ? tag
212 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)
213 let values = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1][attrname]
223 " We need special version of sbase
224 let attrbase = matchstr(context, ".*[\"']")
225 let attrquote = matchstr(attrbase, '.$')
226 if attrquote !~ "['\"]"
227 let attrquoteopen = '"'
230 let attrquoteopen = ''
234 " This if is needed to not offer all completions as-is
235 " alphabetically but sort them. Those beginning with entered
236 " part will be as first choices
237 if m =~ '^'.entered_value
238 call add(res, attrquoteopen . m . attrquote.' ')
239 elseif m =~ entered_value
240 call add(res2, attrquoteopen . m . attrquote.' ')
249 " Two possible arguments for <?xml> plus variation
250 let attrs = ['encoding', 'version="1.0"', 'version']
252 " Don't make completion at all
256 if !has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, tag)
257 " Abandon when data file isn't complete
260 let attrs = keys(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[tag][1])
270 let menu = res + res2
272 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, 'vimxmlattrinfo')
273 for i in range(len(menu))
275 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmlattrinfo'], item)
276 let m_menu = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmlattrinfo'][item][0]
277 let m_info = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmlattrinfo'][item][1]
282 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.'\)$'
287 let final_menu += [{'word':item, 'menu':m_menu, 'info':m_info}]
290 for i in range(len(menu))
292 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.'\)$'
297 let final_menu += [item]
304 let b:unaryTagsStack = "base meta link hr br param img area input col"
306 let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
310 " Complete elements of XML structure
311 " TODO: #REQUIRED, #IMPLIED, #FIXED, #PCDATA - but these should be detected like
312 " entities - in first run
313 " keywords: CDATA, ID, IDREF, IDREFS, ENTITY, ENTITIES, NMTOKEN, NMTOKENS
314 " are hardly recognizable but keep it in reserve
315 " also: EMPTY ANY SYSTEM PUBLIC DATA
317 let tags = ['!ELEMENT', '!DOCTYPE', '!ATTLIST', '!ENTITY', '!NOTATION', '![CDATA[', '![INCLUDE[', '![IGNORE[']
321 let m = substitute(m, '^!\[\?', '', '')
324 let m = substitute(m, '^!\[\?', '', '')
333 " Complete text declaration
339 call add(res, substitute(m, '^?', '', ''))
341 call add(res, substitute(m, '^?', '', ''))
349 " Deal with tag completion.
350 let opentag = xmlcomplete#GetLastOpenTag("b:unaryTagsStack")
351 let opentag = substitute(opentag, '^\k*:', '', '')
354 let tags = keys(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]})
355 call filter(tags, 'v:val !~ "^vimxml"')
357 if !has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, opentag)
358 " Abandon when data file isn't complete
361 let tags = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}[opentag][0]
364 let context = substitute(context, '^\k*:', '', '')
373 let menu = res + res2
374 if b:xml_namespace == 'DEFAULT'
375 let xml_namespace = ''
377 let xml_namespace = b:xml_namespace.':'
379 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}, 'vimxmltaginfo')
381 for i in range(len(menu))
383 if has_key(g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmltaginfo'], item)
384 let m_menu = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmltaginfo'][item][0]
385 let m_info = g:xmldata{'_'.g:xmldata_connection[b:xml_namespace]}['vimxmltaginfo'][item][1]
390 let final_menu += [{'word':xml_namespace.item, 'menu':m_menu, 'info':m_info}]
393 let final_menu = map(menu, 'xml_namespace.v:val')
401 " MM: This is severely reduced closetag.vim used with kind permission of Steven
403 " Changes: strip all comments; delete error messages; add checking for
405 " Author: Steven Mueller <diffusor@ugcs.caltech.edu>
406 " Last Modified: Tue May 24 13:29:48 PDT 2005
409 function! xmlcomplete#GetLastOpenTag(unaryTagsStack)
410 let linenum=line('.')
411 let lineend=col('.') - 1 " start: cursor position
412 let first=1 " flag for first line searched
413 let b:TagStack='' " main stack of tags
414 let startInComment=s:InComment()
416 if exists("b:xml_namespace")
417 if b:xml_namespace == 'DEFAULT'
418 let tagpat='</\=\(\k\|[.:-]\)\+\|/>'
420 let tagpat='</\='.b:xml_namespace.':\(\k\|[.-]\)\+\|/>'
423 let tagpat='</\=\(\k\|[.:-]\)\+\|/>'
426 let line=getline(linenum)
428 let line=strpart(line,0,lineend)
430 let lineend=strlen(line)
432 let b:lineTagStack=''
436 let mpos=matchend(line,tagpat)
438 let b:TagCol=b:TagCol+mpos
439 let tag=matchstr(line,tagpat)
441 if exists('b:closetag_disable_synID') || startInComment==s:InCommentAt(linenum, b:TagCol)
442 let b:TagLine=linenum
443 call s:Push(matchstr(tag,'[^<>]\+'),'b:lineTagStack')
445 let lineend=lineend-mpos
446 let line=strpart(line,mpos,lineend)
449 while (!s:EmptystackP('b:lineTagStack'))
450 let tag=s:Pop('b:lineTagStack')
451 if match(tag, '^/') == 0 "found end tag
452 call s:Push(tag,'b:TagStack')
453 elseif s:EmptystackP('b:TagStack') && !s:Instack(tag, a:unaryTagsStack) "found unclosed tag
456 let endtag=s:Peekstack('b:TagStack')
457 if endtag == '/'.tag || endtag == '/'
458 call s:Pop('b:TagStack') "found a open/close tag pair
459 elseif !s:Instack(tag, a:unaryTagsStack) "we have a mismatch error
464 let linenum=linenum-1 | let first=0
469 function! s:InComment()
470 return synIDattr(synID(line('.'), col('.'), 0), 'name') =~ 'Comment\|String'
473 function! s:InCommentAt(line, col)
474 return synIDattr(synID(a:line, a:col, 0), 'name') =~ 'Comment\|String'
477 function! s:SetKeywords()
478 let g:IsKeywordBak=&iskeyword
479 let &iskeyword='33-255'
482 function! s:RestoreKeywords()
483 let &iskeyword=g:IsKeywordBak
486 function! s:Push(el, sname)
487 if !s:EmptystackP(a:sname)
488 exe 'let '.a:sname."=a:el.' '.".a:sname
490 exe 'let '.a:sname.'=a:el'
494 function! s:EmptystackP(sname)
495 exe 'let stack='.a:sname
496 if match(stack,'^ *$') == 0
503 function! s:Instack(el, sname)
504 exe 'let stack='.a:sname
506 let m=match(stack, '\<'.a:el.'\>')
507 call s:RestoreKeywords()
515 function! s:Peekstack(sname)
517 exe 'let stack='.a:sname
518 let top=matchstr(stack, '\<.\{-1,}\>')
519 call s:RestoreKeywords()
523 function! s:Pop(sname)
524 if s:EmptystackP(a:sname)
527 exe 'let stack='.a:sname
529 let loc=matchend(stack,'\<.\{-1,}\>')
530 exe 'let '.a:sname.'=strpart(stack, loc+1, strlen(stack))'
531 let top=strpart(stack, match(stack, '\<'), loc)
532 call s:RestoreKeywords()
536 function! s:Clearstack(sname)
537 exe 'let '.a:sname."=''"
539 " vim:set foldmethod=marker: