• Login
Community
  • Login

How to format user defined language code?

Scheduled Pinned Locked Moved Help wanted · · · – – – · · ·
2 Posts 2 Posters 1.6k Views
Loading More Posts
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M
    Moutaz Bakier
    last edited by Nov 26, 2021, 7:52 PM

    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?

    P 1 Reply Last reply Nov 27, 2021, 5:48 PM Reply Quote 0
    • P
      PeterJones @Moutaz Bakier
      last edited by Nov 27, 2021, 5:48 PM

      @moutaz-bakier ,

      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 by width or height or color 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.

      1 Reply Last reply Reply Quote 2
      2 out of 2
      • First post
        2/2
        Last post
      The Community of users of the Notepad++ text editor.
      Powered by NodeBB | Contributors