at     parsed version of b:match_words
  "   s:all     regexp based on s:pat and the default groups
  " This part is copied and slightly modified from matchit#Match_wrapper().
  if !exists("b:match_words") || b:match_words == ""
    let match_words = ""
    " Allow b:match_words = "GetVimMatchWords()" .
  elseif b:match_words =~ ":"
    let match_words = b:match_words
  else
    execute "let match_words =" b:match_words
  endif
  if (match_words != s:last_words) || (&mps != s:last_mps) ||
    \ exists("b:match_debug")
    let default = escape(&mps, '[$^.*~\\/?]') .. (strlen(&mps) ? "," : "") ..
      \ '\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\>:#\s*endif\>'
    let s:last_mps = &mps
    let match_words = match_words .. (strlen(match_words) ? "," : "") .. default
    let s:last_words = match_words
    if match_words !~ s:notslash .. '\\\d'
      let s:do_BR = 0
      let s:pat = match_words
    else
      let s:do_BR = 1
      let s:pat = s:ParseWords(match_words)
    endif
    let s:all = '\%(' .. substitute(s:pat, '[,:]\+', '\\|', 'g') .. '\)'
    if exists("b:match_debug")
      let b:match_pat = s:pat
    endif
    " Reconstruct the version with unresolved backrefs.
    let s:patBR = substitute(match_words .. ',',
      \ s:notslash .. '\zs[,:]*,[,:]*', ',', 'g')
    let s:patBR = substitute(s:patBR, s:notslash .. '\zs:\{2,}', ':', 'g')
  endif

  " Second step:  figure out the patterns for searchpair()
  " and save the screen, cursor position, and 'ignorecase'.
  " - TODO:  A lot of this is copied from matchit#Match_wrapper().
  " - maybe even more functionality should be split off
  " - into separate functions!
  let openlist = split(s:pat .. ',', s:notslash .. '\zs:.\{-}' .. s:notslash .. ',')
  let midclolist = split(',' .. s:pat, s:notslash .. '\zs,.\{-}' .. s:notslash .. ':')
  call map(midclolist, {-> split(v:val, s:notslash .. ':')})
  let closelist = []
  let middlelist = []
  call map(midclolist, {i,v -> [extend(closelist, v[-1 : -1]),
        \ extend(middlelist, v[0 : -2])]})
  call map(openlist,   {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
  call map(middlelist, {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
  call map(closelist,  {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
  let open   = join(openlist, ',')
  let middle = join(middlelist, ',')
  let close  = join(closelist, ',')
  if exists("b:match_skip")
    let skip = b:match_skip
  elseif exists("b:match_comment") " backwards compatibility and testing!
    let skip = "r:" .. b:match_comment
  else
    let skip = 's:comment\|string'
  endif
  let skip = s:ParseSkip(skip)
  let view = winsaveview()

  " Third step: call searchpair().
  " Replace '\('--but not '\\('--with '\%(' and ',' with '\|'.
  let openpat = substitute(open, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
  let openpat = substitute(openpat, ',', '\\|', 'g')
  let closepat = substitute(close, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
  let closepat = substitute(closepat, ',', '\\|', 'g')
  let middlepat = substitute(middle, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
  let middlepat = substitute(middlepat, ',', '\\|', 'g')

  if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
    let skip = '0'
  else
    try
      execute "if " .. skip .. "| let skip = '0' | endif"
    catch /^Vim\%((\a\+)\)\=:E363/
      " We won't find anything, so skip searching, should keep Vim responsive.
      return {}
    endtry
  endif
  mark '
  while level
    if searchpair(openpat, middlepat, closepat, a:spflag, skip) < 1
      call s:CleanUp(restore_options, a:mode, startpos)
      return {}
    endif
    let level = level - 1
  endwhile

  " Restore options and return a string to restore the original position.
  call s:CleanUp(restore_options, a:mode, startpos)
  return view
endfun

" Search backwards for "if" or "while" or "<tag>" or ...
" and return "endif" or "endwhile" or "</tag>" or ... .
" For now, this uses b:match_words and the same script variables
" as matchit#Match_wrapper() .  Later, it may get its own patterns,
" either from a buffer variable or passed as arguments.
" fun! s:Autocomplete()
"   echo "autocomplete not yet implemented :-("
"   if !exists("b:match_words") || b:match_words == ""
"     return ""
"   end
"   let startpos = matchit#MultiMatch("bW")
"
"   if startpos == ""
"     return ""
"   endif
"   " - TODO:  figure out whether 'if' or '<tag>' matched, and construct
"   " - the appropriate closing.
"   let matchline = getline(".")
"   let curcol = col(".") - 1
"   " - TODO:  Change the s:all argument if there is a new set of match pats.
"   let regexp = s:Wholematch(matchline, s:all, curcol)
"   let suf = strlen(matchline) - matchend(matchline, regexp)
"   let prefix = (curcol ? '^.\{'  . curcol . '}\%(' : '^\%(')
"   let suffix = (suf ? '\).\{' . suf . '}$'  : '\)$')
"   " Reconstruct the version with unresolved backrefs.
"   let patBR = substitute(b:match_words.',', '[,:]*,[,:]*', ',', 'g')
"   let patBR = substitute(patBR, ':\{2,}', ':', "g")
"   " Now, set group and groupBR to the matching group: 'if:endif' or
"   " 'while:endwhile' or whatever.
"   let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR)
"   let i = matchend(group, s:notslash . ",")
"   let groupBR = strpart(group, i)
"   let group = strpart(group, 0, i-1)
"   " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
"   if s:do_BR
"     let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
"   endif
" " let g:group = group
"
"   " - TODO:  Construct the closing from group.
"   let fake = "end" . expand("<cword>")
"   execute startpos
"   return fake
" endfun

" Close all open structures.  "Get the heck out of here!"
" fun! s:Gthhoh()
"   let close = s:Autocomplete()
"   while strlen(close)
"     put=close
"     let close = s:Autocomplete()
"   endwhile
" endfun

" Parse special strings as typical skip arguments for searchpair():
"   s:foo becomes (current syntax item) =~ foo
"   S:foo becomes (current syntax item) !~ foo
"   r:foo becomes (line before cursor) =~ foo
"   R:foo becomes (line before cursor) !~ foo
fun! s:ParseSkip(str)
  let skip = a:str
  if skip[1] == ":"
    if skip[0] == "s"
      let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" ..
        \ strpart(skip,2) .. "'"
    elseif skip[0] == "S"
      let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" ..
        \ strpart(skip,2) .. "'"
    elseif skip[0] == "r"
      let skip = "strpart(getline('.'),0,col('.'))=~'" .. strpart(skip,2) .. "'"
    elseif skip[0] == "R"
      let skip = "strpart(getline('.'),0,col('.'))!~'" .. strpart(skip,2) .. "'"
    endif
  endif
  return skip
endfun

let &cpo = s:save_cpo
unlet s:save_cpo

" vim:sts=2:sw=2:et:
