Persistent highlighting in Emacs
Posted November 10, 2016 at 09:16 AM | categories: orgmode, emacs | tags:
In this recent post I showed a way to use org-mode links to color text. The main advantage of that approach is it is explicit markup in the file, so it is persistent and exportable to html. The downside of that approach is you cannot use it in code, since the markup will break the code.
An alternative approach is to use overlays to color the text. This allows you to color the text, add annotations as tooltips and to provide a variety of highlighting colors. Overlays are not explicit markup in the file, so it is necessary to think of a way to save them so they can be restored later. We do this by using hook functions to store the overlays in a file-local variable on saving, and a file-local variable to restore the overlays when the file is opened. I bind the primary function `ov-highlighter/body' to a key, in my case hyper-h, which launches a hydra to access the commands.
You can find the code here: https://github.com/jkitchin/scimax/blob/org-9/ov-highlighter.el. Probably around mid-December it will get merged into the master branch.
Here is what this looks like in my buffer:
You may want to see the video:
- blue green pink yellow custom
- Put a comment here.
- Markup a tpyo.
- Get a list of the highlights in the buffer.
These highlights are pretty awesome. They work in code blocks, and comments. They also work in non-org files (only in Emacs of course).
a = 5 b = 6 print(a+b)#print the sum of a and b
Overall, this is pretty handy. You can highlight your own notes, provide feedback to others, etc. without changing the actual text in the document (well, except for the local variables at the end of the buffer, but these are usually in a "comment" that does not affect the document).
Here are few limitations though:
- You can only edit/change the file in Emacs, and the hook functions have to enabled, or the overlay data will get corrupted. That means a merge conflict can ruin the overlays.
- Anyone you share the file with needs to have the ov-highlighter library loaded too. Otherwise they will not see the highlights, and any edits will make the overlay data incorrect.
- The highlights do not export from org-mode (although they do work with `htmlize-buffer'!).
(let* ((html-buffer (htmlize-buffer)) (html (with-current-buffer html-buffer (buffer-string)))) (with-temp-file "test.html" (insert html)) (kill-buffer html-buffer)) (browse-url "test.html")
#<process open test.html>
Copyright (C) 2016 by John Kitchin. See the License for information about copying.
Org-mode version = 9.0