【问题标题】:Can I have Vim ignore a license block at the top of a file?我可以让 Vim 忽略文件顶部的许可证块吗?
【发布时间】:2011-01-16 00:57:44
【问题描述】:

有没有办法使用折叠或其他 Vim 脚本黑魔法来隐藏文件顶部的许可证块?我不喜欢它们占据我编辑窗格的这么大一部分;当我第一次打开文件时,我喜欢了解文件在做什么,而不是满脸的样板。

【问题讨论】:

  • 你想忽略的文本格式是什么?

标签: vim plugins licensing folding boilerplate


【解决方案1】:

我为此创建了一个小型 vim 插件。当页面的第一条评论应该被折叠时,它会占卜。它适用于我的测试用例,但是,当然,欢迎任何改进。添加其他单行或多行标识符应该很容易。

得到它here。要安装,就像任何其他插件一样,只需将其放入 ~/.vim/plugin。

编辑:更改了 vim.org 的链接并清理了答案

【讨论】:

  • 你为什么不把这个 vim.org 作为脚本提交?
【解决方案2】:

在自动命令中试试这个。

function! FoldCopyright
  if !exists( "b:foldedCopyright" )
    let b:foldedCopyright = 1
    1,15fold
  endif
endfunction

适当调整第 4 行的范围。在最坏的情况下,版权开始于不同的位置并且是可变长度的,这种模式应该这样做:

1,/Beginning of copyright/;/End of copyright/

【讨论】:

  • 我建议在 fold 命令前使用 silent!,这样如果许可证块不存在,Vim 不会抱怨。
【解决方案3】:

这取决于许可证块是否有一致的形式以及您使用的编程语言。例如,python 倾向于使用“foldexpr”来定义折叠,因此要添加它,您必须替换现有功能与新功能(或摆脱现有折叠)。我相信 C 中的默认设置是使用手动折叠(尽管我自己可能是这样配置的:我不记得了),所以添加额外的折叠要容易得多。

使用本文末尾的简单 GPL 版权信息,您可以将 foldmethod 设置为手动并拥有一个创建折叠的简单函数。这一切都取决于版权的形式以及维护现有折叠对您的重要性。恐怕我需要更多细节才能给出更有用的答案。无论如何,这里有一个示例脚本,可用于折叠本文末尾的版权声明:

function! CreateCopyrightFold()
    let InCopyright = 0
    set foldmethod=manual
    for Line in range(1,line('$'))
        let LineContents = getline(Line)
        if LineContents !~ "^#"
            if InCopyright
                let CopyrightEnd = Line - 1
                exe CopyrightStart . ',' . CopyrightEnd . 'fold'
            endif
            break
        elseif LineContents =~ "Copyright"
            let InCopyright = 1
            let CopyrightStart = Line
        endif
    endfor
endfunction
au BufRead *.py call CreateCopyrightFold()

假设有这样的版权声明:

# Copyright (C) 2009 Some Company or Something
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys
# Code continues...

【讨论】:

    【解决方案4】:

    删除它们怎么样?认真的。

    源代码受版权所有权和许可的保护,而不是样板文件。它不需要在那里——至少在大多数情况下是这样。

    在 GPL 和其他类似方案确实需要文本存在的情况下,可以将其移动到文件的底部或其他任何地方。

    【讨论】:

    • 如果希望人们首先阅读相关的许可证信息怎么办? Vim 足够强大,可以自动轻松地折叠它,所以这没什么大不了的......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 2019-05-15
    相关资源
    最近更新 更多