Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Created March 7, 2021 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshnuss/6c4fa23a860e4e2c4d0a0658aadca50d to your computer and use it in GitHub Desktop.
Save joshnuss/6c4fa23a860e4e2c4d0a0658aadca50d to your computer and use it in GitHub Desktop.
" 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