Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/* enables CodeMirror syntax highlighting on Minerva (aka the mobile skin) */

(() => {
  if (mw.config.get("skin") !== "minerva") return;

  const TEXTAREA_SELECTOR = "#wikitext-editor";
  let last_textarea = null;

  async function enable_code_mirror($textarea) {
    if (!$textarea.length) return;

    const textarea = $textarea[0];
    if (textarea === last_textarea) return;
    last_textarea = textarea;

    try {
      const require = await mw.loader.using([
        "ext.CodeMirror",
        "ext.CodeMirror.mode.mediawiki",
      ]);

      const CodeMirror = require("ext.CodeMirror");
      const { mediawiki } = require("ext.CodeMirror.mode.mediawiki");
      const { EditorView } = require("ext.CodeMirror.lib");

      // sync changes back to the textarea
      const sync = EditorView.updateListener.of((update) => {
        if (update.docChanged) {
          textarea.value = update.state.doc.toString();
          textarea.dispatchEvent(new Event("input", { bubbles: true }));
          textarea.dispatchEvent(new Event("change", { bubbles: true }));
        }
      });

      const cm = new CodeMirror(textarea, mediawiki());
      cm.initialize([cm.defaultExtensions, sync]);

      console.log("CodeMirror enabled");
    } catch (e) {
      console.error("Failed to enable CodeMirror:", e);
    }
  }

  mw.hook("mobileFrontend.editorOpened").add(() => {
    const $textarea = $(TEXTAREA_SELECTOR);
    enable_code_mirror($textarea);
  });
})();