Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically open QMD files in visual/source editor if specified #577

Merged
merged 18 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions apps/vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1036,6 +1036,16 @@
"default": true,
"markdownDescription": "When using a venv or conda environment, prefer Quarto CLI installed with pip in that environment. This will override Quarto CLI in the `PATH`, but not an explicitly configured `#quarto.path#`."
},
"quarto.defaultEditor": {
"order": 11,
"type": "string",
"markdownDescription": "Default editor",
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
"enum": [
"source",
"visual"
],
"default": "source"
},
"quarto.render.renderOnSave": {
"order": 12,
"scope": "window",
Expand Down
42 changes: 39 additions & 3 deletions apps/vscode/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,16 @@ import { activateStatusBar } from "./providers/statusbar";
import { walkthroughCommands } from "./providers/walkthrough";
import { activateLuaTypes } from "./providers/lua-types";
import { activateCreate } from "./providers/create/create";
import { activateEditor } from "./providers/editor/editor";
import { activateEditor, VisualEditorProvider } from "./providers/editor/editor";
import { activateCopyFiles } from "./providers/copyfiles";
import { activateZotero } from "./providers/zotero/zotero";;
import { extensionHost } from "./host";
import { configuredQuartoPath } from "./core/quarto";
import { activateDenoConfig } from "./providers/deno-config";
import { determineMode, setEditorOpener } from "./providers/editor/toggle";

export async function activate(context: vscode.ExtensionContext) {

// create extension host
const host = extensionHost();

Expand Down Expand Up @@ -125,9 +126,44 @@ export async function activate(context: vscode.ExtensionContext) {

// activate providers common to browser/node
activateCommon(context, host, engine, commands);

// if positron
setEditorOpener();

vscode.workspace.onDidChangeConfiguration(async (event) => {
if (event.affectsConfiguration('quarto.defaultEditor')) {
setEditorOpener();
}
});
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved

const documentOpenHandler = vscode.window.onDidChangeActiveTextEditor(async () => {
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
// Check if the document language is "quarto"

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like we don't have things quite right in this changing active text editor listener

  1. A diff editor view of a quarto document immediately closes
Screen.Recording.2024-10-22.at.4.37.39.PM.mov
  1. I can't seem to go from Visual Mode to Source Mode explicitly
Screen.Recording.2024-10-22.at.4.37.57.PM.mov

const document = vscode.window.activeTextEditor?.document
if (!document || document.languageId != 'quarto') {
return;
}
const config = vscode.workspace.getConfiguration('quarto').get<string>('defaultEditor');

const editorMode = await determineMode(document.getText());
if (editorMode && editorMode != config) {
const editorOpener = editorMode === 'visual' ? VisualEditorProvider.viewType : 'textEditor';
await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
await vscode.commands.executeCommand("vscode.openWith",
document.uri,
editorOpener
);
return;
DavisVaughan marked this conversation as resolved.
Show resolved Hide resolved
}
});

// Add the event handler to the context subscriptions
context.subscriptions.push(documentOpenHandler);

// end if positron
}

export async function deactivate() {
return deactivateLsp();
}
}

92 changes: 82 additions & 10 deletions apps/vscode/src/providers/editor/toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,88 @@
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/

import * as vscode from "vscode";
import { commands, window, workspace, TextDocument, ViewColumn } from "vscode";
import * as path from 'path';
import * as quarto from "quarto-core";
import fs from "node:fs";
import yaml from "js-yaml";
import { Command } from "../../core/command";
import { isQuartoDoc, kQuartoLanguageId } from "../../core/doc";
import { VisualEditorProvider } from "./editor";


export async function determineMode(doc: string): Promise<string | undefined> {
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
let editorOpener = undefined;

// check if file itself has a mode
if (hasEditorMode(doc, "source")) {
editorOpener = "source";
}
else if (hasEditorMode(doc, "visual")) {
editorOpener = "visual";
}
// check if has a _quarto.yml or _quarto.yaml file with editor specified
else {
editorOpener = workspaceHasQuartoYaml();
}

return editorOpener;
}

export async function setEditorOpener() {
const config = vscode.workspace.getConfiguration('quarto').get<string>('defaultEditor');
const viewType = config === 'visual' ? VisualEditorProvider.viewType : 'textEditor';
vscode.workspace.getConfiguration('workbench').update('editor.defaultView', viewType, true);
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
await vscode.commands.executeCommand("workbench.action.setDefaultEditor",
vscode.Uri.file('filename.qmd'),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think this could be replaced as "*.qmd" if we instead expose updateUserAssociations from the Positron side

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I wonder if we could expose updateUserAssociations() with the slightly better name of setEditorAssociations(), but then expose it from positron.d.ts rather than as a command (either in the top level 'positron' namespace, or under a new 'workbench' sub namespace, mirroring what VS Code has. That would work like our existing 'language' and 'runtime' sub namespaces).

That would probably be nice because it would force you to look at Quarto's hasHooks() and hooksApi() helpers to determine whether or not you are in positron (we use that in a few other places too)

(FWIW saveAllTitled had to be a command to be able to call it from R, but this feels more like an Extension API feature that can be a "real" function exported from positron.d.ts)

viewType
);
}

export function workspaceHasQuartoYaml() {
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
const workspaceFolders = vscode.workspace.workspaceFolders;

if (workspaceFolders && workspaceFolders.length > 0) {
const rootPath = workspaceFolders[0].uri.fsPath; // Only look in the root directory of the first workspace folder

const quartoFilePathYml = path.join(rootPath, '_quarto.yml');
const quartoFilePathYaml = path.join(rootPath, '_quarto.yaml');

let fileContent: string | null = null;

if (fs.existsSync(quartoFilePathYml)) {
fileContent = fs.readFileSync(quartoFilePathYml, 'utf8');
} else if (fs.existsSync(quartoFilePathYaml)) {
fileContent = fs.readFileSync(quartoFilePathYaml, 'utf8');
}

export function editInVisualModeCommand() : Command {
if (fileContent) {
const parsedYaml = yaml.load(fileContent) as any;
if (parsedYaml.editor === 'visual' || parsedYaml.editor === 'source') {
return parsedYaml.editor;
}
}
}

return undefined;
}

export function hasEditorMode(doc: string, mode: string) {
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
if (doc) {
const match = doc.match(quarto.kRegExYAML);
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
if (match) {
const yaml = match[0];
return (
!!yaml.match(new RegExp("^editor:\\s+" + mode + "\\s*$", "gm")) ||
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
!!yaml.match(new RegExp("^[ \\t]*" + mode + ":\\s*(default)?\\s*$", "gm"))
);
isabelizimm marked this conversation as resolved.
Show resolved Hide resolved
}
}
return false;
}

export function editInVisualModeCommand(): Command {
return {
id: "quarto.editInVisualMode",
execute() {
Expand All @@ -33,14 +105,14 @@ export function editInVisualModeCommand() : Command {
};
}

export function editInSourceModeCommand() : Command {
export function editInSourceModeCommand(): Command {
return {
id: "quarto.editInSourceMode",
execute() {
const activeVisual = VisualEditorProvider.activeEditor();
if (activeVisual) {
reopenEditorInSourceMode(activeVisual.document, '', activeVisual.viewColumn);
}
}
}
};
}
Expand All @@ -49,14 +121,14 @@ export async function reopenEditorInVisualMode(
document: TextDocument,
viewColumn?: ViewColumn
) {

// save then close
await commands.executeCommand("workbench.action.files.save");
await commands.executeCommand('workbench.action.closeActiveEditor');

// open in visual mode
await commands.executeCommand("vscode.openWith",
document.uri,
await commands.executeCommand("vscode.openWith",
document.uri,
VisualEditorProvider.viewType,
{
viewColumn
Expand All @@ -65,8 +137,8 @@ export async function reopenEditorInVisualMode(
}

export async function reopenEditorInSourceMode(
document: TextDocument,
untitledContent?: string,
document: TextDocument,
untitledContent?: string,
viewColumn?: ViewColumn
) {
if (!document.isUntitled) {
Expand All @@ -91,5 +163,5 @@ export async function reopenEditorInSourceMode(
await window.showTextDocument(doc, viewColumn, false);
}
});

}
2 changes: 1 addition & 1 deletion packages/quarto-core/src/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export function filePathForDoc(doc: Document) {
return URI.parse(doc.uri).fsPath;
}

const kRegExYAML =
export const kRegExYAML =
/(^)(---[ \t]*[\r\n]+(?![ \t]*[\r\n]+)[\W\w]*?[\r\n]+(?:---|\.\.\.))([ \t]*)$/gm;

export function isQuartoDocWithFormat(doc: Document | string, format: string) {
Expand Down