4

How does org-mode implement syntax highlighting for code blocks? More specifically, for a C file, does it use cc-mode or does it have its own algorithm? For example, if I have this org file: test.org:

* Example source code in C: 

#+BEGIN_SRC c
#include <stdio.h>

int main() {
    printf( "Hello world\n" );
    return 0;
}
#+END_SRC

I get the following highlighting:

enter image description here


But if have the same pure C file (using cc-mode) test.c:

#include <stdio.h>

int main() {
    printf( "Hello world\n" );
    return 0;
}

I get:


enter image description here


Notice that printf has different face color in the two files. So it seems like org-mode has its own syntax highlighting. It is not using cc-mode to do the highlighting, is that correct?

1 Answer 1

5

It uses cc-mode.

It copes the text to a temporary buffer, highlights it using the major mode that is associated with the language, and copies back the highlighting.

In addition, it makes everything not highlighted grey. In addition to the difference you spotted in printf, this is also visible in other places like the braces and parentheses.

2
  • Where could one find the source code for org mode doing this? I understand it's probably hairy, but a pointer to some part of it would be much appreciated. Looking to implement something similar for a minor mode in a completely different context (lit-html)
    – Reed Spool
    Commented Jan 23, 2020 at 6:36
  • Check out org-src.el. I found org-src-font-lock-fontify-block enlightening. See how it's used in org.el in org-fontify-meta-lines-and-blocks-1. In Emacs you can do C-h f org-src-font-lock-fontify-block RET and tab to the link for the installed source code or find it on Org Mode's Gogs hosting.
    – Winny
    Commented Mar 5, 2020 at 8:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.