Dienstag, 28. Oktober 2014

Scroll sections with Emacs

Lisp and Scheme programmers often use a form feed to separate source code sections. But this works not very well in other languages. Some people even try to proscribe the use of ^L. Xah Lee suggest the use of § instead. But the paragraph sign has also some limitations. First it is an Unicode symbol and this may cause problems, if you work with Redmond or Java disciples on the same source, because they are limited to UTF-16. Even Perl might be problematic, because Perl's default code page is Latin-1. And second it looks pretty ugly in the code. ;-)

An alternative is to teach Emacs how to recognize major comments. People tend to distinguish comments by varying the number of comment delimiters used to start the comment. In a Bash script it is enough to use one # to start a comment. But major comments are started by two number signs or even three. The same applies to Scheme hackers. They use two semicolons for comments at the beginning of the line, one semicolon for comments in the middle of the line and three for headlines. Instead of teaching Emacs how to find the paragraph sign, it would be much more convenient, if Emacs can jump between the major comments. The following code shows how to do it.

(defun forward-section ()
  "Move cursor forward to next occurrence of a major comment."
  (if (search-forward-regexp "\n\n\\(#\\{2,\\}\\|[;/-]\\{3,\\}\\)" nil t)
    (goto-char (point-max))))

(defun backward-section ()
  "Move cursor backward to previous occurrence of a major comment."
  (let ((p (search-backward-regexp "\n\n\\(#\\{2,\\}\\|[;/-]\\{3,\\}\\)" nil t)))
    (goto-char (if p (+ p 2) (point-min)))))

(define-key global-map (kbd "<C-next>") 'forward-section)
(define-key global-map (kbd "<C-prior>") 'backward-section)

The example works for Bash (##), Scheme and Lisp (;;;), the C languages (///) and SQL (---).

Keine Kommentare: