Set a default syntax by filetype?


#1

For the time being, I’d like to tell my Handlebars files to use HTML syntax highlighting. I assume I can do that in init.coffee but I’m unaware how to find the available methods to call on editor as per the example there.

    atom.workspaceView.eachEditorView (editorView) ->
      editor = editorView.getEditor()
      if path.extname(editor.getPath()) is '.hbs'
        editor.whatGoesHere(HTML) # <= This part?

#2

I think it should be ::setGrammar(grammar). Did you try it?

Check the API Documentation for details


#3

How did you end up doing it? I’m having trouble on how to load grammers atm :confused:


#4

I’m afraid I haven’t been able to wrap my head around grammars either. To be fair though, I haven’t had time to fiddle with it much.


#5

@eriklebsen check this package, and how they do it.

https://github.com/atom/grammar-selector/blob/master/lib/grammar-list-view.coffee#L37


#6

@AbeEstrada: It looks like setGrammarOverrideForPath() needs absolute paths (at least, I couldn’t get wildcards to work).


#7

@eriklebsen: As @DiogoAndre said, setGrammar() is the method you use to set the grammar for a particular editor.

The grammars are all keyed to their Scope name. The Scope for the language-html package is “text.html.basic” (you can check it in the preferences).

You can grab grammars from atom.syntax. Here’s a simple example (see also 2650#4 for more details):

# init.coffee
path = require 'path'

atom.workspaceView.eachEditorView (editorView) ->
  editor = editorView.getEditor()
  return unless path.extname(editor.getPath()) is '.hbs'
  htmlGrammar = atom.syntax.grammarForScopeName 'text.html.basic'
  return unless htmlGrammar?
  editor.setGrammar htmlGrammar

#8

I made the file-types package. Check it out if you get a chance.


#9
  # init.coffee
  path = require 'path' 

  atom.workspaceView.eachEditorView (editorView) ->
    editor = editorView.getEditor()
    editorPath = editor.getPath()
    ext = path.extname(editorPath)
    console.log(editorPath)
    if ext is '.rb'
      if /app\/(controllers|helpers|mailers|models)/.test(editorPath) || /db\/(migrate|seeds)/.test(editorPath)
        editor.setGrammar atom.syntax.grammarForScopeName('source.ruby.rails')
    else if ext is '.erb'
      if /app\/views/.test(editorPath)
        editor.setGrammar atom.syntax.grammarForScopeName('text.html.ruby')