Remember grammar selection for specific files


#1

Is there any way to get Atom to remember the grammar I select for a specific file, on a file-by-file basis, forever, for everything?

I’m working with Markdown files for a Jekyll site but they have lots of HTML written into them. I want them to display with the “Jekyll (HTML)” grammar, but every time I close and reopen any of them they reset to markdown because they’re all .md files. I’d like Atom to remember the grammar that I select, and always open a specific file with the grammar that I’ve chosen for that file.

If this isn’t a feature yet then I’d like to request it! I’m new to hacking Atom but I’d also be interested in working on a package for this.


#2

It’s easily doable. You’d just have to decide how you want to remember a particular file’s grammar, and then use editor.setGrammar() whenever that file is opened. You can’t necessarily make a particular file open with a particular grammar forever unless you want to attach data to that specific file. However, you could have a file like .atom-grammars in the folder that has file names associated with grammars. You can do this pretty much any way you want to, but I recommend using forbidden characters as your delimiter, so that you won’t have a file name accidentally mess up your package. Something like this:

post.html: text.html.jekyll

Then your package could watch atom.workspace.observeTextEditors(). When a new TextEditor is added, it would check whether there’s a .atom-grammars file in that folder and whether the file name matches an entry. If so, it would set the grammar.


#3

This is super helpful, thanks! I’m going to mess around with this and see if I can get a package like that working.

One thing I couldn’t understand when I was trying this out in my init script and the Dev Tools: it seems like setGrammar() only works if it’s passed an entire Grammar object, but I can’t figure out how to retreive that object by name. The closest I got was calling something like atom.grammars.getGrammars()[64] and assigning it to a variable, then passing that variable to setGrammar(). Is there an easier way to retrieve grammar objects? Maybe without knowing exactly what order they’re in within atom.grammars?

Thanks!


#4

atom.grammars.grammarForScopeName("text.html.jekyll") will return the Grammar object for Jekyll.


#5

You can set recognition in your config file, see the flight manual for details.