Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 | 85x 85x 170x 85x 85x 85x 85x 85x 85x 85x 85x 85x 85x 1x 6x 1x 1x 1x 2x 13x 1x 1x 13x 6x 7x 7x 6x 1x 3x 1x 1x 2x 3x 3x 1x 2x 2x 1x 1x 8x 8x 8x 7x 7x 6x 6x 5x 5x 4x 4x 4x 4x 1x 1x 3x 1x 1x 2x 3x 3x 1x 2x 2x 1x 1x 28x 2x 26x 6x 3x 34x 34x 34x 34x 33x 34x 26x 26x 26x 8x 1x 1x 8x 1x 8x 8x 18x 18x 17x 17x 18x 3x 18x 18x 18x 10x 10x 2x 1x 1x 1x 1x 16x 16x 1x 15x 15x 15x 1x 14x 14x 1x 13x 13x 13x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 1x 3x 11x 11x 11x 11x 11x 11x 11x 11x 6x 5x 5x 4x 4x 5x 5x 4x 1x 1x 1x 1x 1x 22x 22x 22x 22x 22x 6x 16x 16x 11x 11x 11x 11x 11x 11x 11x 11x 44x 4x 2x 2x 2x 4x 2x 2x 2x 1x 1x 1x 3x 3x 2x 2x 2x 2x 1x 3x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 2x 2x 2x 1x 1x 1x 2x 9x 9x 9x 9x 9x 9x 1x 8x 1x 6x 6x 6x 6x 2x 4x 1x 3x 3x 1x 3x 2x 4x 4x 4x 6x 6x 4x 8x 8x 2x 6x 6x 1x 5x | import * as vscode from 'vscode';
import { Store, VocabularyRepository } from '@faubulous/mentor-rdf';
import { IDocumentContext } from '@src/services/document/document-context.interface';
import { IDocumentFactory } from '@src/services/document/document-factory.interface';
import { IDocumentTokenSource, TokenDelivery } from '@src/services/document/document-token-source.interface';
import { getMaxCellSlugNumber } from '@src/services/notebook/notebook-cell-slugs';
import { WorkspaceUri } from '@src/providers/workspace-uri';
import { getConfig } from '@src/utilities/vscode/config';
import { createEventLoopYielder } from '@src/utilities/scheduling';
import { isTemplate } from 'triplate';
import { getLog } from '@src/utilities/vscode/log';
import { getErrorMessage } from '@src/utilities/error';
/**
* Maps document URIs to loaded document contexts.
*/
export interface DocumentIndex {
[key: string]: IDocumentContext;
}
/**
* Manages document contexts and coordinates token delivery from language servers.
* This is the central service for loading, tracking, and retrieving RDF document contexts.
*/
export class DocumentContextService {
private readonly _convertTargetLanguageIds = ['ntriples', 'nquads', 'turtle', 'xml'];
private _contexts: DocumentIndex = {};
/**
* Maps document URIs to loaded document contexts.
*/
get contexts(): DocumentIndex {
return this._contexts;
}
/**
* The currently active document context or `undefined`.
*/
activeContext: IDocumentContext | undefined;
private readonly _onDidChangeDocumentContext = new vscode.EventEmitter<IDocumentContext | undefined>();
/**
* The language IDs of the documents that were closed during the current event delivery, keyed
* by document URI. VS Code reports a change of the language of a document by closing and
* reopening it, so this is used to detect language changes in {@link handleTextDocumentOpened}.
*/
private readonly _closedDocumentLanguages = new Map<string, string>();
/**
* The last value sent for the `mentor.editor.cursorOnResource` context key, or
* `undefined` before it was first set.
*/
private _cursorOnResource: boolean | undefined;
/**
* The loads and triple reloads in progress, keyed by document URI.
*/
private readonly _pendingLoads = new Map<string, Promise<void>>();
/**
* An event that is fired after the active document context has changed.
*/
readonly onDidChangeDocumentContext = this._onDidChangeDocumentContext.event;
constructor(
private readonly _extensionContext: vscode.ExtensionContext,
private readonly _store: Store,
private readonly _vocabulary: VocabularyRepository,
private readonly _documentFactory: IDocumentFactory,
private readonly _tokenSource: IDocumentTokenSource
) {
// Register event handlers for editor and document changes.
this._extensionContext.subscriptions.push(...[
vscode.window.onDidChangeActiveTextEditor(() => this.handleActiveEditorChanged()),
vscode.window.onDidChangeTextEditorSelection((e) => this._setCursorOnResourceContext(e.textEditor)),
this.onDidChangeDocumentContext(() => this._setCursorOnResourceContext(vscode.window.activeTextEditor)),
vscode.window.onDidChangeActiveNotebookEditor((e) => this.handleActiveNotebookEditorChanged(e)),
vscode.workspace.onDidOpenNotebookDocument((notebook) => this.handleNotebookDocumentOpened(notebook)),
vscode.workspace.onDidOpenTextDocument((document) => this.handleTextDocumentOpened(document)),
vscode.workspace.onDidChangeTextDocument((e) => this.handleTextDocumentChanged(e)),
vscode.workspace.onDidChangeNotebookDocument((e) => this.handleNotebookDocumentChanged(e)),
vscode.workspace.onDidCloseTextDocument((e) => this.handleDocumentClosed(e)),
this._tokenSource.onDidDeliverTokens((delivery) => this._handleTokenDelivery(delivery)),
this._onDidChangeDocumentContext,
this
]);
}
async loadActiveEditorAtStartup(): Promise<void> {
await this.handleActiveEditorChanged();
await this.activateDocument();
}
/**
* Dispose the manager and clean up resources.
*/
dispose(): void {
// The event emitter and subscriptions are disposed via the extension
// context subscriptions registered in the constructor.
}
/**
* Handles a token delivery from the token source. When the delivery was not
* consumed by a waiting document load, this is the normal path for document
* edits: reload the triples of an already-loaded context to bring it up to
* date with the latest tokens.
* @param delivery The token delivery.
*/
private _handleTokenDelivery(delivery: TokenDelivery): void {
if (delivery.consumed) {
return;
}
const context = this.contexts[delivery.uri];
if (context?.isParsed) {
this._reloadContextTriples(delivery.uri).catch(e => {
getLog().warn('Failed to reload context after token delivery:', e);
});
}
}
/**
* Clear all loaded document contexts. Used when re-indexing the workspace to reset state.
*/
clear(): void {
this._contexts = {};
}
/**
* Get the document context from a URI.
* @param uri A document or workspace URI.
* @returns A document context if the document is loaded, `undefined` otherwise.
*/
getDocumentContextFromUri(uri: string): IDocumentContext | undefined {
if (uri.startsWith(WorkspaceUri.uriScheme)) {
const u = WorkspaceUri.toFileUri(vscode.Uri.parse(uri)).toString();
return this.contexts[u];
} else {
return this.contexts[uri];
}
}
/**
* Get the document context from a text document.
* @param document A text document.
* @param contextType The expected type of the document context.
* @returns A document context of the specified type if the document is loaded and matches the type, null otherwise.
*/
getDocumentContext<T extends IDocumentContext>(document: vscode.TextDocument, contextType: new (...args: any[]) => T): T | null {
const uri = document.uri.toString();
if (!this.contexts[uri]) {
return null;
}
const context = this.contexts[uri];
if (!(context instanceof contextType)) {
return null;
}
return context as T;
}
/**
* Reload triples on an existing context using its current tokens and the latest document content.
* Called when the language server delivers updated tokens for an already-loaded document.
* @param uri The document URI.
*/
private _reloadContextTriples(uri: string): Promise<void> {
return this._trackLoad(uri, this._reloadTriples(uri));
}
/**
* Loads the triples of an existing context again and runs the inference; see
* {@link _reloadContextTriples}.
* @param uri The document URI.
*/
private async _reloadTriples(uri: string): Promise<void> {
const context = this.contexts[uri];
if (!context?.isParsed) return;
const doc = vscode.workspace.textDocuments.find(d => d.uri.toString() === uri);
if (!doc) return;
// Loading and inference each take seconds for very large documents; give the
// event loop a turn in between when a phase used up the budget.
const eventLoop = createEventLoopYielder();
await context.loadTriples(doc.getText());
await eventLoop.yieldIfBusy();
// Verify the context wasn't replaced while yielding.
if (this.contexts[uri] !== context) return;
await context.infer();
// Verify the context wasn't replaced during the async operations.
Iif (this.contexts[uri] !== context) return;
context.activeLanguageTag = getConfig().get('definitionTree.defaultLanguageTag', context.primaryLanguage);
if (this.activeContext?.uri.toString() === uri) {
this.activeContext = context;
this._onDidChangeDocumentContext.fire(context);
}
}
/**
* Get the document context from a file or workspace URI.
* @param uri A document or workspace URI.
* @returns A document context if the document is loaded, `undefined` otherwise.
*/
getContextFromUri(uri: string): IDocumentContext | undefined {
if (uri.startsWith(WorkspaceUri.uriScheme)) {
const u = WorkspaceUri.toFileUri(vscode.Uri.parse(uri)).toString();
return this.contexts[u];
} else {
return this.contexts[uri];
}
}
/**
* Get the document context from a text document.
* @param document A text document.
* @param contextType The expected type of the document context.
* @returns A document context of the specified type if the document is loaded and matches the type, null otherwise.
*/
getContext<T extends IDocumentContext>(document: vscode.TextDocument, contextType: new (...args: any[]) => T): T | null {
const uri = document.uri.toString();
if (!this.contexts[uri]) {
return null;
}
const context = this.contexts[uri];
if (!(context instanceof contextType)) {
return null;
}
return context as T;
}
/**
* Load a text document into a document context.
* @param document The text document to load.
* @param forceReload Indicates whether a new context should be created for existing contexts.
* @param slug Optional slug to assign to the context before triples are loaded. This ensures
* the graph IRI uses the human-readable slug from the start (important for notebook cells).
* @returns A promise that resolves to the document context or undefined if superseded/unsupported.
*/
loadDocument(document: vscode.TextDocument, forceReload: boolean = false, slug?: string): Promise<IDocumentContext | undefined> {
if (!document || !this._documentFactory.supportedLanguages.has(document.languageId)) {
return Promise.resolve(undefined);
}
return this._trackLoad(document.uri.toString(), this._loadDocument(document, forceReload, slug));
}
isLoading(uri: string): boolean {
return this._pendingLoads.has(uri);
}
async waitUntilLoaded(uri: string): Promise<void> {
await this._pendingLoads.get(uri);
}
/**
* Registers a load as the one in progress for a document until it settles.
* @param uri The document URI.
* @param load The load.
* @returns The load.
*/
private _trackLoad<T>(uri: string, load: Promise<T>): Promise<T> {
const pending = load.then(() => undefined, () => undefined);
this._pendingLoads.set(uri, pending);
pending.then(() => {
if (this._pendingLoads.get(uri) === pending) {
this._pendingLoads.delete(uri);
}
});
return load;
}
/**
* Loads a supported document into a context; see {@link loadDocument}.
*/
private async _loadDocument(document: vscode.TextDocument, forceReload: boolean, slug?: string): Promise<IDocumentContext | undefined> {
const uri = document.uri.toString();
let context = this.contexts[uri];
if (context?.isLoaded && !forceReload) {
// If a slug is provided and differs from the current slug, update it now and
// trigger a reload so the triples are stored under the correct graph IRI.
// This handles the race where handleActiveEditorChanged loaded the cell without
// a slug before the workspace indexer ran.
if (slug !== undefined && context.slug !== slug) {
context.slug = slug;
this._reloadContextTriples(uri).catch(e => {
getLog().warn('Failed to reload context after slug update:', e);
});
}
// Indexing releases the tokens of files that are not open in an editor;
// the editor needs them back for its position-based features. The wait
// consumes the delivery, so the triples are not loaded again.
if (context.isTokenized() && !context.isParsed) {
await this._restoreTokens(uri, document);
}
// Compute the inference graph on the document, if it does not exist.
context.infer();
return context;
}
// Start a new load generation for this URI. This invalidates any concurrent
// load that may be in progress (awaiting tokens or loading triples).
const generation = this._tokenSource.beginLoad(uri);
// Create a new context only when one doesn't exist.
// On force reload we intentionally reuse the existing context so that
// already available tokens can be reused and reindexing does not block
// on token delivery timeouts.
if (!context) {
context = this._documentFactory.create(document.uri, document.languageId);
// Register context immediately so language client notification handlers can find it.
this.contexts[uri] = context;
}
// Set the slug before loading triples so that graphIri uses the human-readable
// slug as the URI fragment from the very first load (rather than the opaque
// VS Code-assigned cell fragment).
if (slug !== undefined) {
context.slug = slug;
}
const content = document.getText();
// Parsing, loading and inference each take long for large documents; give the
// event loop a turn in between when a phase used up the budget. The parse is
// counted, so that requests which only need the tokens (go to definition,
// hovers, document links) are answered before the triples are loaded.
const eventLoop = createEventLoopYielder();
// Check if the context already has parser output (from a language server notification
// that arrived early). If not, wait for tokens from the language server.
if (!context.isParsed) {
try {
// Parse the already-open document in-process. Passing the document
// keeps this reliable and O(1): looking it up by URI in
// `workspace.textDocuments` can miss a just-opened document that VS
// Code has already dropped from the list (e.g. during bulk
// indexing), which would otherwise stall for the full token-wait
// timeout waiting for a delivery that never comes.
await this._tokenSource.waitForTokens(uri, undefined, document);
} catch (e) {
// If this load was superseded by a newer one, abandon silently.
if (!this._tokenSource.isCurrentLoad(uri, generation)) {
return;
}
// Timeout waiting for tokens - this can happen if the language server is slow
// or not responding or if the document simply does not contain any tokens (e.g. empty document).
// In this case, we proceed with loading the document without tokens, and log a warning.
const message = getErrorMessage(e);
getLog().warn(`Timeout waiting for tokens: ${uri}`, message);
return context;
}
}
await eventLoop.yieldIfBusy();
// Check if this load was superseded after awaiting tokens.
if (!this._tokenSource.isCurrentLoad(uri, generation)) {
return;
}
// Tokens available, load triples into store.
await context.loadTriples(content);
await eventLoop.yieldIfBusy();
// Check if this load was superseded after loading triples.
if (!this._tokenSource.isCurrentLoad(uri, generation)) {
return;
}
// Compute the inference graph on the document to simplify querying.
await context.infer();
// Final supersession check after all async work is done.
if (!this._tokenSource.isCurrentLoad(uri, generation)) {
return;
}
// The language tag statistics were counted while the triples were loaded. We default to
// the user choice of the primary language tag, as a document may use several languages.
context.activeLanguageTag = getConfig().get('definitionTree.defaultLanguageTag', context.primaryLanguage);
this.contexts[uri] = context;
return context;
}
/**
* Parses an open document whose tokens were released after indexing, so the
* editor features that work on tokens are available again.
* @param uri The document URI.
* @param document The open document.
*/
private async _restoreTokens(uri: string, document: vscode.TextDocument): Promise<void> {
try {
await this._tokenSource.waitForTokens(uri, undefined, document);
} catch (e) {
getLog().warn(`Failed to restore the tokens of ${uri}:`, getErrorMessage(e));
}
}
/**
* Loads a document into a context directly from its raw content, without
* opening a VS Code text document. Workspace indexing uses this to avoid the
* dominant per-file cost of `openTextDocument` — building the text-document
* model and firing `onDidOpenTextDocument` to every registered provider — which
* profiling showed accounts for the bulk of indexing time.
*
* Parsing happens in-process and does not go through the token source, so this
* path deliberately does not emit token deliveries and therefore does not
* trigger the diagnostics that ride on them. Use an explicit workspace
* diagnostics run to validate indexed files.
* @param uri The document URI.
* @param content The document text (e.g. read via `workspace.fs.readFile`).
* @param forceReload Whether to rebuild an already-loaded context.
* @returns The loaded context, or `undefined` when the language is unsupported
* or the load was superseded by a newer one.
*/
async loadDocumentContent(uri: vscode.Uri, content: string, forceReload: boolean = false): Promise<IDocumentContext | undefined> {
const languageId = this._documentFactory.getDocumentLanguageId(uri);
Iif (!languageId || !this._documentFactory.supportedLanguages.has(languageId)) {
return;
}
const key = uri.toString();
let context = this._contexts[key];
Iif (context?.isLoaded && !forceReload) {
// Compute the inference graph on the document, if it does not exist.
context.infer();
return context;
}
// Start a new load generation so a concurrent editor-driven load can detect
// that it superseded this one (and vice versa), mirroring loadDocument.
const generation = this._tokenSource.beginLoad(key);
Eif (!context) {
context = this._documentFactory.create(uri, languageId);
this._contexts[key] = context;
}
// Lexing, parsing, loading and inference each take up to seconds for very large
// files; give the event loop a turn between them when a phase used up the budget.
const eventLoop = createEventLoopYielder();
// Parse the content in-process. This sets the context's tokens/parsed data
// exactly as a token-source delivery would, but without a text document.
context.parse(content);
await eventLoop.yieldIfBusy();
Iif (!this._tokenSource.isCurrentLoad(key, generation)) {
return;
}
await context.loadTriples(content);
await eventLoop.yieldIfBusy();
Iif (!this._tokenSource.isCurrentLoad(key, generation)) {
return;
}
// Compute the inference graph on the document to simplify querying.
await context.infer();
Iif (!this._tokenSource.isCurrentLoad(key, generation)) {
return;
}
// The language tag statistics were counted while the triples were loaded. We default to
// the user choice of the primary language tag, as a document may use several languages.
context.activeLanguageTag = getConfig().get('definitionTree.defaultLanguageTag', context.primaryLanguage);
this._contexts[key] = context;
return context;
}
/**
* Activate the document associated with the active context in the editor.
* If the active context's document is not currently open in the editor, it will be opened.
* @returns A promise that resolves to the active text editor or `undefined`.
*/
async activateDocument(): Promise<vscode.TextEditor | undefined> {
const documentUri = vscode.window.activeTextEditor?.document.uri;
// Compare by string value: Uri instances are never reference-equal across
// contexts, so an object comparison would re-open (and steal focus to)
// the document even when it is already active.
if (this.activeContext && this.activeContext.uri.toString() !== documentUri?.toString()) {
await vscode.commands.executeCommand("vscode.open", this.activeContext.uri);
}
return vscode.window.activeTextEditor;
}
/**
* Handle active editor changed event.
* Loads the document and fires context changed event.
*/
async handleActiveEditorChanged(): Promise<void> {
const editor = vscode.window.activeTextEditor;
// Every context key is an IPC round trip to the workbench, which is busy laying out
// a newly opened document. The keys only drive menus and buttons, so they are sent
// without holding up the load that all language features of the document wait for.
const contextKeysSet = this._setEditorContextKeys(editor);
try {
await this._loadActiveEditorDocument(editor);
} finally {
await contextKeysSet;
}
}
/**
* Sets the editor context keys that depend on the active editor, all at once.
* @param editor The active editor, or `undefined` when there is none.
*/
private async _setEditorContextKeys(editor?: vscode.TextEditor): Promise<void> {
const document = editor?.document.uri ? editor.document : undefined;
await Promise.all([
this._setCursorOnResourceContext(editor),
this._setConvertFileFormatContexts(document?.languageId, document?.uri.toString()),
this._setTriplateTemplateContext(document)
]);
}
/**
* Loads the document of the active editor, makes it the active context and fires
* the context changed event.
* @param editor The active editor, or `undefined` when there is none.
*/
private async _loadActiveEditorDocument(editor?: vscode.TextEditor): Promise<void> {
const uri = editor?.document.uri;
if (!editor || !uri || uri.toString() === this.activeContext?.uri.toString()) {
return;
}
const context = await this.loadDocument(editor.document, false, this._getNotebookCellSlug(editor.document));
if (context) {
this.activeContext = context;
this._onDidChangeDocumentContext.fire(context);
}
// For XML, isRdfDocument could not be determined from the language ID alone;
// update it now that loading is complete.
Iif (editor.document.languageId === 'xml') {
await vscode.commands.executeCommand('setContext', 'mentor.editor.isRdfDocument', context?.isLoaded === true);
}
}
/**
* Finds the slug of a notebook cell in the cell metadata, so that the graph IRI uses
* the human-readable slug from the very first load.
* @param document A text document.
* @returns The slug, or `undefined` if the document is not a notebook cell or has no slug.
*/
private _getNotebookCellSlug(document: vscode.TextDocument): string | undefined {
if (document.uri.scheme !== 'vscode-notebook-cell') {
return undefined;
}
const uri = document.uri.toString();
for (const notebook of vscode.workspace.notebookDocuments) {
const cell = notebook.getCells().find(c => c.document.uri.toString() === uri);
Eif (cell) {
return cell.metadata?.slug as string | undefined;
}
}
return undefined;
}
/**
* Sets the `mentor.editor.cursorOnResource` context key used to toggle visibility of the
* "Describe Resource" editor context-menu item. Updated synchronously on every selection
* change so the key is current when a right-click opens the menu.
* @param editor The editor whose caret position should be evaluated, or `undefined`.
*/
private async _setCursorOnResourceContext(editor?: vscode.TextEditor): Promise<void> {
const uri = editor?.document?.uri?.toString();
const position = editor?.selection?.active;
const iri = uri && position ? this.contexts[uri]?.getIriAtPosition(position) : undefined;
const cursorOnResource = !!iri;
// The selection changes on every keystroke and cursor move, while the key rarely
// does; only send the IPC call to the workbench when the value changes.
if (cursorOnResource === this._cursorOnResource) {
return;
}
this._cursorOnResource = cursorOnResource;
await vscode.commands.executeCommand('setContext', 'mentor.editor.cursorOnResource', cursorOnResource);
}
/**
* Sets the `mentor.editor.isTriplateTemplate` context key used to toggle the
* template execute button in the editor title bar.
* @param document The active document, or `undefined` when there is no active editor.
*/
private async _setTriplateTemplateContext(document?: vscode.TextDocument): Promise<void> {
const isTriplateTemplate = document ? isTemplate(document.getText()) : false;
await vscode.commands.executeCommand('setContext', 'mentor.editor.isTriplateTemplate', isTriplateTemplate);
}
/**
* Sets the language-derived editor context keys for the active document: convert-file-format
* command visibility/enablement, `mentor.editor.isRdfDocument`, and `mentor.editor.isMentorLanguage`
* (used to gate resource-oriented features such as the "Describe Resource" menu item). Keying off
* the active document — rather than the caret — keeps these stable when a right-click opens a menu.
* @param languageId The language ID of the current document. If `undefined`, all contexts are set to `false`.
* @returns A promise that resolves when the contexts have been set.
*/
private async _setConvertFileFormatContexts(languageId?: string, uri?: string): Promise<void> {
const targets = new Set(languageId ? this._documentFactory.getConvertibleTargetLanguageIds(languageId) : []);
const convertible = languageId ? this._documentFactory.isConvertibleLanguage(languageId) : false;
// For non-XML triple-source languages the language ID is unambiguous.
// For XML the language ID is shared with plain XML documents, so we only
// confirm it is RDF/XML once the document context has been successfully loaded.
const isTripleSource = languageId ? this._documentFactory.isTripleSourceLanguage(languageId) : false;
const isRdfDocument = isTripleSource && (languageId !== 'xml' || (uri !== undefined && this.contexts[uri]?.isLoaded === true));
// Whether the document is one of Mentor's first-class RDF authoring languages, sourced from
// the canonical RDF_LANGUAGE_IDS list so menu `when` clauses need not duplicate it.
const isRdfLanguage = languageId ? this._documentFactory.isRdfLanguage(languageId) : false;
// The keys are independent, so they are sent at once rather than one round trip after another.
await Promise.all([
vscode.commands.executeCommand('setContext', 'mentor.command.convertFileFormat.executable', convertible),
vscode.commands.executeCommand('setContext', 'mentor.editor.isRdfDocument', isRdfDocument),
vscode.commands.executeCommand('setContext', 'mentor.editor.isMentorLanguage', isRdfLanguage),
...this._convertTargetLanguageIds.map(targetLanguageId => vscode.commands.executeCommand(
'setContext',
`mentor.command.convertFileFormat.target.${targetLanguageId}`,
targets.has(targetLanguageId)
))
]);
}
/**
* Handle active notebook editor changed event.
* Loads all RDF cells in the notebook.
* @param editor The notebook editor.
*/
async handleActiveNotebookEditorChanged(editor: vscode.NotebookEditor | undefined): Promise<void> {
if (!editor) {
return;
}
// Load the selected cell first so the features of the cell the user is
// looking at come up before the rest of the notebook loads.
const cells = [...editor.notebook.getCells()];
const selectedIndex = editor.selection?.start;
Iif (selectedIndex !== undefined && selectedIndex >= 0 && selectedIndex < cells.length) {
cells.unshift(...cells.splice(selectedIndex, 1));
}
// Each cell load pays a full parse, triple load and inference pass;
// yield between cells so a large notebook does not block the extension host.
const eventLoop = createEventLoopYielder();
// Load all RDF cells in the notebook to ensure their graphs are created.
for (const cell of cells) {
if (this._documentFactory.isTripleSourceLanguage(cell.document.languageId)) {
await eventLoop.yieldIfBusy();
const slug = cell.metadata?.slug as string | undefined;
await this.loadDocument(cell.document, false, slug);
}
}
}
/**
* Handle notebook document opened event. Loads the contexts of all supported
* cells so diagnostics and quick fixes work in notebooks that are open but
* never focused — cells only otherwise acquire a context when they become
* the active editor or the workspace indexer walks the notebook file.
* @param notebook The opened notebook document.
*/
async handleNotebookDocumentOpened(notebook: vscode.NotebookDocument): Promise<void> {
const eventLoop = createEventLoopYielder();
for (const cell of notebook.getCells()) {
if (!this._documentFactory.supportedLanguages.has(cell.document.languageId)) {
continue;
}
await eventLoop.yieldIfBusy();
const slug = cell.metadata?.slug as string | undefined;
try {
// Already-loaded cells return immediately; concurrent loads (e.g.
// the indexer opening the same notebook) are guarded by the token
// source's load generations.
await this.loadDocument(cell.document, false, slug);
} catch (e) {
getLog().warn(`Failed to load notebook cell ${cell.document.uri.toString()}:`, getErrorMessage(e));
}
}
}
/**
* Handle notebook document changed event.
* Assigns auto-generated slugs to newly inserted RDF cells so their ID CodeLens appears immediately.
* @param e The notebook document change event.
*/
async handleNotebookDocumentChanged(e: vscode.NotebookDocumentChangeEvent): Promise<void> {
const addedCells: vscode.NotebookCell[] = [];
for (const change of e.contentChanges) {
for (const cell of change.addedCells) {
const isTripleSource = this._documentFactory.isTripleSourceLanguage(cell.document.languageId);
const hasSlug = typeof cell.metadata?.slug === 'string';
if (isTripleSource && !hasSlug) {
addedCells.push(cell);
}
}
}
if (addedCells.length === 0) {
return;
}
const cellEdits: {
cell: vscode.NotebookCell;
metadata: { [key: string]: any },
edit: vscode.NotebookEdit;
}[] = [];
let n = getMaxCellSlugNumber(e.notebook) + 1;
for (const cell of addedCells) {
const metadata = {
...cell.metadata,
slug: `cell-${n}`,
slugIsAuto: true
};
cellEdits.push({
cell,
metadata: metadata,
edit: vscode.NotebookEdit.updateCellMetadata(cell.index, metadata),
});
n++;
}
Eif (cellEdits.length > 0) {
const workspaceEdit = new vscode.WorkspaceEdit();
workspaceEdit.set(e.notebook.uri, cellEdits.map(e => e.edit));
await vscode.workspace.applyEdit(workspaceEdit);
for (const cellEdit of cellEdits) {
const document = cellEdit.cell.document;
const context = await this.loadDocument(document, false, cellEdit.metadata.slug);
Eif (context) {
this._onDidChangeDocumentContext.fire(context);
}
}
}
}
/**
* Handle text document changed event. Does not trigger a full document reload.
* Instead, the existing contextis kept visible and the reload happens when the
* language server delivers updated tokens via the token source → _reloadContextTriples.
* @param e The text document change event.
*/
async handleTextDocumentChanged(e: vscode.TextDocumentChangeEvent): Promise<void> {
if (!this._documentFactory.supportedLanguages.has(e.document.languageId)) {
return;
}
const uri = e.document.uri.toString();
let context = this.contexts[uri];
if (!context) {
// No context exists yet — create one so the language client notification
// handler can find it and set tokens on it.
context = this._documentFactory.create(e.document.uri, e.document.languageId);
this.contexts[uri] = context;
// The token source's own change handler is subscribed before this one
// and bails out for documents without a context, so the edit that just
// created the context scheduled no re-parse — without this kick, no
// diagnostics or quick fixes would appear until a second edit.
this._tokenSource.refreshTokens(uri);
}
// Notify the context for immediate lightweight reactions (e.g. auto-prefix).
context.onDidChangeDocument(e);
}
/**
* Handle text document closed event.
* @param document The closed text document.
*/
handleDocumentClosed(document: vscode.TextDocument): void {
const uri = document.uri.toString();
const context = this.contexts[uri];
// A language change closes and reopens the document in the same event delivery, so the
// language only needs to be remembered until the delivery has finished.
this._closedDocumentLanguages.set(uri, document.languageId);
queueMicrotask(() => this._closedDocumentLanguages.delete(uri));
// Notebook cell documents close when their cell is deleted or the
// notebook is closed; without cleanup their contexts and graphs would
// leak for the rest of the session and keep stale data in the store.
const isNotebookCell = document.uri.scheme === 'vscode-notebook-cell';
if (context && (context.isTemporary || isNotebookCell)) {
// Cleanup temporary / non-persisted document context generated by views.
this._deleteContext(uri);
} else if (context && context.isTokenized()) {
// The context stays in the index, but the closed editor no longer needs
// the tokens; opening the document again parses it anew.
context.releaseTokens();
}
}
/**
* Handle text document opened event. VS Code reports a change of the language of a document,
* e.g. of an unsaved document from plain text to Turtle, by closing and reopening it without
* changing the active editor. The context that was created for the previous language has the
* wrong type then, so it is replaced, and the document is made the active context if it is
* shown in the active editor.
* @param document The opened text document.
*/
async handleTextDocumentOpened(document: vscode.TextDocument): Promise<void> {
const uri = document.uri.toString();
const previousLanguageId = this._closedDocumentLanguages.get(uri);
this._closedDocumentLanguages.delete(uri);
if (previousLanguageId === undefined || previousLanguageId === document.languageId) {
return;
}
// Keep the context when switching to an unsupported language, so that the triples of the
// document remain in the workspace index.
if (!this._documentFactory.supportedLanguages.has(document.languageId)) {
return;
}
this._deleteContext(uri);
if (this.activeContext?.uri.toString() === uri) {
this.activeContext = undefined;
}
if (vscode.window.activeTextEditor?.document.uri.toString() === uri) {
await this.handleActiveEditorChanged();
}
}
/**
* Removes the contexts of documents that no longer exist and deletes their graphs
* from the store. For a notebook file, the contexts of all of its cells are removed.
* @param uris The URIs of the removed files.
*/
removeDocuments(uris: ReadonlyArray<vscode.Uri>): void {
const fileKeys = new Set(uris.map(uri => uri.toString()));
const notebookPaths = new Set(uris.map(uri => uri.path));
for (const key of Object.keys(this._contexts)) {
// Notebook cells are indexed under cell URIs which share the notebook's path.
const isRemovedCell = key.startsWith('vscode-notebook-cell:') && notebookPaths.has(vscode.Uri.parse(key).path);
if (fileKeys.has(key) || isRemovedCell) {
this._deleteContext(key);
}
}
}
/**
* Removes a document context and deletes its graphs from the store to free up memory.
* @param key The document URI under which the context is stored.
*/
private _deleteContext(key: string): void {
const context = this._contexts[key];
if (!context) {
return;
}
delete this._contexts[key];
// A preset graph is owned by the store, which loads it at startup and on
// reindexing; the context only borrows it.
if (context.isPreset) {
return;
}
// The inference graphs go with the data graphs; leaving them behind kept
// the inferred triples of deleted and renamed files in the store for good.
this._store.deleteGraphs(context.graphs, true);
}
}
|