Automatically set correct syntax for files with no extension in Sublime Text 3

So maybe you’ve recently setup Rakefile tasks in your ST3 symbol list, or added the ssh_config syntax.  Now you’re getting tired of switching that syntax setting every time and wish it would just default to the correct one based on the file name.  This is fairly easy for files with an extension (just use Syntax -> Open all with current extension…).  For files with no extension we need a plugin though.

I’ve found ApplySyntax to not only be perfectly suited for this task, but also to be great for having DSL-based files open with the correct syntax automatically (e.g. use Rspec syntax instead of plain Ruby).

The installation instructions in the ApplySyntax github readme will get you most of the way there.  The final piece of the puzzle is a snippet like this in your ApplySyntax user settings file:

// Rakefiles
"name": "User/Rakefile",
"rules": [
  {"file_name": ".*/Rakefile$"},
]

These little snippets go in the syntaxes section. Note that the path is included in the file_name so it has to be part of the match expression (this is on purpose so you can match files by what subdir(s) they live in). Here’s a complete example also showing an ssh_config (and sshd_config) rule:

    // Put your custom syntax rules here:
    "syntaxes": [
      {
          // Rakefiles
          "name": "User/Rakefile",
          "rules": [
            {"file_name": ".*/Rakefile$"},
          ]
      },
      {
          // SSH config files
          "name": "SSH Config/SSH Config",
          "rules": [
            {"file_name": ".*/sshd?_config.erb$"},
          ]
      },
    ]

Now that you’ve got Rakefiles loading automatically with the correct syntax, how about populating your symbol list with tasks defined in the Rakefile? 😀

Leave a Reply

Your email address will not be published. Required fields are marked *