Skip to content

Commit

Permalink
#6 Conversion for Editor Selection
Browse files Browse the repository at this point in the history
  • Loading branch information
Ozan Tellioglu committed Dec 16, 2021
1 parent e9eb137 commit fee68da
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/converter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import LinkConverterPlugin from 'main';
import { App, TFile, Notice, normalizePath, TFolder } from 'obsidian';
import { App, TFile, Notice, normalizePath, TFolder, MarkdownView } from 'obsidian';
import { getFilesUnderPath } from './utils';

/* -------------------- LINK DETECTOR -------------------- */
Expand Down Expand Up @@ -150,6 +150,29 @@ export const convertLinksUnderFolder = async (folder: TFolder, plugin: LinkConve
}
};

// --> Convert Links within editor Selection
export const convertLinksWithinSelection = async (finalFormat: 'markdown' | 'wiki', plugin: LinkConverterPlugin) => {
let activeLeaf = plugin.app.workspace.getActiveViewOfType(MarkdownView);
if (activeLeaf) {
let editor = activeLeaf.editor;
let selection = editor.getSelection();
let sourceFile = activeLeaf.file;
if (selection !== '') {
let newText: string;
if (finalFormat === 'markdown') {
newText = await convertWikiLinksToMarkdown(selection, sourceFile, plugin);
} else if (finalFormat === 'wiki') {
newText = await convertMarkdownLinksToWikiLinks(selection, sourceFile, plugin);
}
editor.replaceSelection(newText);
} else {
new Notice("You didn't select any text.");
}
} else {
new Notice('There is no active leaf open.', 3000);
}
};

// --> Command Function: Converts All Links in All Files in Vault and Save in Corresponding Files
export const convertLinksInVault = async (plugin: LinkConverterPlugin, finalFormat: 'markdown' | 'wiki') => {
convertLinksUnderFolder(plugin.app.vault.getRoot(), plugin, finalFormat);
Expand Down
12 changes: 12 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@ export default class LinkConverterPlugin extends Plugin {
},
});

this.addCommand({
id: 'convert-wikis-to-mdlinks-within-selection',
name: 'Editor Selection: Links to Markdown',
callback: async () => Converter.convertLinksWithinSelection('markdown', this),
});

this.addCommand({
id: 'convert-mdlinks-to-wiki-within-selection',
name: 'Editor Selection: Links to Wiki',
callback: async () => Converter.convertLinksWithinSelection('wiki', this),
});

if (this.settings.contextMenu) this.app.workspace.on('file-menu', this.addFileMenuItems);
}

Expand Down

0 comments on commit fee68da

Please sign in to comment.