How do I add syntax highlighting to a custom view?


#1

Hello,

I am developing a package which has it’s own settings view (as I want to do a little more than the standard settings provide). In this view I have a list of snippets for different languages. The snippets are wrapped in a <code></code> element and now I want them to be highlighted in the respective language.

I’ve found out that the Atom styleguide view (Packages -> Styleguide -> Show) uses CSS classes like .show-example-html .editor-colors.example-html to support highlighting but I can’t figure how this is done.
I looked into the code on Github, and it looks like it uses the core function $$ of require('space-pen') but I can’t go further than that.

I also took a look into the atom-minimap package, which supports code highlighting. It looks like they use a buffer and then call getGrammar() on it, but how should this work with custom code snippets on a custom view?

I am a bit lost at this point and don’t know in which direction I should head or what else to do.

Edit: Or should I use the <atom-text-editor> element? Adding disabled or readonly attributes doesn’t work, as it is a custom element. Is it possible to make it read only?


#2

If you want Atom to highlight your stuff for you, then atom-text-editor is probably the best way to go. There is no supported API for getting the tokenizer or highlighting information from Atom. (That doesn’t mean people don’t reach into the internals and do it anyway … it just means that they’re ok with the Atom team changing things out from under them without notice.)

On the flip side, atom-text-editor doesn’t support a read-only mode currently. See here for more information:


#3

Thanks for your reply :slightly_smiling:

I am already using internal functions and API as I couldn’t really figure out the official way to solve my problems. Doesn’t feel right at all and I want to switch to the public API soon but for now that works :smiley:

Looks like <atom-text-editor> is the way to go with then.

Edit again:
Another problem I am facing with <atom-text-editor> is that my code isn’t highlighted. It automatically gets data-grammar="text plain null-grammar" assigned, even though I specifically apply another one. Calling addGrammarScopeAttribute() also always returns text plain null grammar. Is there a way to solve this?


#4

You probably need to use TextEditor.setGrammar to set the grammar associated with the text editor in order for it to work the way you want.