Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/markdown-language-features/src/client/workspace.ts
3292 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import * as vscode from 'vscode';
7
import { ITextDocument } from '../types/textDocument';
8
import { Disposable } from '../util/dispose';
9
import { isMarkdownFile, looksLikeMarkdownPath } from '../util/file';
10
import { InMemoryDocument } from './inMemoryDocument';
11
import { ResourceMap } from '../util/resourceMap';
12
13
/**
14
* Provides set of markdown files known to VS Code.
15
*
16
* This includes both opened text documents and markdown files in the workspace.
17
*/
18
export class VsCodeMdWorkspace extends Disposable {
19
20
private readonly _watcher: vscode.FileSystemWatcher | undefined;
21
22
private readonly _documentCache = new ResourceMap<ITextDocument>();
23
24
private readonly _utf8Decoder = new TextDecoder('utf-8');
25
26
constructor() {
27
super();
28
29
this._watcher = this._register(vscode.workspace.createFileSystemWatcher('**/*.md'));
30
31
this._register(this._watcher.onDidChange(async resource => {
32
this._documentCache.delete(resource);
33
}));
34
35
this._register(this._watcher.onDidDelete(resource => {
36
this._documentCache.delete(resource);
37
}));
38
39
this._register(vscode.workspace.onDidOpenTextDocument(e => {
40
this._documentCache.delete(e.uri);
41
}));
42
43
this._register(vscode.workspace.onDidCloseTextDocument(e => {
44
this._documentCache.delete(e.uri);
45
}));
46
}
47
48
private _isRelevantMarkdownDocument(doc: vscode.TextDocument) {
49
return isMarkdownFile(doc) && doc.uri.scheme !== 'vscode-bulkeditpreview';
50
}
51
52
public async getOrLoadMarkdownDocument(resource: vscode.Uri): Promise<ITextDocument | undefined> {
53
const existing = this._documentCache.get(resource);
54
if (existing) {
55
return existing;
56
}
57
58
const matchingDocument = vscode.workspace.textDocuments.find((doc) => this._isRelevantMarkdownDocument(doc) && doc.uri.toString() === resource.toString());
59
if (matchingDocument) {
60
this._documentCache.set(resource, matchingDocument);
61
return matchingDocument;
62
}
63
64
if (!looksLikeMarkdownPath(resource)) {
65
return undefined;
66
}
67
68
try {
69
const bytes = await vscode.workspace.fs.readFile(resource);
70
71
// We assume that markdown is in UTF-8
72
const text = this._utf8Decoder.decode(bytes);
73
const doc = new InMemoryDocument(resource, text, 0);
74
this._documentCache.set(resource, doc);
75
return doc;
76
} catch {
77
return undefined;
78
}
79
}
80
}
81
82