### Obsidian Plugin Setup and Event Handling (TypeScript) Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt Sets up an Obsidian plugin, registers settings, a command palette action, and hooks into the editor-paste event to handle URL conversions. It manages plugin lifecycle events like loading and unloading. ```typescript import { Editor, MarkdownView, Plugin } from "obsidian"; import UrlIntoSelection from "./core"; import { PluginSettings, UrlIntoSelectionSettingsTab, DEFAULT_SETTINGS } from "./setting"; export default class UrlIntoSel_Plugin extends Plugin { settings: PluginSettings; // Paste event handler pasteHandler = (evt: ClipboardEvent, editor: Editor) => UrlIntoSelection(editor, evt, this.settings); async onload() { console.log("loading url-into-selection"); // Load saved settings await this.loadSettings(); // Register settings tab this.addSettingTab(new UrlIntoSelectionSettingsTab(this.app, this)); // Register command palette command this.addCommand({ id: "paste-url-into-selection", name: "Paste URL into selection", editorCallback: async (editor: Editor) => { const clipboardText = await navigator.clipboard.readText(); UrlIntoSelection(editor, clipboardText, this.settings); }, }); // Hook into paste event this.app.workspace.on("editor-paste", this.pasteHandler); } onunload() { console.log("unloading url-into-selection"); // Clean up event listeners this.app.workspace.off("editor-paste", this.pasteHandler); } async loadSettings() { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } } // Example usage scenarios: // Scenario 1: User selects "documentation" and pastes "https://docs.example.com" // Result: [documentation](https://docs.example.com) // Scenario 2: User selects "https://github.com" and pastes "GitHub Repository" // Result: [GitHub Repository](https://github.com) // Scenario 3: User has cursor on word "README", settings.nothingSelected = autoSelect // Pastes "https://github.com/user/repo/blob/main/README.md" // Result: [README](https://github.com/user/repo/blob/main/README.md) // Scenario 4: Empty selection, settings.nothingSelected = insertInline // Pastes "https://example.com" // Result: [](https://example.com) with cursor positioned at ch=1 // Scenario 5: User in markdown link [text](|) where | is cursor // Pastes "https://example.com" // Result: [text](https://example.com) - no double wrapping ``` -------------------------------- ### Configure Obsidian URL Plugin Settings Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt Demonstrates how to configure various settings for the Obsidian URL Into Selection plugin. Includes examples for default settings, auto-selecting words, inserting inline links, inserting bare URLs, and image embed whitelisting. Settings are managed via the 'PluginSettings' interface. ```typescript import { PluginSettings, NothingSelected, DEFAULT_SETTINGS } from "./setting"; import { Plugin, PluginSettingTab, Setting } from "obsidian"; // Default settings const defaultSettings: PluginSettings = { regex: /^[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/.source, nothingSelected: NothingSelected.doNothing, listForImgEmbed: "" }; // Custom settings example 1: Auto-select word behavior const autoSelectSettings: PluginSettings = { regex: DEFAULT_SETTINGS.regex, nothingSelected: NothingSelected.autoSelect, // Automatically selects word at cursor listForImgEmbed: "" }; // Custom settings example 2: Insert inline link template const insertInlineSettings: PluginSettings = { regex: DEFAULT_SETTINGS.regex, nothingSelected: NothingSelected.insertInline, // Inserts [](url) with cursor between brackets listForImgEmbed: "" }; // Custom settings example 3: Insert bare URL const insertBareSettings: PluginSettings = { regex: DEFAULT_SETTINGS.regex, nothingSelected: NothingSelected.insertBare, // Inserts listForImgEmbed: "" }; // Custom settings example 4: Image embed patterns const imgEmbedSettings: PluginSettings = { regex: DEFAULT_SETTINGS.regex, nothingSelected: NothingSelected.autoSelect, listForImgEmbed: [ "youtu\.?be|vimeo", "\.jpg$\|\.jpeg$\|\.png$\|\.gif$\|\.webp$\|\.svg$", "imgur\.com|giphy\.com", "unsplash\.com" ].join("\n") }; // Behavior with NothingSelected modes: // - doNothing: Standard paste behavior when no text selected // - autoSelect: Automatically selects word under cursor before pasting // - insertInline: Creates [](url) and positions cursor between brackets // - insertBare: Wraps URL in angle brackets: ``` -------------------------------- ### Optimize Regex Operations with RegexCache Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt Utilizes a `regexCache` utility to store and retrieve compiled regular expressions. This prevents redundant compilation, significantly improving performance for frequent URL validation and image embed pattern matching. It supports caching for fallback URL regexes and image embed regexes, with manual cache clearing. ```typescript import { regexCache } from "./utils/regex-cache"; // Fallback URL regex caching const urlPattern = /^https?:\/\/.+\.source; const regex1 = regexCache.getFallbackUrlRegex(urlPattern); const regex2 = regexCache.getFallbackUrlRegex(urlPattern); console.log(regex1 === regex2); // true - same instance returned from cache // Image embed regex caching const imgPatterns = "youtu\.?be|vimeo\n\.jpg$|\.png$"; const imgRegexes1 = regexCache.getImgEmbedRegexes(imgPatterns); const imgRegexes2 = regexCache.getImgEmbedRegexes(imgPatterns); console.log(imgRegexes1 === imgRegexes2); // true - cached // Cache invalidation on pattern change const newPattern = "imgur\.com|\.gif$"; const imgRegexes3 = regexCache.getImgEmbedRegexes(newPattern); console.log(imgRegexes3 === imgRegexes1); // false - new pattern compiled // Error handling for invalid regex const invalidPattern = "[invalid(regex"; const safeRegex = regexCache.getFallbackUrlRegex(invalidPattern); // Returns fallback regex, logs warning to console // Clear cache manually regexCache.clear(); const regex3 = regexCache.getFallbackUrlRegex(urlPattern); console.log(regex1 === regex3); // false - cache was cleared ``` -------------------------------- ### Main Link Processing Function - Obsidian Plugin Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt Handles paste events to transform clipboard content with selected text into markdown links. It validates data, determines selection range, checks for existing markdown links, and applies text replacement. Supports pasting URLs over text and text over URLs. ```typescript import { Editor } from "obsidian"; import UrlIntoSelection from "./core"; import { PluginSettings, DEFAULT_SETTINGS } from "./setting"; // Example 1: Paste URL over selected text const editor = editor; // Obsidian Editor instance const settings = DEFAULT_SETTINGS; // User has "GitHub" selected and pastes "https://github.com" editor.setSelection({ line: 0, ch: 0 }, { line: 0, ch: 6 }); // Selects "GitHub" const clipboardEvent = new ClipboardEvent('paste', { clipboardData: new DataTransfer() }); clipboardEvent.clipboardData.setData('text', 'https://github.com'); UrlIntoSelection(editor, clipboardEvent, settings); // Result: "[GitHub](https://github.com)" // Example 2: Paste text over selected URL (reverse operation) editor.setSelection({ line: 0, ch: 0 }, { line: 0, ch: 18 }); // Selects "https://github.com" const textEvent = new ClipboardEvent('paste', { clipboardData: new DataTransfer() }); textEvent.clipboardData.setData('text', 'Visit GitHub'); UrlIntoSelection(editor, textEvent, settings); // Result: "[Visit GitHub](https://github.com)" // Example 3: Using as command with clipboard text async function pasteFromClipboard(editor: Editor) { const clipboardText = await navigator.clipboard.readText(); UrlIntoSelection(editor, clipboardText, settings); } ``` -------------------------------- ### Identify Image Embed URLs (TypeScript) Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt The `isImgEmbed` function checks if a given URL should be treated as an image and formatted using markdown's image embed syntax (`![alt](url)`). It evaluates the URL against a list of patterns defined in the plugin's settings, which can include specific domains, file extensions (like .jpg, .png), and regex rules. This function helps distinguish between regular links and image URLs, ensuring correct display within Obsidian. ```typescript import { isImgEmbed } from "./utils/url"; import { PluginSettings } from "./types"; // Configure image embed patterns const settings: PluginSettings = { regex: "", nothingSelected: 0, listForImgEmbed: "youtu\.?be|vimeo\n\.jpg$|\.png$|\.gif$|\.webp$ imgur\.com" }; // YouTube URLs console.log(isImgEmbed("https://youtube.com/watch?v=xyz", settings)); // true console.log(isImgEmbed("https://youtu.be/xyz", settings)); // true // Image file extensions console.log(isImgEmbed("https://example.com/photo.jpg", settings)); // true console.log(isImgEmbed("https://example.com/image.png", settings)); // true console.log(isImgEmbed("https://example.com/animation.gif", settings)); // true console.log(isImgEmbed("https://example.com/photo.webp", settings)); // true // Image hosting services console.log(isImgEmbed("https://i.imgur.com/abc123.jpg", settings)); // true // Vimeo console.log(isImgEmbed("https://vimeo.com/123456", settings)); // true // Non-image URLs console.log(isImgEmbed("https://github.com", settings)); // false console.log(isImgEmbed("https://example.com/document.pdf", settings)); // false ``` -------------------------------- ### Format URLs for Markdown Compatibility (TypeScript) Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt The `processUrl` function formats given URLs to ensure compatibility with markdown syntax. It converts local file paths to `file://` URIs, encodes characters like angle brackets that conflict with markdown, and wraps URLs containing special characters or encoded brackets in angle brackets to prevent parsing issues. It handles various URL types, including regular URLs, file paths, and pre-formatted markdown links. ```typescript import { processUrl } from "./utils/url"; // File path conversion console.log(processUrl("C:\\Users\\file.txt")); // Output: "file:///C:/Users/file.txt" console.log(processUrl("/home/user/document.pdf")); // Output: "file:///home/user/document.pdf" // URLs with spaces need wrapping console.log(processUrl("https://example.com/path with spaces")); // Output: "" // URLs with parentheses need wrapping console.log(processUrl("https://en.wikipedia.org/wiki/Article_(disambiguation)")); // Output: "" // Already wrapped URLs pass through console.log(processUrl("")); // Output: "" // Regular URLs without special chars console.log(processUrl("https://github.com/user/repo")); // Output: "https://github.com/user/repo" // Angle brackets in URL are encoded console.log(processUrl("https://example.com?param=")); // Output: "" ``` -------------------------------- ### URL Validation Function - Obsidian Plugin Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt Validates if a string is a legitimate URL. It checks against the URL constructor, validates protocol schemes, detects file paths, supports Obsidian wikilinks, and falls back to custom regex patterns. This prevents incorrect identification of strings like 'font-style: italic' as URLs. ```typescript import { isUrl } from "./utils/url"; import { PluginSettings } from "./types"; const settings: PluginSettings = { regex: /^[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/.source, nothingSelected: 0, listForImgEmbed: "" }; // Valid URLs console.log(isUrl("https://example.com", settings)); // true console.log(isUrl("http://localhost:3000/api", settings)); // true console.log(isUrl("file:///home/user/document.pdf", settings)); // true console.log(isUrl("obsidian://open?vault=MyVault", settings)); // true console.log(isUrl("[[Internal Link]]", settings)); // true (wikilink) console.log(isUrl("C:\\Users\\Documents\\file.txt", settings)); // true (Windows path) console.log(isUrl("/home/user/file.txt", settings)); // true (Unix path) console.log(isUrl("example.com", settings)); // true (via fallback regex) // Invalid URLs console.log(isUrl("font-style: italic", settings)); // false (invalid protocol) console.log(isUrl("just some text", settings)); // false console.log(isUrl("", settings)); // false console.log(isUrl("/command args", settings)); // false (command pattern) ``` -------------------------------- ### Detect Cursor within Markdown Link (TypeScript) Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt The `checkIfInMarkdownLink` function determines if the current cursor position within an Obsidian editor is inside the URL part of a markdown link. This is crucial for preventing double markdown formatting when inserting URLs. It analyzes the editor's content and cursor range to return a boolean indicating whether the cursor is within link parentheses, either empty or containing an existing URL, or within an image link. ```typescript import { checkIfInMarkdownLink } from "./utils/markdown"; import { Editor, EditorRange } from "obsidian"; // Simulate editor with markdown content const editor: Editor = getEditor(); // Obsidian Editor instance // Example 1: Cursor inside empty link parentheses editor.setValue("[Click here]()"); editor.setCursor({ line: 0, ch: 14 }); // Inside () const range1: EditorRange = { from: { line: 0, ch: 14 }, to: { line: 0, ch: 14 } }; console.log(checkIfInMarkdownLink(editor, range1)); // true // Example 2: Cursor inside link with existing URL editor.setValue("[GitHub](https://github.com)"); editor.setCursor({ line: 0, ch: 15 }); // Inside URL const range2: EditorRange = { from: { line: 0, ch: 15 }, to: { line: 0, ch: 15 } }; console.log(checkIfInMarkdownLink(editor, range2)); // true // Example 3: Cursor in regular text editor.setValue("Regular text here"); editor.setCursor({ line: 0, ch: 5 }); const range3: EditorRange = { from: { line: 0, ch: 5 }, to: { line: 0, ch: 5 } }; console.log(checkIfInMarkdownLink(editor, range3)); // false // Example 4: Inside image link editor.setValue("![Alt text]()"); editor.setCursor({ line: 0, ch: 13 }); const range4: EditorRange = { from: { line: 0, ch: 13 }, to: { line: 0, ch: 13 } }; console.log(checkIfInMarkdownLink(editor, range4)); // true ``` -------------------------------- ### Strip Surrounding Quotes from Paths and URLs Source: https://context7.com/denolehov/obsidian-url-into-selection/llms.txt Implements the `stripSurroundingQuotes` function to remove leading and trailing quote characters (single or double) from strings, commonly used for cleaning file paths or URLs copied from file explorers. It handles various cases including mismatched quotes and empty strings. ```typescript import { stripSurroundingQuotes } from "./utils/quotes"; // Double quotes removed console.log(stripSurroundingQuotes('"C:\\Users\\Documents\\file.txt"')); // Output: "C:\\Users\\Documents\\file.txt" // Single quotes removed console.log(stripSurroundingQuotes("'/home/user/document.pdf'")); // Output: "/home/user/document.pdf" // URLs with quotes console.log(stripSurroundingQuotes('"https://example.com"')); // Output: "https://example.com" // Mismatched quotes not removed console.log(stripSurroundingQuotes('"path/to/file'')); // Output: "\"path/to/file'" // No quotes - unchanged console.log(stripSurroundingQuotes('regular text')); // Output: "regular text" // Single character with quotes console.log(stripSurroundingQuotes('"a"')); // Output: "a" // Empty or short strings console.log(stripSurroundingQuotes('""')); // Output: "" console.log(stripSurroundingQuotes('a')); // Output: "a" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.