Limiting the number of lines in the compilation window

For large projects, the output in the compilation window can become quite large. Furthermore, I use the ANSI coloring functionality, so that colored build systems look nice. These two things together can slow down Emacs significantly. However, when the compilation buffer gets so long, the output is most probably only success messages anyway. The errors would already have stopped the compilation process. So I wrote the following function to trim the compilation buffer:
(defun my-limit-compilation-buffer ()
  "This function limits the length of the compilation buffer.
It uses the variable my-compilation-buffer-length to determine
the maximum allowed number of lines. It will then delete the first 
N+50 lines of the buffer, where N is the number of lines that the 
buffer is longer than the above mentioned variable allows."
  (let ((num-lines (count-lines (point-min) (point-max))))
    (if (> num-lines my-compilation-buffer-length)
        (let ((beg (point)))
          (goto-char (point-min))
            (- num-lines my-compilation-buffer-length)
            (/ my-compilation-buffer-length 10) ) )
          (delete-region (point-min) (point))
          (goto-char beg)
Of course, now you still have to register this function to be actually applied to the compilation buffer, so I read about customization variables. And out came this, to introduce a customizable variable for toggling the compilation-trimming behaviour:
(defun set-my-compilation-buffer-length (symbol value)
  (set-default symbol value)
  (if value
      (add-hook 'compilation-filter-hook 'my-limit-compilation-buffer)
    (remove-hook 'compilation-filter-hook 'my-limit-compilation-buffer)

(defcustom my-compilation-buffer-length 2500 
  "The maximum number of lines that the compilation buffer is allowed to store"
  :set 'set-my-compilation-buffer-length)
This is my first shot at such "complex" Emacs Lisp functions, so maybe it's not optimal, and I don't know much about the Emacs Lisp API either. Improvement suggestions are welcome!
Update: Over at Stackoverflow someone pointed me to a function that is already built into Emacs. So here's the alternative solution:
(add-hook 'compilation-filter-hook 'comint-truncate-buffer)
(setq comint-buffer-maximum-size 2000)
This function is used for other comint buffers as well, such as the shell.

No comments:

Post a Comment