在 .vimrc 中转义反斜杠以使用 :map 与 grep 和 \s 一起工作

escaping backslash in .vimrc to have a :map working with grep and \s

在我的 .vimrc 我使用这个:

:map ,p :!clear; grep -E "def \|class " %

,p 映射到提供 Python def 和 class 层次结构的 grep,效果很好。

我尝试做同样的事情来获得一些 vuejs 结构,但没有成功。

我在 Bash 上得到了我需要的,这是 grep:

$ grep -E '^\s+\S+: {|\() {$|<script>|import' /tmp/somevuejs.vue

但是当我尝试把它放在 .vimrc 上时:

:map ,j :!clear; grep -E '^\s+\S+: {|\() {$|<script>|import' %

我收到这个错误:

$ vim file.txt
Error detected while processing /home/me/.vimrc:
line   20:
E10: \ should be followed by /, ? or &

我试过多次转义组合但没有成功,这两个都不起作用:

:map ,j :!clear; grep -E '^//\s+//\S+: {|\() {$|<script>|import' %
:map ,j :!clear; grep -E "^//\s+//\S+: {|\() {$|<script>|import" %

:help map-bar 说你不能在映射中使用 | 除非你以某种方式转义它。

您现有的映射“有效”,因为它的 | 已正确转义:

:map ,p :!clear; grep -E "def \|class " %
                              ^^

您的新映射不起作用,因为它的许多 | 未转义:

:map ,j :!clear; grep -E '^\s+\S+: {|\() {$|<script>|import' %
                                    ^      ^        ^

Vim 报告的确切错误是由以下构造引起的:

{|\(

Vim 认为 | 是两个 Vim 命令之间的分隔符,所以你得到一个 Vim 命令:

:!clear; grep -E '^\s+\S+: {

(无论如何执行一个无聊的外部命令),然后是第二个:

:\() {$|<script>|import' %

这真的没有意义。这是导致错误的 \ 。如果您转义第一个 |,您将得到由第二个 | 引起的不同错误,然后是第三个 |.

引起的另一个错误

转义那些 | 以使您的映射“有效”:

:map ,j :!clear; grep -E '^\s+\S+: {\|\() {$\|<script>\|import' %
                                    ^^      ^^        ^^

我将“工作”放在引号中,因为这些映射非常笨重。

  1. 最后需要一个<CR>这样你就不用回车执行命令了:

    :map ,p :!clear; grep -E "def \|class " %<CR>
    :map ,j :!clear; grep -E '^\s+\S+: {\|\() {$\|<script>\|import' %<CR>
    
  2. 它们应该限制在正常模式下,除非你真的希望它们也被定义为视觉、select 和 operator-pending 模式:

    :nmap ,p :!clear; grep -E "def \|class " %<CR>
    :nmap ,j :!clear; grep -E '^\s+\S+: {\|\() {$\|<script>\|import' %<CR>
    
  3. 由于您似乎并没有故意在映射中使用其他映射,因此最好将它们设为 non-recursive:

    :nnoremap ,p :!clear; grep -E "def \|class " %<CR>
    :nnoremap ,j :!clear; grep -E '^\s+\S+: {\|\() {$\|<script>\|import' %<CR>
    
  4. 而且,由于您在脚本中,您可以安全地删除冒号:

    nnoremap ,p :!clear; grep -E "def \|class " %<CR>
    nnoremap ,j :!clear; grep -E '^\s+\S+: {\|\() {$\|<script>\|import' %<CR>
    

干净多了!

现在,我想我们将保留下一个谜团,即为什么您使用外部工具而不是 :help :global、评论……或另一个问题。