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

2022-01-20 00:00:00 ide vim javascript html css

请注意:我已经通过此链接 跳转到在 VIM 中编辑 HTML 时的 CSS 定义,但对我没有帮助.

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

我希望跳转到 CSS 定义或 html 文件中的 javascript 函数.我很想点击单词下方的组合键来跳转到它的定义,而不仅仅是定义所在的文件.

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.

推荐答案

这个快速而肮脏的函数似乎对 *.html -> *.css 有用:

This quick and dirty function seems to do the trick for *.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/foo.css

    .foo {
      background-color: red;
    }
    

  • bar/bar.css

    #bar {
      border-color: gold;
    }
    

  • 将光标放在 test.html 中的任意 foobar 属性值上,点击 <F9> 跳转到正确文件中的正确定义.可以修改该函数以拆分打开目标文件,仅搜索链接的样式表……或者被 ZyX 完全嘲笑和破坏;-).

    With the cursor on any foo or bar attribute value in test.html, hitting <F9> jumps to the right definition in the right file. The function could be modified to open the target file in a split, search only the linked stylesheets… or be completely ridiculed and destroyed by ZyX ;-).

    编辑

    一些额外的指针:

    • :help iskeyword 让这个函数使用破折号连接的名字
    • :help expand()
    • :help searchpos():help search() 了解参数的含义
    • :help starstar 用于使用 ** 通配符
    • :help iskeyword for this function to work with dash-joined names
    • :help expand()
    • :help searchpos() and :help search() for the meanings of the arguments
    • :help starstar for the use of the ** wildcard

相关文章