|
| 1 | +/* |
| 2 | + * context-keys.ts |
| 3 | + * |
| 4 | + * Copyright (C) 2024 by Posit Software, PBC |
| 5 | + * |
| 6 | + * Unless you have received this program directly from Posit Software pursuant |
| 7 | + * to the terms of a commercial license agreement with Posit Software, then |
| 8 | + * this program is licensed to you under the terms of version 3 of the |
| 9 | + * GNU Affero General Public License. This program is distributed WITHOUT |
| 10 | + * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, |
| 11 | + * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the |
| 12 | + * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. |
| 13 | + * |
| 14 | + */ |
| 15 | + |
| 16 | +import * as vscode from "vscode"; |
| 17 | +import debounce from "lodash.debounce"; |
| 18 | + |
| 19 | +import { isQuartoDoc } from "../core/doc"; |
| 20 | +import { MarkdownEngine } from "../markdown/engine"; |
| 21 | +import { mainLanguage } from "../vdoc/vdoc"; |
| 22 | + |
| 23 | +const debounceOnDidChangeDocumentMs = 250; |
| 24 | + |
| 25 | +export function activateContextKeySetter( |
| 26 | + context: vscode.ExtensionContext, |
| 27 | + engine: MarkdownEngine |
| 28 | +) { |
| 29 | + |
| 30 | + // set context keys when active text editor changes |
| 31 | + vscode.window.onDidChangeActiveTextEditor( |
| 32 | + (editor) => { |
| 33 | + if (editor) { |
| 34 | + setContextKeys(editor, engine); |
| 35 | + } |
| 36 | + }, |
| 37 | + null, |
| 38 | + context.subscriptions |
| 39 | + ); |
| 40 | + |
| 41 | + // set context keys on changes to the document (if it's active) |
| 42 | + vscode.workspace.onDidChangeTextDocument( |
| 43 | + (event) => { |
| 44 | + const activeEditor = vscode.window.activeTextEditor; |
| 45 | + if (activeEditor) { |
| 46 | + debounce( |
| 47 | + () => setContextKeys(activeEditor, engine), |
| 48 | + debounceOnDidChangeDocumentMs |
| 49 | + )(); |
| 50 | + } |
| 51 | + }, |
| 52 | + null, |
| 53 | + context.subscriptions |
| 54 | + ); |
| 55 | +} |
| 56 | + |
| 57 | +function setContextKeys(editor: vscode.TextEditor, engine: MarkdownEngine) { |
| 58 | + if (!editor || !isQuartoDoc(editor.document)) { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + // expose main language for use in keybindings, etc |
| 63 | + const tokens = engine.parse(editor.document); |
| 64 | + const language = mainLanguage(tokens); |
| 65 | + vscode.commands.executeCommand( |
| 66 | + 'setContext', |
| 67 | + 'quarto.document.languageId', |
| 68 | + language?.ids[0]); |
| 69 | +} |
0 commit comments