### Vimium C Substitution Rule Examples Source: https://github.com/gdh1995/vimium-c/wiki/Substitute-URLs-and-text-during-commands Provides practical examples of Vimium C substitution rules. The first example shows how to skip a specific page within a GitHub wiki. The second example demonstrates how to modify the behavior of 'goToRoot' to stop at a project's root directory when on a child page. ```plaintext u@/wiki/?$@@g,host=github.com r@^https://github\.com/[^\s\/?#]+/[^\s\/?#]+(?=/)@@,matched,return ``` -------------------------------- ### Vimium C Dispatch Event Example Source: https://github.com/gdh1995/vimium-c/wiki/Auto-run-a-tree-of-commands Shows how to use the `dispatchEvent` command in Vimium C to simulate events on web pages. This example maps `` to dispatch an event. ```vimium-c map dispatchEvent ``` -------------------------------- ### Example: Invoke ff2mpv 5.0.0+ Source: https://github.com/gdh1995/vimium-c/wiki/Send-dynamic-messages-to-other-extensions Illustrates how to use LinkHints with `sendToExtension` to open a link using the ff2mpv extension. ```APIDOC ## Example: Invoke ff2mpv 5.0.0+ ### Description This example demonstrates configuring Vimium C to use LinkHints to select a link and then send it to the ff2mpv extension for opening. ### Method N/A (Vimium C command) ### Endpoint N/A ### Parameters See `sendToExtension` command documentation for parameter details. ### Request Example 1. **Custom key mappings:** ``` map vvv LinkHints.activateOpenUrl sed="_ff2mpv" # replace the id="**********" with id="ff2mpv@yossarian.net" on Firefox map sendToExtension \ id="ephjcajbkgplkjmelpglennepbpmdpjg" raw ``` *Note: Replace the `id` with the correct one for your browser (e.g., `ff2mpv@yossarian.net` for Firefox).* 2. **Auto substitution of various text:** ``` _ff2mpv@^@@,encode _ff2mpv@^.*@vimium://run1/#data={"type":"openVideo","url":"$0"} ``` ### Response See `sendToExtension` command documentation for response details. ### Notes Refer to https://github.com/gdh1995/vimium-c/issues/1077#issuecomment-1936979906 for more context. ``` -------------------------------- ### Example: Send URL on Vomnibar to another extension Source: https://github.com/gdh1995/vimium-c/wiki/Send-dynamic-messages-to-other-extensions Demonstrates how to map a key to send the currently selected Vomnibar URL to another extension. ```APIDOC ## Example: Send URL on Vomnibar to another extension ### Description This example shows how to configure key mappings and custom search engines to send the selected Vomnibar suggestion URL to another extension. ### Method N/A (Vimium C command) ### Endpoint N/A ### Parameters See `sendToExtension` command documentation for parameter details. ### Request Example 1. **Custom key mappings:** ``` map xxx Vomnibar.activate itemSedKeys="1" sedKeys="1" itemKeyword="sendUrl" map sendToExtension id="ADDONID" raw ``` *Note: Replace `ADDONID` with the actual ID of the target extension.* 2. **Custom search engines:** ``` sendUrl: vimium://run/##data={"type":"create","params":{"url":"$1"}} ``` 3. **Auto substitution:** ``` # always encode a string to ensure "${it}" is a valid JSON string 1@^@@,json ``` ### Response See `sendToExtension` command documentation for response details. ### Notes Refer to https://github.com/gdh1995/vimium-c/issues/573#issuecomment-1114758798 for more context. ``` -------------------------------- ### Vimium C mapKey Directive Example (Vimscript) Source: https://github.com/gdh1995/vimium-c/wiki/Use-in-another-keyboard-layout Demonstrates the 'mapKey' directive in Vimium C for remapping keys. This example shows how to map Cyrillic characters to their corresponding English keys for a Russian/Ukrainian layout. It highlights specific mappings and notes on handling special characters and modes. ```vim mapKey й q mapKey ц w mapKey у e mapKey к r mapKey е t mapKey н y mapKey г u mapKey ш i mapKey щ o mapKey з p mapKey х [ mapKey Х { mapKey ъ ] mapKey Ъ } mapKey ї ] mapKey Ї } # after \ mapKey ё \ mapKey Ё | mapKey ґ \ mapKey Ґ | mapKey ф a mapKey ы s mapKey і s mapKey в d mapKey а f mapKey п g mapKey р h mapKey о j mapKey л k mapKey д l mapKey ж ; mapKey Ж : mapKey э ' mapKey Э " mapKey є ' mapKey Є " mapKey я z mapKey ч x mapKey с c mapKey м v mapKey и b mapKey т n mapKey ь m mapKey б , mapKey Б < mapKey ю . mapKey Ю > # '.' and ',' overrides (disables this keys for mappings) mapKey . / mapKey , ? ``` -------------------------------- ### Building Vimium C from Source Source: https://context7.com/gdh1995/vimium-c/llms.txt Instructions for compiling Vimium C from its TypeScript source code. This involves installing dependencies, running the TypeScript compiler, and using build scripts for packaging. ```bash # Install dependencies npm install typescript npm install pngjs # Only needed for Chromium browsers # Compile TypeScript node scripts/tsc # Build debug package ./scripts/make.sh vimium_c-debug.zip # Alternative: Use gulp for development gulp local # Compile in place with build options gulp dist # Compile and minimize to dist/ ``` -------------------------------- ### Vimium C Key Mapping Example for Toggling Status Source: https://github.com/gdh1995/vimium-c/wiki/Enable-or-Disable-all-frames-by-a-shortcut This example illustrates a Vimium C key mapping that utilizes the `openUrl` command to toggle the Vimium C status. It specifically targets toggling between enabled and disabled states, with an option to define specific keys that should remain active even when the status is disabled. The URL is JSON-encoded, and special characters like '/' are represented by `\u0020` (space). ```vimscript map openUrl url="vimium://status/toggle/^ " ``` -------------------------------- ### Remap Keys and Commands Source: https://github.com/gdh1995/vimium-c/blob/master/pages/options.html Provides examples of custom key mappings and commands for Vimium C. This includes activating link hints, unmapping keys, simulating key presses, creating new tabs, and defining custom shortcuts. ```text map f [LinkHints.activate](# "LinkHints Configuration") unmap mapKey shortcut createTab position="end" url=… shortcut userCustomized1 command="goBack" # "unmapAll" unmaps all above and default ``` -------------------------------- ### Vimium C Dark Mode Styling (CSS) Source: https://github.com/gdh1995/vimium-c/wiki/Style-the-UI-of-Vimium-C-using-custom-CSS Provides CSS examples for styling Vimium C UI elements, particularly when dark mode is active. It shows how to target elements with the 'D' class and style the HUD and Vomnibar background. ```css /* #ui */ .HUD.D:after { background: black; } /* #omni */ #bar { background: #333; } ``` -------------------------------- ### Configure Auto Substitution for ff2mpv Integration Source: https://github.com/gdh1995/vimium-c/wiki/Send-dynamic-messages-to-other-extensions These auto-substitution rules are used in conjunction with the ff2mpv example. The first rule encodes a placeholder, and the second rule constructs the final URL to be opened by ff2mpv, including the video URL. ```vimiumc _ff2mpv@^@@,encode _ff2mpv@^.*@vimium://run1/#data={"type":"openVideo","url":"$0"} ``` -------------------------------- ### Text Substitution Rules for Copy/Paste Source: https://context7.com/gdh1995/vimium-c/llms.txt Text substitution rules define transformations for text during copy and paste operations. The syntax is `keys/regexp/replacement/flags[,actions...]`. Examples include skipping wiki home during goUp, stopping goToRoot at project home on GitHub, decoding base64 content during paste, and converting URLs during copy. ```text # Skip wiki home during goUp u@/wiki/?$@@g,host=github.com # Stop goToRoot at project home on GitHub r@^https://github\.com/[^\s\/?#]+/[^\s\/?#]+(?=/)@@,matched,return # Decode base64 content during paste p@^([A-Za-z0-9+/=]+)$@$1@,base64-decode # Convert URL during copy c@^(https?://[^\s]+)$@$1@,decode ``` -------------------------------- ### Global Shortcuts Configuration Source: https://github.com/gdh1995/vimium-c/wiki/Enable-or-Disable-all-frames-by-a-shortcut This section covers the configuration of global shortcuts for Vimium C, which can be set via browser extension shortcut settings or custom key mappings. It provides an example of mapping a shortcut to open a URL. ```APIDOC ## Global Shortcuts Configuration ### Description This section describes how to configure global shortcuts for Vimium C. These shortcuts can be defined in the browser's extension shortcut settings (e.g., `chrome://extensions/shortcuts`) or through custom key mappings within Vimium C. The functionality of these shortcuts can be arbitrarily defined. ### Method Configuration via browser extension settings or Vimium C custom key mappings. ### Endpoint N/A (Configuration setting) ### Parameters #### Custom Key Mapping Parameters - **`command`** (string): The action to perform when the shortcut is triggered. Common commands include `openUrl`. - **`url`** (string): The URL to open when the `openUrl` command is used. This can be a standard URL or a Vimium C command URL. ### Request Example *Mapping a custom shortcut `User Customized 1` to open a new tab with a specific URL:* In Vimium C's custom key mappings: ``` map userCustomized1 openUrl url="https://example.com" ``` When the global shortcut `User Customized 1` is triggered, a new tab will open to `https://example.com`. ### Response #### Success Response (200) N/A (Configuration setting) #### Response Example N/A ``` -------------------------------- ### Comments in Vimium C Mappings Source: https://github.com/gdh1995/vimium-c/blob/master/README.md Explains how to add comments to key mapping configurations. Lines starting with `"`, `#`, or a space followed by `#` are treated as comments and ignored by Vimium C. ```vimiumc # This is a comment " This is also a comment # This is another comment ``` -------------------------------- ### EditText Command Examples Source: https://github.com/gdh1995/vimium-c/wiki/Trigger-commands-in-an-input-box Demonstrates the usage of the `editText` command with its `run` attribute for text manipulation. This includes replacing selected text, collapsing selections, and modifying selections by moving forward or backward with specified granularities. The `exec` command allows using `document.execCommand`. ```vimiumc # make selected text italic (e.g. in a MarkDown document) map editText run="replace,_$s_" ``` -------------------------------- ### Configure Global Shortcuts Source: https://github.com/gdh1995/vimium-c/wiki/Trigger-commands-in-an-input-box Guides users on configuring global shortcuts via `chrome://extensions/shortcuts` or `about:addons` (Firefox). These shortcuts are generally always active, though browser-level shortcuts may take precedence. Custom commands can be added via Vimium C's options page. ```vimiumc shortcut userCustomized1 command="goBack" ``` -------------------------------- ### Support '' key sequences with custom mappings (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Introduces support for key sequences starting with '', even in command modes. This allows for more complex custom key mappings, such as mapping '' to '' to extract quoted strings. ```JavaScript /* * ``: fix issues and now support key sequences starting with ``, even in command modes. * Example: * mapKey * map " autoCopy sed="s@\"(.*?)\"@$1@,matched" * `Y"` in VisualMode will extract a string between quotes from selected text and then copy it. */ function handleCustomKeySequence(event, mode) { // ... logic to handle custom key sequences like '' ... console.log(`Handled custom key sequence in ${mode} mode.`); } ``` -------------------------------- ### Navigate to Next/Previous Number in URL (Vimium C) Source: https://github.com/gdh1995/vimium-c/wiki/Substitute-URLs-and-text-during-commands The `goNext` and `goPrevious` commands facilitate navigating through numbered sections in URLs. They identify patterns like `${N/[start]:[end]:[step]}` and increment or decrement the number `N` by `step`, using the result to form a new URL. This is often used in conjunction with auto-substitution rules. ```vimiumc n@tid=(\d+)@tid=$${$1/::2}@ ``` -------------------------------- ### Vimium C Simulate Key Press with runKey Source: https://github.com/gdh1995/vimium-c/wiki/Auto-run-a-tree-of-commands Illustrates simulating key presses like 'Escape' using `runKey` with specific key codes and options. It demonstrates how to map a key combination (``) to execute a sequence that includes dispatching events and setting options. ```vimium-c # simluate `Escape` on page scripts by press `Ctrl+]` run #key=Escape%2C27+de-de ``` -------------------------------- ### Vimium C Simulate Arrow Keys with runKey Source: https://github.com/gdh1995/vimium-c/wiki/Auto-run-a-tree-of-commands Demonstrates simulating arrow key presses (`ArrowDown`, `ArrowUp`) using `runKey` and environment variables. It shows how to define reusable environment settings for elements and then use them in `runKey` mappings for complex actions. ```vimium-c env s element="select" env t element="textarea" run #key=ArrowDown%2C40+de+-de,#key=ArrowUp%2C38+de+-de \ expect="t:editText#run=auto%2ccount%2cline;s:scrollSelect" run - ``` -------------------------------- ### Map Keys in Insert Mode (v1.84.1+) Source: https://github.com/gdh1995/vimium-c/wiki/Trigger-commands-in-an-input-box Introduces the ability to map keys that end with `:i` to work within plain insert mode, starting from v1.84.1. These mappings are specific to insert mode and do not apply to global insert modes activated by commands like `enterInsertMode`. Keys starting with `v-` also work in plain insert mode since v1.92.0. ```vimiumc map editText run="auto,forward,line" map v-j editText run="auto,forward,line" ``` -------------------------------- ### Click Links with Keyboard using LinkHints.activate Source: https://context7.com/gdh1995/vimium-c/llms.txt The `LinkHints.activate` command shows hint markers on clickable elements, allowing users to activate links by typing the hint characters. Various options control how links are opened (current tab, new tab, new foreground tab), copied, downloaded, focused, hovered, or selected. Hints can be filtered by CSS selectors or custom clickable elements, and a filtered hints mode can be enabled for text-based filtering. ```text # Default: open link in current tab map f LinkHints.activate # Open in new tab map F LinkHints.activateOpenInNewTab # Open in new foreground tab map LinkHints.activateOpenInNewForegroundTab # Open multiple links in new tabs (queue mode) map LinkHints.activateWithQueue # Copy link URL to clipboard map yf LinkHints.activateCopyLinkUrl # Copy link text map yl LinkHints.activateCopyLinkText # Download link or image map LinkHints.activateDownloadLink # Focus element without clicking map ;f LinkHints.activateFocus # Hover over element map ;h LinkHints.activateHover # Select element and enter visual mode map yv LinkHints.activateSelect # Filter hints by CSS selector map f LinkHints.activate match=".article-link" exclude="[role=heading]" # Add custom clickable elements map f LinkHints.activate clickable=".my-button,.custom-link" # Use filtered hints mode (type link text to filter) # Enable in Options page under "Use link name filtering" ``` -------------------------------- ### Firefox Time Measurement on Windows Source: https://github.com/gdh1995/vimium-c/blob/master/tests/unit/performance-now.md Employs `QueryPerformanceCounter()` for high-resolution time measurement on Windows. If unavailable, it falls back to `GetTickCount64()`, which provides milliseconds since system start. ```c++ #include BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount); ULONGLONG GetTickCount64(void); ``` -------------------------------- ### Open Bookmark and Run Key Tree Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Adds `openBookmark` and `vimium://run/` commands to execute long command sequences with complex options. Supports nested calls but not self-calls. ```vimium add openBookmark and vimium://run/ to run long command sequences with complicated options * now support nested calls (but still refuse to call itself directly) ``` -------------------------------- ### Open URLs with Masks using openUrl Source: https://context7.com/gdh1995/vimium-c/llms.txt The `openUrl` command opens URLs, supporting direct opening, opening in new tabs, and using URL or title masks to dynamically include content from the current tab. It also provides shortcuts for opening copied URLs and focusing existing tabs or launching new ones. ```text # Open URL directly map go openUrl url="https://github.com" # Open in new tab map gO openUrl url="https://github.com" reuse=-1 # Use URL mask to include current page URL map gc openUrl \ url="http://webcache.googleusercontent.com/search?q=cache:$s" \ url_mask="$s" # Use title mask map gt openUrl \ url="https://www.google.com/search?q=$s" \ title_mask="$s" # Open copied URL map p openCopiedUrlInCurrentTab map P openCopiedUrlInNewTab # Focus existing tab or launch new map gf focusOrLaunch url="https://mail.google.com" ``` -------------------------------- ### Key Behavior Rules Source: https://github.com/gdh1995/vimium-c/blob/master/pages/options.html Specifies how Vimium C handles key inputs. If 'Keys' is empty, Vimium C is disabled. If 'Keys' starts with '^', only listed keys are enabled. Otherwise, only listed keys are passed through. ```text If "Keys" is empty, Vimium C gets wholly disabled; if "Keys" starts with "^", only listed keys are enabled, and all others are passed through; otherwise, just the listed keys are passed through. ``` -------------------------------- ### '' sequences work in Find HUD (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Ensures that key sequences starting with '' now function correctly even when the Find HUD (Heads-Up Display) is active. This expands the usability of custom key sequences. ```JavaScript /* * `` sequences: now work even in Find HUD. */ function handleFindHUDInput(event) { // ... logic to process key events, including '' sequences ... console.log("Key event processed in Find HUD."); } ``` -------------------------------- ### Fix broken mapKey in Normal/Insert mode (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Resolves a bug affecting `mapKey <*-*> ` commands in both Normal and Insert modes, which was introduced in versions v1.99.1 and v1.99.2. This ensures that custom key sequences starting with '' function correctly. ```JavaScript /* * Fixes broken `mapKey <*-*> ` in Normal and Insert mode on v1.99.1/2. */ function mapVSequence(mode, keySequence, action) { // ... corrected logic for mapping '' sequences in Normal/Insert mode ... console.log(`Mapped '${keySequence}' in ${mode} mode to '${action}'.`); } ``` -------------------------------- ### Vimium C Global Shortcut Configuration Source: https://github.com/gdh1995/vimium-c/wiki/Enable-or-Disable-all-frames-by-a-shortcut This snippet shows how to configure global shortcuts for Vimium C, typically managed via browser extension shortcut settings (e.g., `chrome://extensions/shortcuts`). It demonstrates mapping a shortcut like 'User Customized 1' to the `openUrl` command, specifying a URL to open in a new tab when the shortcut is triggered. ```vimscript shortcut userCustomized1 command="openUrl" url="..." ``` ```vimscript map openUrl url="vimium://status/toggle-disable/^ " ``` -------------------------------- ### Prepare Window Onload and JavaScript Evaluation Utilities Source: https://github.com/gdh1995/vimium-c/blob/master/tests/unit/simple-js-eval.html This snippet defines utility functions for handling the window's onload event and for evaluating JavaScript code. It includes functions to dynamically load an evaluation script, execute arbitrary JavaScript code safely, normalize code input, and format various data types for display. ```javascript var resultDiv = document.querySelector("#resultDiv") var VApi = { v: null, z: { v: typeof Reflect !== "undefined" ? 51 : 32 }, t: function (_msg) { /* empty */ }} var __filename = null var define = function (depNames, factory) { (factory || depNames)(null, window.simple_eval = {}) }; "use strict"; //#region prepare window.onload = function () { if (VApi.v) { onLoadWrapper() } else { const el = document.createElement("script") el.src = "chrome-extension://hfjbmagddngcpeloejdejnfgbamkjaeg/lib/simple_eval.js" el.onload = onLoadWrapper document.body.appendChild(el) } }; function onLoadWrapper () { setTimeout(onLoad, 100) } var jsEval = function (code) { var error = null, value code = normalizeCode(code) try { value = (VApi.v.tryEval && VApi.v)(code) } catch (e) { error = e } return [code, error ? null : value, error] } var normalizeCode = function (code) { if (typeof code === "function") { code = (code + "") if (code.endsWith("}")) { code = code.slice(code.indexOf("{") + 1, -1) } else if (/^\(\s*\)\s*=>/.test(code)) { code = code.slice(code.indexOf("=>") + 2) } } return code.trim() } var formatCode = function (code) { code = code.trim().replace(/ +/g, " ") return '"' + (code.length > 30 ? code.slice(0, 30).replace(/\n/g, "\\n") + '"\u2026' : code + '"') } var formatAnyObject = function (value) { try { var keys = Object.getOwnPropertyNames(value).concat( Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(value) : [] ), str = "{ " for (var i = 0; i < keys.length; i++) { var key = typeof keys[i] === "symbol" ? "[" + String(keys[i]) + "]" : /[\w$]+/.test(keys[i]) ? keys[i] : JSON.stringify(keys[i]) var desc = Object.getOwnPropertyDescriptor(value, keys[i]) desc.enumerable || (str += "non-E ") if (desc.value) { const val2 = formatValue(desc.value) str += typeof desc.value === "function" && val2[0] !== "(" && !val2.startsWith("function") ? val2 + ", " : key + ": " + val2 + ", " } else { desc.writable || (str += "non-W ") desc.get && (str += formatValue(desc.get) + ", ") desc.set && (str += formatValue(desc.set) + ", ") } } return str.length > 2 ? str.slice(0, -2) + " }" : "{}" } catch (e) {} } var formatFunc = function (value) { return (value + "") .replace(/;(?!\n)/g, ";\n") .replace(/\/\/[^\n]*|\/\*[^\*]*\*\//, "") .replace(/\n\s*\n/g, "\n") .replace(/\n {4} +/g, "\n ") .replace(/'([^'\\]|\\.)*'/g, function(s){ return JSON.stringify(JSON.parse(('"' + s.slice(1, -1) + '"') .replace(/\\(x..|\\)/g, function(_,hex){ return hex.length > 1 ? "\\u" + hex : "\\"}) )) }) } ``` -------------------------------- ### Vimium C Injection Data Attributes (HTML Attribute) Source: https://github.com/gdh1995/vimium-c/wiki/Inject-into-other-extensions These examples show how to use data attributes within the Vimium C injector script tag to control its behavior. '[data-block-focus]' controls focus grabbing, and '[data-vimium-hooks=false]' disables event listener hooking. ```html ``` ```html ``` -------------------------------- ### Open Vomnibar After Creating New Tab in Vimium C Source: https://github.com/gdh1995/vimium-c/wiki/Auto-run-a-tree-of-commands Shows different methods to open the Vomnibar after creating a new tab. This includes using $then with Vomnibar.activate or a predefined mapping 'o', and using the runKey or shortcut directives with chained commands. ```vimium-c map t createTab $then="Vomnibar.activate" map t createTab $then="o" map t runKey keys="createTab+Vomnibar.activate" # since v1.93.0 shortcut createTab $then="o" ``` -------------------------------- ### Vimium C runKey Command with Tree Syntax Source: https://github.com/gdh1995/vimium-c/wiki/Auto-run-a-tree-of-commands Demonstrates the `runKey` command's ability to execute complex command trees with conditional logic and sequential execution. It supports various node types (key, list, branching) and execution orders, with options for overriding behavior. ```vimium-c map W scrollToTop map i runKey keys="focusInput?:(mainFrame:W+150wait)%cfocusInput" \ o.keep o.select="all-line" o.reachable \ o.prefer="#js-issues-search,#searchEngines" ``` -------------------------------- ### Send Messages to Other Extensions using sendToExtension Source: https://github.com/gdh1995/vimium-c/wiki/Send-dynamic-messages-to-other-extensions The `sendToExtension` command allows Vimium C to send messages to other installed extensions. It takes an extension ID, message data, and a raw flag to control the message format. The target extension must be configured to accept external messages. ```vimiumc map sendToExtension id="ADDONID" raw ``` ```vimiumc map sendToExtension \ id="ephjcajbkgplkjmelpglennepbpmdpjg" raw ``` -------------------------------- ### Join search engine queries with %20 for vimium://run (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Modifies how queries are handled for `vimium://run` links within search engines. Queries are now joined by '%20' (space) by default, ensuring proper URL formation and execution. ```JavaScript /* * `vimium://run` in search engines: queries are joined by `%20` by default. */ function formatRunQuery(queries) { return queries.join('%20'); } ``` -------------------------------- ### Add path support for add/open bookmark (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Introduces support for 'path' when adding or opening bookmarks. This allows bookmarks to be organized within folders, improving bookmark management. ```JavaScript /* * Add/open bookmark: add `path` and support both folders and URL nodes. */ function manageBookmark(action, url, path = '') { // ... logic to add or open bookmark with path support ... console.log(`Bookmark ${action} with path: ${path}`); } ``` -------------------------------- ### Construct URL with Current Tab Info (Vimium C) Source: https://github.com/gdh1995/vimium-c/wiki/Substitute-URLs-and-text-during-commands The `openUrl` command allows constructing new URLs using information from the current tab. It requires `url` and `url_mask` options to define the template and how to fill it with data like the current URL, host, or title. The `url_mask` determines if the URL is encoded or raw. ```vimiumc map xxx openUrl url="http://webcache.googleusercontent.com/search?q=cache:$s" url_mask="$s" ``` -------------------------------- ### Vimium C Force Dark Mode Hint Styling Workaround (CSS) Source: https://github.com/gdh1995/vimium-c/wiki/Style-the-UI-of-Vimium-C-using-custom-CSS Presents a workaround using CSS to adjust hint character appearance when 'Force Dark Mode' causes readability issues, focusing on changing background colors. This method is effective in older Chromium versions. ```css .LH, .D>.LH { background: green; } .LH { border: /*!DPI*/ 1px solid lightgreen; } /* #omni */ .s { background-color: #d8e3f3; } ``` -------------------------------- ### Vimium C Force Dark Mode Hint Styling (CSS) Source: https://github.com/gdh1995/vimium-c/wiki/Style-the-UI-of-Vimium-C-using-custom-CSS Offers CSS solutions for improving the readability of hint characters when Chrome's 'Force Dark Mode for Web Contents' flag is enabled. It includes styles for hint characters and their backgrounds, along with Vomnibar styling. ```css .LH, .D>.LH { background: linear-gradient(hsl(56deg 100% 30%),hsl(42deg 100% 25%)); color: #f1f1f1; } ``` -------------------------------- ### Vimium C UI Styling Structure (CSS) Source: https://github.com/gdh1995/vimium-c/wiki/Style-the-UI-of-Vimium-C-using-custom-CSS Defines the basic structure for applying custom CSS rules to different Vimium C UI components using CSS comments as section identifiers. These comments help organize styles for the HUD, Vomnibar, FindBar, and specific states. ```css /* #ui */ [ Rules for the HUD and Hints go here. ] /* #omni */ [ Rules for the Vomnibar go here. ] /* #find */ [ Rules for the FindBar (inside the iframe) go here. ] /* #find:host */ [ Rules _for web pages while only enabled when there's a FindMode_ go here. ] /* #find:selection */ [ When Vimium C executes find and there's at least one match, this can be used to change styles of the selection area ] ``` -------------------------------- ### Chain Commands with $then and $else in Vimium C Source: https://github.com/gdh1995/vimium-c/wiki/Auto-run-a-tree-of-commands Demonstrates how to execute a subsequent command based on the success or failure of a previous command using $then and $else options. These options can be appended to most commands and support inline options as suffixes. The default chain length is 7 commands, extendable with $retry. ```vimium-c map i scrollToTop $then="focusInput" $else="" map mainFrame $then="focusInput" ``` -------------------------------- ### Plain insert mode key mapping for shortcuts (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Enables the creation of shortcuts in plain insert mode using `mapKey x `. This allows users to define custom key sequences that trigger specific actions, similar to using ':' followed by a command. ```JavaScript /* * Plain insert mode: now allow `mapKey x ` to create shortcuts like `:` + `xxx`. */ function mapInsertModeKey(key, action) { // ... logic to map keys in insert mode ... console.log(`Mapped insert mode key '${key}' to action '${action}'.`); } ``` -------------------------------- ### JavaScript to manage dialog and element positioning Source: https://github.com/gdh1995/vimium-c/blob/master/tests/dom/firefox-position_fixed-in-dialog.html This JavaScript code checks for the existence of the HTMLDialogElement constructor. If not available, it appends a message to the DOM. Otherwise, it starts a test function that opens a modal dialog and sets up an event listener to toggle the 'position' style of an element with ID 'omni' between 'absolute' and 'fixed'. ```javascript const test = document.querySelector('#test') if (typeof HTMLDialogElement !== "function") { test.previousElementSibling.append( document.createElement("br"), "Please enable on about:config firstly!") } else { setTimeout(start, 100) } function start() { test.firstElementChild.showModal() test.querySelector("button").onclick = () => { const el = test.querySelector("#omni") el.style.position = "absolute"; setTimeout(() => { el.style.position = "fixed"; }, 300) } // const dialog = document.createElement("dialog") // dialog.innerH } ``` -------------------------------- ### Delete Word from Cursor (Bash-like) Source: https://github.com/gdh1995/vimium-c/wiki/Trigger-commands-in-an-input-box This command mimics the bash shell's behavior of deleting a word starting from the current cursor position. It utilizes the `editText` command with specific run options. The `dom` option can be set to true to extend functionality to content-editable elements beyond standard input and textarea fields. ```vimium-c map editText run="extend,forward,word,exec,delete" ``` -------------------------------- ### Vimium Inner URLs for Utility Functions Source: https://context7.com/gdh1995/vimium-c/llms.txt Special `vimium://` URLs provide various utility functions. These include evaluating mathematical expressions, summing numbers, copying text to the clipboard, building URLs from keywords, parsing and re-searching URLs, toggling extension status, navigating URL hierarchies, and pasting from the clipboard converted to a URL. ```text # Mathematical expressions vimium://math 2 * sin(PI / 4) # Returns: 1.414213562373095 vimium://sum 1 2 3 4 # Returns: 10 # Copy to clipboard vimium://copy text-to-copy # Build URL from keyword vimium://url g vimium c # Returns: https://www.google.com/search?q=vimium+c # Parse and re-search URL vimium://parse g https://www.bing.com/search?q=vimium # Toggle extension status vimium://status toggle vimium://status enable vimium://status disable # Navigate URL hierarchy vimium://cd .. https://github.com/user/repo/issues # Returns: https://github.com/user/repo # Paste from clipboard and convert to URL vimium://paste ``` -------------------------------- ### Conditional Command Execution with runKey Source: https://context7.com/gdh1995/vimium-c/llms.txt The `runKey` command allows for conditional mappings and command trees with branching logic. It supports environment definitions, expect/keys attributes for mapping, and simplified syntax with the 'run' directive. It also enables command trees with if-then-else branching and chaining commands with $then and $else. ```text # Define environments for conditional mapping env google host="https://www.google.com/" env youtube host="youtube.com" env input element="input" env textarea element="textarea" # Map key to different commands based on environment map runKey \ expect={"input":"","textarea":""} \ keys="" map editText run="auto,forward,line" map editText run="auto,forward,character" map scrollSelect # Simplified syntax with 'run' directive run expect="input:;textarea:" # Command tree with if-then-else branching # Syntax: condition ? then-branch : else-branch map i runKey keys="focusInput?:(mainFrame+150wait+focusInput)" # Chain commands with $then and $else map i scrollToTop $then="focusInput" $else="mainFrame" # Open Vomnibar after creating tab map t createTab $then="Vomnibar.activate" ``` -------------------------------- ### JavaScript Event Listener Test for handleEvent Source: https://github.com/gdh1995/vimium-c/blob/master/tests/dom/handleevent.html This JavaScript code sets up an event listener test to check the behavior of the 'handleEvent' property when dispatching custom events. It iterates through an array of objects, some with valid 'handleEvent' functions and others with various invalid types, and registers them as listeners. Finally, it dispatches an event and logs the test's start and end. ```javascript var testNode = null, eventName = "test1"; function listen(listener, capture) { document.addEventListener(eventName, listener, capture); } window.onload = function() { var arr = [ {}, { foo: 1 }, { handleEvent: undefined }, { handleEvent: null }, { handleEvent: 1 }, { handleEvent: false }, { handleEvent: {} }, { handleEvent: window.Symbol && Symbol.iterator }, { handleEvent: NaN }, { handleEvent: -1 }, { handleEvent: "adfas", bar: 12 }, { handleEvent: function() {} }, ]; for (const i of arr) { listen(i, false); listen(i, true) } console.log("test start") document.body.dispatchEvent(new Event(eventName)); setTimeout(function() { console.log("test end") }); result.innerText = "Open console to see results of " + arr.length + " tests.\n" + "Chrome 78/92 has no exceptions, but Firefox 70/91 reports 11 errors;\n" + "Chrome should pause if enabling \"pause on caught exceptions\" on DevTools."; } ``` -------------------------------- ### Vimium C Exclusion Rule Key Management Source: https://github.com/gdh1995/vimium-c/wiki/Enable-or-Disable-all-frames-by-a-shortcut This section explains how to configure the 'Keys' property within Vimium C's exclusion rules. The 'Keys' setting can act as an allow list for usable key mappings. If 'keys' starts with '^ ', it defines an explicit allow list; otherwise, it's treated as a space-separated list of composed keys. ```text if `keys` starts with `^ `, then following keys means an allow list ``` ```text if not, the `keys` means a list of "composed keys", separated by space characters ``` -------------------------------- ### LinkHints FocusInput with .clickable Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md The `LinkHints` and `focusInput` commands now consistently include elements matching `.clickable`, even in other modes. This ensures clickable elements are always considered. ```vimium LinkHints/focusInput: always add elements matching .clickable even in other modes ``` -------------------------------- ### Copy Tab Information with Custom Format (Vimium C) Source: https://github.com/gdh1995/vimium-c/wiki/Substitute-URLs-and-text-during-commands The `copyWindowInfo` command enables copying tab information with flexible formatting. The `format` parameter defines the output structure (defaulting to `${title}: ${url}`), and `join` specifies a separator (e.g., `\n`, JSON, or a custom string). It supports filtering tabs by URL parts or titles and can copy information from the current window, browser, or specific tabs. ```vimiumc copyWindowInfo format="${title}: ${url}" join="\n" ``` ```vimiumc copyWindowInfo format="${url}" join="json" type="window" ``` ```vimiumc copyWindowInfo format="${title}" join=", " type="browser" filter="url, example.com" ``` -------------------------------- ### JavaScript: Closures and Array Manipulation Source: https://github.com/gdh1995/vimium-c/blob/master/tests/unit/simple-js-eval.html This code creates an array of functions using a loop and demonstrates how closures work. It also shows how to access and modify array elements. ```javascript assert(function() { let a=[];for(let i = 0; i < 3;i++) {a.push(()=>i)} return [a[0](), a[1](), a[2](), void a.length, void a] }) ``` -------------------------------- ### Vomnibar - Universal Search in Vimium C Source: https://context7.com/gdh1995/vimium-c/llms.txt The Vomnibar offers a unified interface for searching URLs, bookmarks, history, and open tabs directly from the keyboard. It can be activated for general search, or specifically for bookmarks, history, or tabs. The Vomnibar also allows editing the current URL and can be launched with custom options like auto-selection and case-insensitive matching. ```text # Open Vomnibar for URL/bookmark/history map o Vomnibar.activate # Open in new tab map O Vomnibar.activateInNewTab # Search bookmarks only map b Vomnibar.activateBookmarks map B Vomnibar.activateBookmarksInNewTab # Search history only map h Vomnibar.activateHistory # Search open tabs map T Vomnibar.activateTabs # Edit current URL map ge Vomnibar.activateEditUrl map gE Vomnibar.activateEditUrlInNewTab # Vomnibar with custom options map o Vomnibar.activate autoSelect=true icase=true ``` -------------------------------- ### Define Custom Key Sequences with runKey Source: https://github.com/gdh1995/vimium-c/wiki/Map-a-key-to-different-commands-on-different-websites The `runKey` command allows for the definition of custom key sequences, including those that repeat a count or select from a list. The `keys` parameter can be a single sequence, a list of sequences, or a tree structure for more complex logic. This enables advanced navigation and command execution. ```vimiumc # Define base key sequences for caret movement map editText run="auto,forward,line" map editText run="auto,backward,line" map editText run="auto,forward,character" map editText run="auto,backward,character" # Define key sequences for scrolling within select elements map scrollSelect map scrollSelect dir=-1 # Define a key sequence for activating link hints map LinkHints.activateModeToOpenInNewTab # Define a key sequence for activating link hints with a specific selector map LinkHints.activateModeToOpenInNewTab match=".titlelink" # Define a key sequence for activating link hints map LinkHints.activate ``` -------------------------------- ### Define Custom Search Engines Source: https://github.com/gdh1995/vimium-c/blob/master/pages/options.html Allows users to define custom search engines for quick searching. The format involves a name, followed by a URL template where '%s' is replaced by the query. JavaScript execution can also be triggered. ```text a|A|MainName: https://a.com/?q=%s js:|JS: javascript: $S; Run JavaScript key: https://c.com/$s/space=\s\ space_end # this is a comment ``` -------------------------------- ### LinkHints Configuration with then Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Configures following Vomnibar or Visual Mode for LinkHints. This allows for chaining actions after a link hint is selected. ```vimium LinkHints: use then={...} to configure following Vomnibar / Visual Mode ``` -------------------------------- ### enterInsertMode HUD Tip (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md When `hideHUD` is enabled, `enterInsertMode` now displays a tip instead of running silently, providing user feedback. ```javascript enterInsertMode(); // Shows a tip if hideHUD is true. ``` -------------------------------- ### Conditional Key Mappings with runKey (String Expect) Source: https://github.com/gdh1995/vimium-c/wiki/Map-a-key-to-different-commands-on-different-websites The `runKey` command can also use a string format for the `expect` option, especially in older versions of Vimium-C. This format uses colons and semicolons (or commas in newer versions) to separate environment-key mappings. This provides a more concise way to define conditional key sequences. ```vimiumc # Map using a string format for expect (pre v1.92.0 syntax) # map runKey expect="input:;select:," keys="" ``` -------------------------------- ### mapKey with (JavaScript) Source: https://github.com/gdh1995/vimium-c/blob/master/RELEASE-NOTES.md Allows mapping keys using the `` syntax, which is now functional in most command modes and triggers its mapped command. This enhances key mapping flexibility. ```javascript mapKey 'j' ''; // Example: map 'j' to trigger a visual mode command ```