Search code examples
emacshidecopyright-display

Hide long copyright message at top of all files


We have 15 line long copyright messages at the top of all our source-code files.

When I have them open in emacs, that wastes a lot of valuable space.
Is there any way to get emacs to always a hide a certain message but still leave it in the file?


Solution

  • You could write a function that narrows your buffer to everything but the first 15 lines.

    (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))))
    

    Then all you need to do is make sure that this function is called for every file that contains a copyright note. This can be done by adding a hook, preferably to the major mode of your file. For instance you could add the above function definition and the following line to your .emacs file:

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

    This would call the function 'hide-copyright-note whenever you open a C file.

    In practice, you would probably want to make your hook-function more clever, either by checking if a copyright note to hide actually exists or by running hide-copyright-note only if a file is in a certain directory etc.

    For instance, to stick with the C example, you could insert the following test into the above function:

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

    As for your other concern:

    When I have them open in emacs, that wastes a lot of valuable space.

    ...or you could just scroll down. To achieve this automatically, we could use the following function instead of 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)))
    

    However, the reason I recommended the first variation is that if you merely scroll down automatically, then whenever you jump to the beginning of the buffer (M-<) you'll have to scroll down again manually. This problem does not occur with the narrowing solution.