LeetCode Custom Mapping

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

2026/07/31のページです。最新版はこちら

スクリプトをインストールするには、Tampermonkey, GreasemonkeyViolentmonkey のような拡張機能のインストールが必要です。

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

スクリプトをインストールするには、TampermonkeyViolentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、TampermonkeyUserscripts のような拡張機能のインストールが必要です。

このスクリプトをインストールするには、Tampermonkeyなどの拡張機能をインストールする必要があります。

このスクリプトをインストールするには、ユーザースクリプト管理ツールの拡張機能をインストールする必要があります。

(ユーザースクリプト管理ツールは設定済みなのでインストール!)

このスタイルをインストールするには、Stylusなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus などの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus tなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

(ユーザースタイル管理ツールは設定済みなのでインストール!)

このスクリプトの質問や評価の投稿はこちら通報はこちらへお寄せください
// ==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.");
  });
})();