使用单击键从Vim中的HTML文件跳转到css文件中的CSS选择器

时间:2012-10-11 06:05:40

标签: javascript html css vim ide

请注意:我已通过此链接Jump to CSS definition when editing HTML in VIM,但它无法帮助我。

我希望从html文件跳转到CSS定义或javascript函数。我想在单词下面点击一个关键组合来跳转到它的定义,而不仅仅是定义所在的文件。

我目前需要在打开的缓冲区中搜索单词,然后在所需的缓冲区中找到所有搜索结果。这非常耗时。

请帮我解决这个非常规的要求。

2 个答案:

答案 0 :(得分:6)

这个快速而肮脏的功能似乎可以解决* .html - > *的CSS:

function! JumpToCSS()
  let id_pos = searchpos("id", "nb", line('.'))[1]
  let class_pos = searchpos("class", "nb", line('.'))[1]

  if class_pos > 0 || id_pos > 0
    if class_pos < id_pos
      execute ":vim '#".expand('<cword>')."' **/*.css"
    elseif class_pos > id_pos
      execute ":vim '.".expand('<cword>')."' **/*.css"
    endif
  endif
endfunction

nnoremap <F9> :call JumpToCSS()<CR>
  • <强>的test.html

    <html>
      <body>
        <div class="foo" id="bar">lorem</div>
        <div id="bar" class="foo">ipsum</div>
        <div id="bar">dolor</div>
        <div class="foo">sit</div>
      </body>
    </html>
    
  • <强>富/ foo.css

    .foo {
      background-color: red;
    }
    
  • <强>酒吧/ bar.css

    #bar {
      border-color: gold;
    }
    

将光标放在foo中的任意bartest.html属性值上,点击<F9>会跳转到右侧文件中的右侧定义。可以修改该函数以在拆分中打开目标文件,仅搜索链接的样式表......或者被ZyX完全嘲笑和销毁; - )。

修改

一些额外的指示:

  • :help iskeyword,此功能可以使用加入短划线的名称
  • :help expand()
  • :help searchpos():help search()了解参数的含义
  • :help starstar使用**通配符

答案 1 :(得分:6)

我认为这应该是一个单独的答案,所以,那里。

您可以向ctags添加CSS支持,并使用它以与JavaScript相同的方式跳转到定义。就像在~/.ctags文件中添加以下行一样简单:

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

完成后,clasic :!ctags -R .将正确索引您的CSS文件,您将能够:tag .myClass在正确的CSS文件中跳转到正确的CSS定义。

但是,有一个问题。类和ID标记将包含其.#,因此:tag myClass:tag .myClass不起作用。最简单的解决方案是使用“regexp search”而不是“整个标记搜索”::tag /myClass

这两个映射完美无缺(对于JS有一段时间以及CSS几天以来):

" 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>