Skip to content

Commit fee68da

Browse files
author
Ozan Tellioglu
committed
#6 Conversion for Editor Selection
1 parent e9eb137 commit fee68da

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/converter.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import LinkConverterPlugin from 'main';
2-
import { App, TFile, Notice, normalizePath, TFolder } from 'obsidian';
2+
import { App, TFile, Notice, normalizePath, TFolder, MarkdownView } from 'obsidian';
33
import { getFilesUnderPath } from './utils';
44

55
/* -------------------- LINK DETECTOR -------------------- */
@@ -150,6 +150,29 @@ export const convertLinksUnderFolder = async (folder: TFolder, plugin: LinkConve
150150
}
151151
};
152152

153+
// --> Convert Links within editor Selection
154+
export const convertLinksWithinSelection = async (finalFormat: 'markdown' | 'wiki', plugin: LinkConverterPlugin) => {
155+
let activeLeaf = plugin.app.workspace.getActiveViewOfType(MarkdownView);
156+
if (activeLeaf) {
157+
let editor = activeLeaf.editor;
158+
let selection = editor.getSelection();
159+
let sourceFile = activeLeaf.file;
160+
if (selection !== '') {
161+
let newText: string;
162+
if (finalFormat === 'markdown') {
163+
newText = await convertWikiLinksToMarkdown(selection, sourceFile, plugin);
164+
} else if (finalFormat === 'wiki') {
165+
newText = await convertMarkdownLinksToWikiLinks(selection, sourceFile, plugin);
166+
}
167+
editor.replaceSelection(newText);
168+
} else {
169+
new Notice("You didn't select any text.");
170+
}
171+
} else {
172+
new Notice('There is no active leaf open.', 3000);
173+
}
174+
};
175+
153176
// --> Command Function: Converts All Links in All Files in Vault and Save in Corresponding Files
154177
export const convertLinksInVault = async (plugin: LinkConverterPlugin, finalFormat: 'markdown' | 'wiki') => {
155178
convertLinksUnderFolder(plugin.app.vault.getRoot(), plugin, finalFormat);

src/main.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,18 @@ export default class LinkConverterPlugin extends Plugin {
7171
},
7272
});
7373

74+
this.addCommand({
75+
id: 'convert-wikis-to-mdlinks-within-selection',
76+
name: 'Editor Selection: Links to Markdown',
77+
callback: async () => Converter.convertLinksWithinSelection('markdown', this),
78+
});
79+
80+
this.addCommand({
81+
id: 'convert-mdlinks-to-wiki-within-selection',
82+
name: 'Editor Selection: Links to Wiki',
83+
callback: async () => Converter.convertLinksWithinSelection('wiki', this),
84+
});
85+
7486
if (this.settings.contextMenu) this.app.workspace.on('file-menu', this.addFileMenuItems);
7587
}
7688

0 commit comments

Comments
 (0)