Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
" Extracts a CSS var
"
" Setup:
" Load this in your VIM: `source extract-css-var.vim`
"
" Usage:
" Place cursor on any line with CSS. ie "color: red;"
" Call the function (ideally with a key mapping): `call ExtractCSSVar()`
" You'll be prompted to enter a name for the var, then hit Enter (defaults to the current property name)
" It will update the current line, and place the var value, ie `--var-name: original-value` inside the default register (so you can paste it)
function! ExtractCSSVar()
let line = getline(".")
let trimmed = Trim(line)
" error if not a CSS attribute expression
if stridx(trimmed, ":") < 0
echohl ErrorMsg | echom "Expected CSS expression `attribute: value`" | echohl None
return
endif
let stripped = ChompSemi(l:trimmed)
let parts = split(stripped, ':')
let property = Trim(parts[0])
let value = Trim(parts[1])
let varName = "--" . input("var name: ", property)
let lineNo = line(".")
let whitespace = LeadingWhitespace(l:line)
" replace current line, preserving whitespace
call setline(lineNo, whitespace . property . ": var(" . varName . ");")
" put in register
let @" = whitespace . varName . ": " . value . ";"
endfunction
" returns leading whitespace
function! LeadingWhitespace(input)
return substitute(a:input, '^\(\s*\).*', '\1', '')
endfunction
" remove semicolon
function! ChompSemi(input)
return substitute(a:input, '^\(.*\);$', '\1', '')
endfunction
" remove whitespace from text
function! Trim(input)
return substitute(a:input, '^\s*\(.\{-}\)\s*$', '\1', '')
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment