PyCharm: highlighting for custom filetype

2019-08-06 15:15发布

问题:

In PyCharm, is it possible to define custom rules for syntax highlighting for files, which combine syntax from two different languages?

A bit contrived example: following file should be treated as HTML, except for text in script tags, which should be treated as Python code.

<html>
<p></p>
<script type="text/python">
  v = "something"
</script>
<br />
<script type="text/python">
  print v
</python>
</html>

Bonus points for getting code completion to work as well.

Note that "IntelliLang" extension features don't fit, as in second block it wouldn't see variables declared in previous blocks.

回答1:

I found a blog from jetbrains that details how to do it, and it will work in other languages and inside PyCharm as well (It is noted to work in most of their IDEs). This is an example of having PHP inside of javascript, but should work for you as well.

Syntax Highlighting - This has a brief explanation of what to do, and also has a link that goes to a full blown tutorial on their confluence: Full tutorial

A small snipet from the full tutorial, which you will have to create a custom file extension for it to read both/multiple languages says:

Step 2. Associate new file type with PHP (or other language)

We need to associate the new file type (*.js.php) with PHP (in our case) in Settings | File Types. If you do not want to use such custom extension, then you'll have to assign the full file name as a pattern, which is not recommended.

Please note that this setting is IDE-wide, so this file type association will affect all projects. Therefore, having a custom extension is the best way to proceed with it.