autocmd BufRead,BufNewFile *.blade.php set filetype=blade


" autocmd FileType blade inoremap<buffer> > <c-r>=CreateTag()<cr>


" Abbreviations
autocmd FileType blade iabbr <silent> class= class=""<Left><C-R>=Eatchar('\s')<CR>
autocmd FileType blade iabbr <silent> id= id=""<Left><C-R>=Eatchar('\s')<CR>
autocmd FileType blade iabbr <silent> log console.log()<Left><C-R>=Eatchar('\s')<CR>




func Eatchar(pat)
   let c = nr2char(getchar(0))
   return (c =~ a:pat) ? '' : c
endfunc

func CreateTag()
	let line = getline('.')
	let end = col('.') - 1
	let begin = end - 1
	let start = ''
	let tagname_regexp = '[a-zA-Z0-9-_\.#]'
	let first_chars = '[a-zA-Z0-9]'
	let id_regexp = '[#]'
	let class_regexp = '[\.]'
	let tagname = ''
	let id = ''
	let classes = ''
	let current_type = 0 " 0: tagname, 1: classes, 2: id
	" incase the previous character was not in the usage
	if line[begin] !~ first_chars
		return '>'
	endif

	" reverse until we leave the replacement
  while begin > 0
		if line[begin] !~ tagname_regexp
			let begin += 1
      break
    endif
    let begin -= 1
  endwhile

	let start = begin

	" start over reading the tag name
	while begin < end
		"deteremine if the type changes
		if line[begin] =~ id_regexp
			let current_type = 2
		elseif	line[begin] =~ class_regexp
			let current_type = 1
			"need a space in the class if there is already classes
			if classes != ''
				let classes .= ' '
			endif
		else
			" Write to the current type
			if current_type == 0
				let tagname .= line[begin]
			elseif current_type == 1
				let classes .= line[begin]
			elseif current_type == 2
				let id .= line[begin]
			endif
		endif

		let begin += 1
	endwhile

	" Trim the strings, just in case
	let tagname = trim(tagname)
	let id = trim(id)
	let classes = trim(classes)


	let str = '<' .tagname
	if id != ''
		let str .= ' id="' . id . '"'
	endif
	if classes != ''
		let str .= ' class="' . classes . '"'
	endif
	let str .= '> </'. tagname . '>'	
	" delete the previous characters
	let del_count = (end-start)
  execute "normal! " . del_count . "X"
	" delete the char under the cursor
  execute "normal! x"

	return str . repeat("\<Left>", len(tagname) + 4)
	
endfunc

