Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

javascript - jump to CSS selector in a css file from the HTML file in Vim using a single keystroke

Please note: I have been through this link Jump to CSS definition when editing HTML in VIM, but it couldn't help me.

I am looking to jump to the CSS definition or for that matter a javascript function from the html file. I would love to hit a key combo below the word to jump to its definition, not just the file in which the definition resides.

I currently need to search the word in opened buffers and then reach to all the search results in the required buffer. It is very time consuming.

Please help me with this very regular requirement.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I thought this deserved to be a separate answer so, there.

You can add CSS support to ctags and use it to jump to definition the same way you would do for JavaScript. It's as simple as adding the following lines to the ~/.ctags file:

--langdef=css
--langmap=css:.css
--regex-css=/^[ ]*.([A-Za-z0-9_-]+)/.1/c,class,classes/
--regex-css=/^[ ]*#([A-Za-z0-9_-]+)/#1/i,id,ids/
--regex-css=/^[ ]*(([A-Za-z0-9_-]+[ 
,]+)+){/1/t,tag,tags/
--regex-css=/^[ ]*@medias+([A-Za-z0-9_-]+)/1/m,media,medias/

Once you are done, the clasic :!ctags -R . will correctly index your CSS files and you'll be able to do :tag .myClass to jump to the correct CSS definition in the correct CSS file.

There's one catch, though. The classes an ids tags will include their . or # so :tag myClass won't work while :tag .myClass will. The simplest solution is to use "regexp search" instead of "whole tag search": :tag /myClass.

These two mappings have worked flawlessly (for JS for a while and for CSS since a few days) :

" alternative to <C-]>
" place your cursor on an id or class and hit <leader>]
" to jump to the definition
nnoremap <leader>] :tag /<c-r>=expand('<cword>')<cr><cr>

" alternative to <C-w>}
" place your cursor on an id or class and hit <leader>}
" to show a preview of the definition. This doesn't seem to be
" very useful for CSS but it rocks for JavaScript 
nnoremap <leader>} :ptag /<c-r>=expand('<cword>')<cr><cr>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...