reddit / emacs

Change text appearance in buffer

haffnasty · 2022-11-09 22:37
I'm wondering how I can use emacs lisp to change the way text _appears_ in the buffer (without actually modifying the underlying text). Essentially I want to include a "label" of sorts. Specifically, I create presentations using RMarkdown and xaringan (which use remark.js on the backend) in Emacs. Three dashed lines (e.g., "---") marks the beginning of a new slide. At every occurrence of these three dashed lines, I want to display the slide number. So the buffer will look like this: ``` --- # Header for first slide content --- # Header for second slide --- # Header for third slide ``` And what I want the the buffer to look like this: ``` --- Slide 1 # Header for first slide content --- Slide 2 # Header for second slide --- Slide 3 # Header for third slide ``` So after I type "---" with a line break, it will add the slide number. The trick is that I can't _actually_ insert the text though because in order for xaringan to properly break slides, there cannot be anything after the three dashes, not even a line break. How can I do this? If I am in a git project, I can see that magit includes the "+" character at the end of the line without actually modifying the plain text, so this has to be doable, right?
MitchellMarquez42 · 2022-11-10 00:10
What you're looking for is Overlays.
haffnasty · 2022-11-10 00:28
Great! I'll take a look. I couldn't figure out the right term to search and overlays never came up. Thanks!
casouri · 2022-11-10 02:46
On top of that, you can use jit-lock to apply overlay/text property on-the-fly
github-alphapapa · 2022-11-10 20:39
The short answer is to use font-locking. The less short answer is to use font-locking to match text using regexps and apply a face or an overlay to the text to change its appearance. And in order to do that, you'll need to study the Elisp manual section on font-locking and probably some existing code that implements it. Be advised, that section of the manual is not for the faint-hearted, and it will likely require re-reading a few times, and experimentation, but it can be done. As examples, I can recommend code in https://github.com/alphapapa/highlight-function-calls (simple) and https://github.com/alphapapa/prism.el (more complex). For help developing and debugging, I recommend Lindydancer's tools, some of which I list here: https://github.com/alphapapa/emacs-package-dev-handbook#highlighting--font-locking Especially his font-lock-studio package, which can save a lot of time and hair-pulling (it's easy to make a mistake while developing font-locking code that puts Emacs into an infinite loop that is difficult--but not impossible--to escape without killing Emacs).