In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "implementation principle of markdown Preview in vscode". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the implementation principle of markdown Preview in vscode".
Train of thought analysis
Create a webview through vscode.window.createWebviewPanel, specify to open it on the side, and then set the html through the webview.html property of the panel object.
Html is generated from the editor's markdown content, which is obtained through editor.document.getText (), and then generated by calling a third-party markdown to html's library.
This completes the preview of the markdown.
After the preview, you need to update, listen for vscode.workspace.onDidSaveTextDocument and vscode.workspace.onDidChangeTextDocument events, get the contents of the editor when the document is updated and saved, regenerate the html, and then set it to webview.
WebviewPanel supports webview.postMessage (message);, and supports a series of command, such as updateHTML, which can be triggered by passing messages.
But how do you know which document updates which webview?
You can maintain a map, which is recorded in the map when the webviewPanel is created, and the key is the file path, so that when you update, you can find the corresponding webview to update.
In this way, the update of markdown content is completed.
In fact, the overall idea is relatively simple, let's write down the code.
Code implementation
Let's take a look at the code for the vscode-markdown-preview-enhanced plug-in, which is also a plug-in for previewing markdown. The code is fairly concise and can be used to learn.
(the following code is simplified)
First of all, the plug-in should specify the trigger condition, that is, specify activationEvents in package.json:
"activationEvents": ["onLanguage:markdown", "onCommand:markdown-preview-enhanced.openPreviewToTheSide"]
Here, one is activated when editing markdown content, and the other is activated when command is executed.
The specific activation logic is in the active method:
Export function activate (context: vscode.ExtensionContext) {const contentProvider = new MarkdownPreviewEnhancedView (context); context.subscriptions.push (vscode.commands.registerCommand ("markdown-preview-enhanced.openPreviewToTheSide", openPreviewToTheSide,),); function openPreviewToTheSide (uri?: vscode.Uri) {let resource = uri; if (! (resource instanceof vscode.Uri)) {if (vscode.window.activeTextEditor) {resource = vscode.window.activeTextEditor.document.uri } contentProvider.initPreview (resource, vscode.window.activeTextEditor, {viewColumn: vscode.ViewColumn.Two, preserveFocus: true,});}}
We register that command, execute command to get the url of the current editor, and then preview the markdown.
All the logic of preview is defined centrally in the instance object of MarkdownPreviewEnhancedView, which executes initPreivew when command triggers.
Public async initPreview (sourceUri: vscode.Uri, editor: vscode.TextEditor, viewOptions: {viewColumn: vscode.ViewColumn; preserveFocus?: boolean},) {/ / create webview let previewPanel: vscode.WebviewPanel = vscode.window.createWebviewPanel ("markdown-preview-enhanced", `Preview ${path.basename (sourceUri.fsPath)} `, viewOptions); / / listen for webview messages previewPanel.webview.onDidReceiveMessage ((message) = > {}) / record webview to map this.previewMaps [sourceUri.fsPath] = previewPanel; / / get the editor's text and generate html const text = editor.document.getText (); engine .generateHTMLTemplatePreview ({inputString: text}) .then ((html) = > {/ / set html to previewPanel previewPanel.webview.html = html;});}
Create a webviewPanel in initWebivew and save the webviewPanel to map, where key is the file path of the document. Get the editor text to generate the html and set it to webview.html, which completes the preview of the markdown.
Once this path is available, we have implemented a preview of markdown.
But you can't preview it only once. After updating the document, you need to update it automatically. Let's continue to add event listener to the active method:
Context.subscriptions.push (vscode.workspace.onDidSaveTextDocument ((document) = > {if (isMarkdownFile (document)) {contentProvider.updateMarkdown (document.uri, true);}}),); context.subscriptions.push (vscode.workspace.onDidChangeTextDocument ((event) = > {if (isMarkdownFile (event.document)) {contentProvider.update (event.document.uri);}}),)
When listening for text modification and saving, call the update method to update.
Public updateMarkdown (sourceUri: Uri) {/ / fetch the corresponding webviewPanel const previewPanel = this.previewMaps [sourceUri.fsPath] from map according to the file path; / / generate the latest html and pass it to webview const text = document.getText () Engine .parseMD (text) .then ({markdown, html}) = > {previewPanel.webview.postMessage ({command: "updateHTML", html});}}
Here, the command message of updateHTML is passed to the html content through webview.postMessage, triggering the update of the html content.
In this way, we realize the synchronous refresh of markdown.
Summary
The preview of markdown in vscode is a common feature that is not difficult to implement. We took a look at the source code of the vscode-markdown-preview-enhanced plug-in and sorted out the overall process:
Create a webviewPanel to display html through vscode.window.createWebviewPanel
Html gets the text content through editor.document.getText (), generates it through a third-party package, and sets it to webviewPanel
Listen to workspace.onDidSaveTextDocument and workspace.onDidChangeTextDocument to get the latest content, and then generate html to update to webview by passing udpateHTML messages through webview.postMessage.
It should be noted that a map needs to be recorded to save the correspondence between uri.fsPath and webviewPanel, and to change and update the webview corresponding to the text.
Thank you for your reading, these are the contents of "the implementation principle of markdown Preview in vscode". After the study of this article, I believe you have a deeper understanding of the realization principle of markdown Preview in vscode. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.