My tenth-grade Latin teacher sometimes became frustrated with a classmate who couldn't keep his attention on the text. She would say over and over again, “You've got to focus. You've simply got to focus.”
Sometimes, it's important to study one fragment of code deeply,
ignoring everything else. Perhaps it's part of someone else's code, or
it's something you're debugging, or it implements a tricky algorithm.
Emacs's narrowing commands, e.g. narrow-to-defun
, are helpful for that. They make everything in a buffer invisible
except for the part you're concentrating on.
I often find myself needing to peek at the surrounding context, then
return to my primary focus. But it's distracting to have to specify
the narrowed region repeatedly. It's a little thing, but when I'm
trying to concentrate with all my might, getting right back to the
task at hand is crucial. To solve that problem, I wrote narrow-to-focus
, listed below. If the region is active, it narrows to that region.
Otherwise, it narrows to the part of the buffer that it was last used
on. Now, I can shift into and out of focus without having to think
about it.
(defun narrow-to-focus (start end) "If the region is active, narrow to region, marking it (and only it) for the future. If the mark is not active, narrow to the region that was the most recent focus." (interactive "r") (cond ((use-region-p) (remove-overlays (point-min) (point-max) 'focus t) (let ((overlay (make-overlay start end))) (overlay-put overlay 'focus t) (narrow-to-region start end))) (t (let ((focus (seq-find (lambda (o) (overlay-get o 'focus)) (overlays-in (point-min) (point-max))))) (when focus (narrow-to-region (overlay-start focus) (overlay-end focus))))))) (define-key global-map "\C-xnf" 'narrow-to-focus)
Thank you, Mrs. Sarbanes.