LeetCode Custom Mapping

Apply custom vim mappings to LeetCode's built-in Monaco Vim mode

Verze ze dne 31. 07. 2026. Zobrazit nejnovější verzi.

K instalaci tototo skriptu si budete muset nainstalovat rozšíření jako Tampermonkey, Greasemonkey nebo Violentmonkey.

You will need to install an extension such as Tampermonkey to install this script.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Violentmonkey.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Userscripts.

You will need to install an extension such as Tampermonkey to install this script.

K instalaci tohoto skriptu si budete muset nainstalovat manažer uživatelských skriptů.

(Už mám manažer uživatelských skriptů, nechte mě ho nainstalovat!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Už mám manažer uživatelských stylů, nechte mě ho nainstalovat!)

// ==UserScript==
// @name         LeetCode Custom Mapping
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Apply custom vim mappings to LeetCode's built-in Monaco Vim mode
// @author       thraxis
// @match        https://leetcode.com/problems/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @license      MIT
// ==/UserScript==
(function () {
  "use strict";

  const defaultMappings = [
    { lhs: "jk", rhs: "<Esc>", mode: "insert" },
    { lhs: "jj", rhs: "<Esc>", mode: "insert" },
    { lhs: "H", rhs: "^", mode: "normal" },
    { lhs: "L", rhs: "$", mode: "normal" },
    { lhs: "J", rhs: "5j", mode: "normal" },
    { lhs: "K", rhs: "5k", mode: "normal" },
  ];

  function normalizeEntry(entry) {
    if (entry && typeof entry === "object" && !Array.isArray(entry)) {
      const { lhs, rhs, mode } = entry;
      if (typeof lhs === "string" && typeof rhs === "string" && typeof mode === "string") {
        return { lhs, rhs, mode };
      }
      return null;
    }
    if (typeof entry === "string") {
      const parts = entry.trim().split(/\s+/);
      if (parts[0] === "map" && parts.length >= 4) {
        return { lhs: parts[1], rhs: parts[2], mode: parts[3] };
      }
      return null;
    }
    return null;
  }

  function getMappings() {
    const stored = GM_getValue("mappings", defaultMappings);
    if (!Array.isArray(stored)) {
      console.warn("[LC-Vim] Stored mappings malformed (not an array), resetting to defaults.", stored);
      GM_setValue("mappings", defaultMappings);
      return defaultMappings;
    }
    const normalized = stored.map(normalizeEntry).filter(Boolean);
    if (normalized.length !== stored.length) {
      console.warn("[LC-Vim] Some stored mapping entries were invalid and were dropped.", stored);
    }
    return normalized;
  }

  function applyMappings() {
    if (!unsafeWindow.monacoVim || !unsafeWindow.monacoVim.VimMode || !unsafeWindow.monacoVim.VimMode.Vim) {
      return false;
    }
    const V = unsafeWindow.monacoVim.VimMode.Vim;
    getMappings().forEach(({ lhs, rhs, mode }) => {
      try {
        V.map(lhs, rhs, mode);
        console.log(`[LC-Vim] Mapped ${lhs} -> ${rhs} (${mode})`);
      } catch (e) {
        console.error("[LC-Vim] Failed to map:", lhs, rhs, mode, e);
      }
    });
    return true;
  }

  function startPolling() {
    let tries = 0;
    const maxTries = 60;
    const interval = setInterval(() => {
      tries++;
      if (applyMappings()) {
        clearInterval(interval);
        console.log("[LC-Vim] Mappings applied.");
      } else if (tries >= maxTries) {
        clearInterval(interval);
        console.log("[LC-Vim] Gave up waiting for Vim mode (not enabled on this page?).");
      }
    }, 1000);
  }

  startPolling();

  let lastUrl = location.href;
  new MutationObserver(() => {
    if (location.href !== lastUrl) {
      lastUrl = location.href;
      startPolling();
    }
  }).observe(document.body, { childList: true, subtree: true });

  function mappingsToText(mappings) {
    return mappings.map((m) => `map ${m.lhs} ${m.rhs} ${m.mode}`).join("\n");
  }
  function textToMappings(text) {
    return text
      .split("\n")
      .map((line) => normalizeEntry(line))
      .filter(Boolean);
  }

  GM_registerMenuCommand("Edit Mappings", () => {
    const current = mappingsToText(getMappings());
    const newText = prompt(
      'Enter mappings (one per line, e.g., "map jk <Esc> insert"):',
      current
    );
    if (newText !== null) {
      const arr = textToMappings(newText);
      GM_setValue("mappings", arr);
      alert("Saved. Reload page for changes to take effect.");
    }
  });

  GM_registerMenuCommand("Reset Mappings to Defaults", () => {
    GM_setValue("mappings", defaultMappings);
    alert("Reset to defaults. Reload page.");
  });
})();