Code Formatting with Komodo IDE

How many times have you copied a large chunk of HTML or XML from a web page or software application and pasted it into Komodo IDE, only to find that it's either all on one line or not indented properly, and thus a nightmare to read? What about if you need to ensure your CSS or JavaScript code is formatted properly before you commit it? How can you ensure your Python code is correctly indented?

The answers to these, and similar questions is Komodo IDE's code formatting features. By feeding your code through a known formatter, Komodo IDE makes it easy to ensure your code is consistent and readable. You can even format your source files automatically upon saving via a user script. Let us explore these two ideas.

Formatting

Komodo's formatting features live in the "Code > Format" menu and sub-menus. Given this untidy stream of HTML:


<html><head><title>Hi</title></head><body><h1>Hello World!</h1></body></html>

Piping it through Komodo's "Code > Format > Document using > XML Tidy" yields a much more tidy:


<html>
    <head>
        <title>Hi</title>
    </head>
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

Similarly, Komodo can reformat code in other languages like CSS, JavaScript, and Python. You can add your own formatter by going to "Edit > Preferences", selecting "Formatters", clicking on the "Create a new formatter...", and then filling in the dialog prompts.

Auto-Formatting on Save

Formatting code manually can be tedious, and it can be easy to forget to do it. Fortunately, Komodo IDE gives you the tools to easily automate this process, such as immediately upon saving the file. Simply go to "Tools > Macros > Create New Macro", give it a name, and then enter the following JavaScript command:

ko.commands.doCommandAsync('cmd_format')

Then, in the "Triggers" tab at the top of the dialog, check the "Userscript should trigger on a Komodo event", and then select "Before file save".

Now every time you save a source file, its associated formatter will run. If no formatter has been configured for your language, Komodo will discreetly remind you.

Conclusion

Dealing with badly, or potentially badly, formatted code should not be a hassle. Komodo IDE's code formatting features make this process easy by using existing and user-configured formatters, and by providing the ability to automate the process too.