initial commit: scaffold plugin from obsidian-sample-plugin

Copy Image Hotkey 1.0.0 — Cmd+C copies the actual image when an image
embed is selected in source mode. Built off the official sample-plugin
template; source is in src/main.ts, builds main.js via esbuild.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ali Irani 2026-05-01 15:06:10 -07:00
commit 8808b4851f
15 changed files with 5553 additions and 0 deletions

10
.editorconfig Normal file
View file

@ -0,0 +1,10 @@
# top-most EditorConfig file
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = tab
indent_size = 4
tab_width = 4

22
.gitignore vendored Normal file
View file

@ -0,0 +1,22 @@
# vscode
.vscode
# Intellij
*.iml
.idea
# npm
node_modules
# Don't include the compiled main.js file in the repo.
# They should be uploaded to GitHub releases instead.
main.js
# Exclude sourcemaps
*.map
# obsidian
data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store

1
.npmrc Normal file
View file

@ -0,0 +1 @@
tag-version-prefix=""

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Ali Irani
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

58
README.md Normal file
View file

@ -0,0 +1,58 @@
# Copy Image Hotkey
Cmd+C (or Ctrl+C) copies the **actual image** to your clipboard when an image embed is selected in an Obsidian note — instead of copying the wikilink text.
## Why
By default, selecting `![[my-photo.png]]` in source mode and pressing Cmd+C copies the literal text `![[my-photo.png]]`. If you want to paste the image into another app (Slack, Mail, Figma, etc.), you have to right-click and "Copy image" from the rendered preview, which breaks flow.
This plugin makes Cmd+C just work: select the image embed, copy, paste anywhere.
## Demo
<!-- TODO: replace with a real demo GIF before announcing -->
![demo](docs/demo.gif)
## How it works
The plugin listens for the system copy event. When the current selection is either:
1. text matching `![[filename.ext]]` (source mode), or
2. a rendered `<img>` element (Live Preview),
it intercepts the copy, reads the image binary from your vault, and writes it to the clipboard as the correct MIME type. SVGs are written as text. Everything else is written as `Blob`.
Supported formats: PNG, JPG/JPEG, GIF, BMP, TIFF, WebP, SVG.
## Install
### From the Obsidian community plugins (post-approval)
1. Settings → Community Plugins → Browse
2. Search for "Copy Image Hotkey"
3. Install and enable
### Pre-approval (via BRAT)
While the plugin is awaiting community-plugin approval, install via [BRAT](https://github.com/TfTHacker/obsidian42-brat):
1. Install and enable BRAT from the community plugin browser
2. BRAT settings → "Add Beta plugin"
3. Paste: `aliir74/copy-image-hotkey`
4. Enable Copy Image Hotkey under Settings → Community Plugins
### Manual install
1. Download `main.js`, `manifest.json`, and `styles.css` from the [latest release](https://github.com/aliir74/copy-image-hotkey/releases/latest)
2. Drop them into `<your-vault>/.obsidian/plugins/copy-image-hotkey/`
3. Reload Obsidian → Settings → Community Plugins → enable Copy Image Hotkey
## Notes
- Desktop-only (uses the `navigator.clipboard.write` API with `ClipboardItem`).
- The plugin doesn't bind a custom hotkey — it intercepts the existing system copy. If you've remapped copy elsewhere, the plugin will still trigger off whichever key fires the `copy` event.
## License
MIT — see [LICENSE](LICENSE).

49
esbuild.config.mjs Normal file
View file

@ -0,0 +1,49 @@
import esbuild from "esbuild";
import process from "process";
import { builtinModules } from 'node:module';
const banner =
`/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;
const prod = (process.argv[2] === "production");
const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["src/main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtinModules],
format: "cjs",
target: "es2018",
logLevel: "info",
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: "main.js",
minify: prod,
});
if (prod) {
await context.rebuild();
process.exit(0);
} else {
await context.watch();
}

34
eslint.config.mts Normal file
View file

@ -0,0 +1,34 @@
import tseslint from 'typescript-eslint';
import obsidianmd from "eslint-plugin-obsidianmd";
import globals from "globals";
import { globalIgnores } from "eslint/config";
export default tseslint.config(
{
languageOptions: {
globals: {
...globals.browser,
},
parserOptions: {
projectService: {
allowDefaultProject: [
'eslint.config.js',
'manifest.json'
]
},
tsconfigRootDir: import.meta.dirname,
extraFileExtensions: ['.json']
},
},
},
...obsidianmd.configs.recommended,
globalIgnores([
"node_modules",
"dist",
"esbuild.config.mjs",
"eslint.config.js",
"version-bump.mjs",
"versions.json",
"main.js",
]),
);

10
manifest.json Normal file
View file

@ -0,0 +1,10 @@
{
"id": "copy-image-hotkey",
"name": "Copy Image Hotkey",
"version": "0.1.0",
"minAppVersion": "1.4.0",
"description": "Cmd+C copies the actual image when an image embed is selected in source mode.",
"author": "Ali Irani",
"authorUrl": "https://github.com/aliir74",
"isDesktopOnly": true
}

5149
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

39
package.json Normal file
View file

@ -0,0 +1,39 @@
{
"name": "copy-image-hotkey",
"version": "0.1.0",
"description": "Cmd+C copies the actual image when an image embed is selected in source mode.",
"main": "main.js",
"type": "module",
"author": "Ali Irani",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/aliir74/copy-image-hotkey.git"
},
"scripts": {
"dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json",
"lint": "eslint ."
},
"keywords": [
"obsidian",
"obsidian-plugin",
"clipboard",
"image"
],
"devDependencies": {
"@types/node": "^16.11.6",
"esbuild": "0.25.5",
"eslint-plugin-obsidianmd": "0.1.9",
"globals": "14.0.0",
"tslib": "2.4.0",
"typescript": "^5.8.3",
"typescript-eslint": "8.35.1",
"@eslint/js": "9.30.1",
"jiti": "2.6.1"
},
"dependencies": {
"obsidian": "latest"
}
}

109
src/main.ts Normal file
View file

@ -0,0 +1,109 @@
import { Plugin, Notice, TFile } from "obsidian";
const IMAGE_EMBED_RE = /^!\[\[(.+?\.(png|jpg|jpeg|gif|bmp|tiff|webp|svg))\]\]$/i;
const IMAGE_EXT_RE = /\.(png|jpg|jpeg|gif|bmp|tiff|webp|svg)$/i;
const MIME_TYPES: Record<string, string> = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
bmp: "image/bmp",
tiff: "image/tiff",
webp: "image/webp",
svg: "image/svg+xml",
};
export default class CopyImageHotkeyPlugin extends Plugin {
async onload(): Promise<void> {
this.registerDomEvent(document, "copy", (evt: ClipboardEvent) => {
this.handleCopy(evt);
});
}
handleCopy(evt: ClipboardEvent): void {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return;
// Strategy 1: Selected text matches ![[image.ext]] pattern
const text = selection.toString().trim();
const match = text.match(IMAGE_EMBED_RE);
if (match && match[1] && match[2]) {
const ext = match[2].toLowerCase();
const mimeType = MIME_TYPES[ext];
if (!mimeType) return;
evt.preventDefault();
this.copyImageToClipboard(match[1], mimeType);
return;
}
// Strategy 2: Selection contains an <img> element (Live Preview rendered widget)
const range = selection.getRangeAt(0);
const fragment = range.cloneContents();
const img = fragment.querySelector("img");
if (!img) return;
const filename = this.extractFilenameFromImg(img);
if (!filename) return;
const extMatch = filename.match(IMAGE_EXT_RE);
if (!extMatch || !extMatch[1]) return;
const mimeType = MIME_TYPES[extMatch[1].toLowerCase()];
if (!mimeType) return;
evt.preventDefault();
this.copyImageToClipboard(filename, mimeType);
}
extractFilenameFromImg(img: HTMLImageElement): string | null {
// Try alt attribute first (most reliable in Obsidian)
const alt = img.getAttribute("alt");
if (alt && IMAGE_EXT_RE.test(alt)) return alt;
// Try src — Obsidian uses app://local/<vault-path>/filename.ext
const src = img.getAttribute("src");
if (src) {
try {
const decoded = decodeURIComponent(src);
const parts = decoded.split("/");
const last = parts[parts.length - 1];
if (!last) return null;
const basename = last.split("?")[0];
if (basename && IMAGE_EXT_RE.test(basename)) return basename;
} catch (e) {
// ignore decode errors
}
}
return null;
}
async copyImageToClipboard(filename: string, mimeType: string): Promise<void> {
try {
const file = this.app.metadataCache.getFirstLinkpathDest(filename, "");
if (!file || !(file instanceof TFile)) {
new Notice("Image not found: " + filename);
return;
}
const buffer = await this.app.vault.readBinary(file);
if (mimeType === "image/svg+xml") {
const text = new TextDecoder().decode(buffer);
await navigator.clipboard.writeText(text);
new Notice("SVG copied to clipboard!");
return;
}
const blob = new Blob([buffer], { type: mimeType });
await navigator.clipboard.write([
new ClipboardItem({ [mimeType]: blob }),
]);
new Notice("Image copied to clipboard!");
} catch (err: unknown) {
console.error("copy-image-hotkey:", err);
new Notice("Failed to copy image: " + (err as Error).message);
}
}
}

1
styles.css Normal file
View file

@ -0,0 +1 @@
/* Copy Image Hotkey - no custom styles needed */

30
tsconfig.json Normal file
View file

@ -0,0 +1,30 @@
{
"compilerOptions": {
"baseUrl": "src",
"inlineSourceMap": true,
"inlineSources": true,
"module": "ESNext",
"target": "ES6",
"allowJs": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"moduleResolution": "node",
"importHelpers": true,
"noUncheckedIndexedAccess": true,
"isolatedModules": true,
"strictNullChecks": true,
"strictBindCallApply": true,
"allowSyntheticDefaultImports": true,
"useUnknownInCatchVariables": true,
"lib": [
"DOM",
"ES5",
"ES6",
"ES7"
]
},
"include": [
"src/**/*.ts"
]
}

17
version-bump.mjs Normal file
View file

@ -0,0 +1,17 @@
import { readFileSync, writeFileSync } from "fs";
const targetVersion = process.env.npm_package_version;
// read minAppVersion from manifest.json and bump version to target version
const manifest = JSON.parse(readFileSync("manifest.json", "utf8"));
const { minAppVersion } = manifest;
manifest.version = targetVersion;
writeFileSync("manifest.json", JSON.stringify(manifest, null, "\t"));
// update versions.json with target version and minAppVersion from manifest.json
// but only if the target version is not already in versions.json
const versions = JSON.parse(readFileSync('versions.json', 'utf8'));
if (!Object.values(versions).includes(minAppVersion)) {
versions[targetVersion] = minAppVersion;
writeFileSync('versions.json', JSON.stringify(versions, null, '\t'));
}

3
versions.json Normal file
View file

@ -0,0 +1,3 @@
{
"0.1.0": "1.4.0"
}