5

我们所有源代码文件的顶部都有 15 行长的版权信息。

当我在 emacs 中打开它们时,会浪费很多宝贵的空间。
有什么方法可以让 emacs 始终隐藏某个消息但仍将其保留在文件中?

4

3 回答 3

9

您可以使用hideshow 次要模式,这是一个标准的内置包,它有一个通用命令hs-hide-initial-comment-block,可以执行您想要的操作,而无需知道顶部评论部分有多长。您可以将其添加到任何语言的模式挂钩中,但这里有一个使用 C 的示例:

(add-hook 'c-mode-common-hook 'hs-minor-mode t)
(add-hook 'c-mode-common-hook 'hs-hide-initial-comment-block t)

请注意,它不仅仅隐藏版权,还隐藏完整的初始评论块,它也可能隐藏有用的文档。

于 2012-12-24T04:40:44.097 回答
3

您可以编写一个函数,将缓冲区缩小到除前 15 行之外的所有内容。

(defun hide-copyright-note ()
  "Narrows the current buffer so that the first 15 lines are
hidden."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (forward-line 15)
    (narrow-to-region (point) (point-max))))

然后,您需要做的就是确保为每个包含版权说明的文件调用此函数。这可以通过添加一个钩子来完成,最好是添加到文件的主要模式中。例如,您可以将上述函数定义和以下行添加到您的 .emacs 文件中:

(add-hook 'c-mode-hook 'hide-copyright-note)

每当您打开 C 文件时,这将调用函数“hide-copyright-note”。

在实践中,您可能希望通过检查要隐藏的版权说明是否确实存在或仅在文件位于某个目录中时运行 hide-copyright-note 等来使您的挂钩功能更聪明。

例如,要坚持使用 C 示例,您可以将以下测试插入到上述函数中:

(defun hide-copyright-note ()
  "Narrows the current buffer so that the first 15 lines are
hidden."
  (interactive)
  (when (copyright-message-p)
    (save-excursion
      (goto-char (point-min))
      (forward-line 15)
      (narrow-to-region (point) (point-max)))))

(defun copyright-message-p ()
  "Returns t when the current buffer starts with a Copyright
note inside a C-style comment"
  (save-excursion
    (goto-char (point-min))
    (looking-at "\\s */\\*\\(:?\\s \\|\\*\\)*Copyright\\b")))

至于你的其他顾虑:

当我在 emacs 中打开它们时,会浪费很多宝贵的空间。

...或者您可以向下滚动。为了自动实现这一点,我们可以使用以下函数代替hide-copyright-note

(defun scroll-on-copyright ()
  "Scrolls down to the 16th line when the current buffer starts
with a copyright note."
  (interactive)
  (when (copyright-message-p)
    (goto-char (point-min))
    (beginning-of-line 16)
    (recenter 0)))

但是,我推荐第一种变体的原因是,如果您只是自动向下滚动,那么无论何时跳到缓冲区的开头 ( M-<),您都必须再次手动向下滚动。缩小解决方案不会出现此问题。

于 2011-02-07T17:41:22.077 回答
2

看看折叠模式。基本上,您所需要的只是一种方法来识别要折叠的部分,然后使用folding-top-markfolding-bottom-mark标记它们。顺便说一句,EMACS elisp 代码有一些技巧可以做到这一点,所以你应该很容易找到可以修改的代码。

于 2011-02-07T16:08:54.283 回答