Peter Wone
Peter Wone

Reputation: 18765

What is the vscode command to open a file in preview

I wrote an extension for vscode. After installation the extension folder contains documentation in a markdown file. I want to provide a command that loads this file into the preview pane so it displays rendered with images and hyperlinks etc.

You can do this sort of thing interactively:

Context menu item that loads a file directly into the preview pane

and I have the full path to the markdown file, so now all I need is details of the command that implements this context menu item.

Web search does not produce complete or usable results.

Upvotes: 1

Views: 1508

Answers (2)

Peter Wone
Peter Wone

Reputation: 18765

After cloning the VS Code repo and trawling through the source I discovered the markdown.showPreview and associated commands.

To give credit where due, Lex Li reported the corresponding package.json entry in a comment while I was looking.

Without parameters this previews the content of the active editor, but as I said in a comment, it supports an optional Uri parameter and the code looks like this:

    let pathToManual = path.join(context.extensionPath, "manual.md");
    let uriManual: vscode.Uri = vscode.Uri.file(pathToManual);
    vscode.commands.executeCommand('markdown.showPreview', uriManual);

For information on constructing workspace relative paths see the answer from Mark. The joinPath method he uses requires a base path as a Uri which is conveniently available for the workspace but not for the extension path.

If you need information on things like showing preview to one side then given the dearth of documentation I recommend cloning the repo and searching it for "markdown.showPreview", then exploring nearby code. If you fold the methods it gets easier to survey your options.

Upvotes: 3

Mark
Mark

Reputation: 181050

Try:

vscode.commands.executeCommand("markdown.showPreview", vscode.Uri.joinPath(vscode.workspace.workspaceFolders[0].uri,'test.md'));

Your fileName there at the end of course. And that assumed you are in the first or only root of a workspace. You might be able to simplify it using:

vscode.Uri.path(<path to file)

instead of the joinPath that I used.

Upvotes: 0

Related Questions