How to format user defined language code?
-
We have the following codes:
<head> create object { code_text width 128 height 128 color red } create object { width 128 height 128 color red }
The user-defined language should be formatted as follows:
<head> create object1 { width 128 height 128 color red } create object2 { width 128 height 128 color red }
Can this be done?
-
User Defined Languages are just about syntax highlighting (adding color to keywords) – not about re-formatting your text for you.
If I were trying to reformat a file with structure as simple as you’ve shown, I would just use a few search/replace pairs, all with Search Mode = Regular Expression enabled:
- FIND =
^\h*(?={|}|create)
REPLACE =\t
- FIND =
^\h*(?=width|height|color)
REPLACE =\t\t
Those will change lines that start with any whitespace followed by
{
or}
or create to start with a single tab; and lines that start with any whitespace followed bywidth
orheight
orcolor
into two tabs before the word. If, instead of tabs, you want 4 spaces or 8 spaces per tab, use four spaces or eight spaces in the first replace, and 8 or 16 spaces in the second replace.If the structure is the same, but there are more keywords that are always indented to a certain level, just add them as
|keyword|another
in the list of|
-separated terms above. OTOH, if you actually have more complicated nesting with extra levels of{ ... }
or similar, and the ability for the same keywords to be at different levels depending on how deeply it’s nested, then the simplistic regex I supplied will not be enough.Many languages come with a “pretty print” or “tidy” utility, which allows you to pipe source code through that utility and it will come out with consistent formatting; using the NppExec plugin, you can pipe the active file through that re-formatting utility. @Michael-Vincent showns an example in this linked post of a script that will look at the file extension, and run it through one of many code reformatters, depending on language.
- FIND =