Skip to content

Instantly share code, notes, and snippets.

@eloytoro
Created June 3, 2018 16:07
Show Gist options
  • Save eloytoro/8a2c2f70b0a3914bfc7ea62a448b87d4 to your computer and use it in GitHub Desktop.
Save eloytoro/8a2c2f70b0a3914bfc7ea62a448b87d4 to your computer and use it in GitHub Desktop.
" ----------------------------------------------------------------------------
" HTML/JSX autoclose tag
" ----------------------------------------------------------------------------
let s:closed_tag_regexp = '<\/\(\w\|\.\)\+>'
let s:tag_name_regexp = '<\(\w\|\.\|:\)\+'
let s:tag_properties = '\s*\(\s\+[^>]\+\s*\)*'
let s:tag_regexp = s:tag_name_regexp.s:tag_properties.'[^\/]'
let s:tag_blacklist = ['TMPL_*', 'input', 'br']
let s:hl_whitelist = ['xmlTag', 'htmlTag']
function! CarriageReturn()
if has('python3')
let snippet = UltiSnips#ExpandSnippetOrJump()
if g:ulti_expand_or_jump_res > 0
return snippet
endif
endif
let col = col('.') - 1
if col && strpart(getline('.'), col) =~ '^'.s:closed_tag_regexp
return "\<CR>\<Esc>".'zvO'
endif
return "\<CR>"
endfunction
inoremap <silent> <CR> <C-R>=CarriageReturn()<CR>
function! CloseTag()
let n = getline('.')
let column = col('.') - 1
let hl = s:hl()
let close = '>'
if !column
return close
endif
for item in s:hl_whitelist
if index(hl, item) == -1
return close
endif
endfor
let line_before_cursor = strpart(n, 0, column)
if line_before_cursor !~ s:tag_regexp.'$'
return close
endif
let tag = matchstr(line_before_cursor, s:tag_name_regexp.'\('.s:tag_properties.'$\)\@=')
for item in s:tag_blacklist
if tag =~ item
return close
endif
endfor
return '></'.strpart(tag, 1).'>'."\<Esc>F>a"
endfunction
function! EraseTag()
let n = line('.')
let line = getline(n)
let col = col('.') - 1
if col
\ && strpart(line, 0, col) =~ s:tag_regexp.'>$'
\ && strpart(line, col) =~ '^'.s:closed_tag_regexp
return "\<Esc>cf>"
endif
if n > 0
let before = getline(n - 1)
let after = getline(n + 1)
if line =~ '^\s*$'
\ && after =~ '^\s*'.s:closed_tag_regexp
\ && before =~ s:tag_regexp.'>$'
return "\<Esc>kJJhct<"
endif
endif
return "\<BS>"
endfunction
augroup autoclose_tags
autocmd!
autocmd FileType javascript.jsx inoremap <buffer> <silent> > <C-R>=CloseTag()<CR>
autocmd FileType javascript.jsx inoremap <buffer> <silent> <BS> <C-R>=EraseTag()<CR>
autocmd FileType html,xml inoremap <buffer> <silent> <BS> <C-R>=EraseTag()<CR>
augroup END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment