diff --git a/src/extension.ts b/src/extension.ts index 708c0d6..496dad5 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -232,6 +232,20 @@ export function activate(context: vscode.ExtensionContext) { type: 'run-code-chunk' }) } + + function clickTagA(uri, href) { + const sourceUri = vscode.Uri.parse(decodeURIComponent(uri)); + if (['.pdf', '.xls', '.xlsx', '.doc', '.ppt', '.docx', '.pptx'].indexOf(path.extname(href)) >= 0) { + utility.openFile(href) + } else if (href.match(/^file\:\/\/\//)) { + // openFilePath = href.slice(8) # remove protocal + let openFilePath = href.replace(/(\s*)[\#\?](.+)$/, '') // remove #anchor and ?params... + openFilePath = decodeURI(openFilePath) + vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(openFilePath), vscode.ViewColumn.One) + } else { + utility.openFile(href) + } + } context.subscriptions.push(vscode.workspace.onDidSaveTextDocument(document => { @@ -364,6 +378,8 @@ export function activate(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.commands.registerCommand('_markdown-preview-enhanced.runAllCodeChunks', runAllCodeChunks)) + context.subscriptions.push(vscode.commands.registerCommand('_markdown-preview-enhanced.clickTagA', clickTagA)) + context.subscriptions.push(contentProviderRegistration) } diff --git a/src/markdown-preview-enhanced-webview.ts b/src/markdown-preview-enhanced-webview.ts index ae9fdaf..b35d1de 100644 --- a/src/markdown-preview-enhanced-webview.ts +++ b/src/markdown-preview-enhanced-webview.ts @@ -667,6 +667,27 @@ async function initEvents() { mpe.refreshingIcon.style.display = "none" } +function bindTagAClickEvent() { + const as = mpe.previewElement.getElementsByTagName('a') + for (let i = 0; i < as.length; i++) { + const a = as[i] + const href = a.getAttribute('href') + if (href && href[0] === '#') { + // anchor, do nothing + } else { + a.onclick = (event)=> { + event.preventDefault() + event.stopPropagation() + + window.parent.postMessage({ + command: 'did-click-link', // <= this has to be `did-click-link` to post message + data: `command:_markdown-preview-enhanced.clickTagA?${JSON.stringify([sourceUri, href])}` + }, 'file://') + } + } + } +} + /** * update previewElement innerHTML content * @param html @@ -695,6 +716,8 @@ function updateHTML(html) { // init several events initEvents().then(()=> { mpe.scrollMap = null + + bindTagAClickEvent() // scroll to initial position if (!mpe.doneLoadingPreview) {