Possible to implement formatting for HTML editor?

Here is a quick-and-dirty add-on that allows you to pretty-format HTML in the HTML editor using js-beautify.

Requirements

  • node.js

Download js-beautify and create add-on

  • Create a new folder in the addons21 folder (assuming beautify_html)
  • Launch a console (Command Prompt, Powershell, Git Bash, etc.) and navigate to beautify_html directory.
  • Download js-beautify
    • npm init -y
    • npm install --save-dev js-beautify
  • Create my-script.js in beautify_html directory and type the following code:
    function getActiveCodeMirror() {
        const cm = [...document.querySelectorAll(".CodeMirror")].find((ele) =>
            ele.contains(document.activeElement)
        );
        return cm ? cm.CodeMirror : cm;
    }
    
    // https://github.com/beautify-web/js-beautify#setting-inheritance-and-language-specific-overrides
    const opt = {
        indent_size: 2,
    };
    
    function beautify() {
        const cm = getActiveCodeMirror();
        cm?.getDoc().setValue(html_beautify(cm.getValue(), opt));
    }
    
  • Create __init__.py in beautify_html directory and type the following code:
    from typing import Any, Optional
    
    import aqt
    
    root = f"/_addons/{__name__.split('.')[0]}"
    js_beautify_path = f"{root}/node_modules/js-beautify/js/lib/beautify-html.js"
    my_script_path = f"{root}/my-script.js"
    
    
    def on_editor_will_show_context_menu(
        webview: aqt.editor.EditorWebView, menu: aqt.qt.QMenu
    ) -> None:
        def callback(inPlainTextInput) -> None:
            if inPlainTextInput:
                menu.addAction("Beautify", lambda: webview.eval("beautify();"))
    
        webview.evalWithCallback("!!getActiveCodeMirror();", callback)
    
    
    def on_webview_will_set_content(
        web_content: aqt.webview.WebContent, context: Optional[Any]
    ) -> None:
        if isinstance(context, aqt.editor.Editor):
            web_content.js.extend((js_beautify_path, my_script_path))
    
    
    aqt.mw.addonManager.setWebExports(__name__, r".+\.js")
    aqt.gui_hooks.webview_will_set_content.append(on_webview_will_set_content)
    aqt.gui_hooks.editor_will_show_context_menu.append(on_editor_will_show_context_menu)
    

How to use this add-on:

  • Right-click on the HTML editor → Click on Beautify command

Demo (Gif)

beautify-html

6 Likes