Sublime Text 3 — Set Different Syntax for Specific Directories

How to set a different Syntax for same file type that belongs to different directory using Sublime Text?

There are times we would like to set a specific syntax for files inside a specific directory in Sublime Text. For example, you have directory called Posts and scripts. Inside those directories, there are files which have the same file type. For example, .ctp files. And we would like to set different syntax specifically for those files in that folder. In order to achieve that, follow the steps below:

Step-by-step Guide

Let us assume that the syntax for all .ctp files are set to PHP. And we’re going to have a directory structure like below:

View |- Posts | |- index.ctp |- Elements | |- Posts | |- element.ctp | |- scripts | |- modal.ctp

Our target is to apply all .ctp files inside View/Elements/scripts/ directory to use the JavaScript syntax.

To do this:

  1. We need to install a plugin called ApplySyntax.
  2. Once you have the ApplySyntax plugin installed, open the user settings of ApplySyntax. For Mac users, you just have to go to Sublime Text → Preferences → Package Settings → Apply Syntax → Settings. And add the settings below:
"default_syntaxes": [ { "syntax": "JavaScript/JavaScript", "rules": [ {"file_path": ".*/scripts/.*\\.ctp$"}, ] }, ],

Now try to restart Sublime Text and check your files inside scripts directory and other files from different directory. You’ll notice that they are now using different syntax.