Skip to content

Instantly share code, notes, and snippets.

@AndrewRadev
Last active May 30, 2017 07:15
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 AndrewRadev/d718c145216060ae13234e2db9ed5ee8 to your computer and use it in GitHub Desktop.
Save AndrewRadev/d718c145216060ae13234e2db9ed5ee8 to your computer and use it in GitHub Desktop.
gf for react
set includeexpr=<SID>Includeexpr()
augroup jsx_autocommands
autocmd!
" Override gf if rails sets it after
autocmd User Rails cmap <buffer><expr> <Plug><cfile> <SID>Includeexpr()
augroup END
function! s:Includeexpr()
let word = expand('<cword>')
let import_pattern =
\ '^\s*import\s\+\%({\%(\w\|,\s*\)*\)\='.
\ word.
\ '\%(\%(\w\|,\|\s*\)*}\)\=\s\+from\s\+\zs[''"]\(.\{-}\)[''"]'
if search(import_pattern, 'wc') <= 0
return word
endif
let start_quote_col = col('.')
let quote = getline('.')[start_quote_col - 1]
if search(quote, 'W', line('.')) <= 0
return word
endif
let end_quote_col = col('.')
let relative_path = strpart(getline('.'), start_quote_col, (end_quote_col - start_quote_col - 1))
let dirname = expand('%:h')
let absolute_path = fnamemodify(dirname.'/'.relative_path, ':p')
let suffixes = ['.js', '.jsx', '/index.js', '/index.jsx']
for suffix in suffixes
let path = substitute(absolute_path, '/$', '', '').suffix
if filereadable(path)
return simplify(fnamemodify(path, ':.'))
endif
endfor
return relative_path
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment