Path: blob/main/extensions/markdown-language-features/src/client/workspace.ts
3292 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import * as vscode from 'vscode';6import { ITextDocument } from '../types/textDocument';7import { Disposable } from '../util/dispose';8import { isMarkdownFile, looksLikeMarkdownPath } from '../util/file';9import { InMemoryDocument } from './inMemoryDocument';10import { ResourceMap } from '../util/resourceMap';1112/**13* Provides set of markdown files known to VS Code.14*15* This includes both opened text documents and markdown files in the workspace.16*/17export class VsCodeMdWorkspace extends Disposable {1819private readonly _watcher: vscode.FileSystemWatcher | undefined;2021private readonly _documentCache = new ResourceMap<ITextDocument>();2223private readonly _utf8Decoder = new TextDecoder('utf-8');2425constructor() {26super();2728this._watcher = this._register(vscode.workspace.createFileSystemWatcher('**/*.md'));2930this._register(this._watcher.onDidChange(async resource => {31this._documentCache.delete(resource);32}));3334this._register(this._watcher.onDidDelete(resource => {35this._documentCache.delete(resource);36}));3738this._register(vscode.workspace.onDidOpenTextDocument(e => {39this._documentCache.delete(e.uri);40}));4142this._register(vscode.workspace.onDidCloseTextDocument(e => {43this._documentCache.delete(e.uri);44}));45}4647private _isRelevantMarkdownDocument(doc: vscode.TextDocument) {48return isMarkdownFile(doc) && doc.uri.scheme !== 'vscode-bulkeditpreview';49}5051public async getOrLoadMarkdownDocument(resource: vscode.Uri): Promise<ITextDocument | undefined> {52const existing = this._documentCache.get(resource);53if (existing) {54return existing;55}5657const matchingDocument = vscode.workspace.textDocuments.find((doc) => this._isRelevantMarkdownDocument(doc) && doc.uri.toString() === resource.toString());58if (matchingDocument) {59this._documentCache.set(resource, matchingDocument);60return matchingDocument;61}6263if (!looksLikeMarkdownPath(resource)) {64return undefined;65}6667try {68const bytes = await vscode.workspace.fs.readFile(resource);6970// We assume that markdown is in UTF-871const text = this._utf8Decoder.decode(bytes);72const doc = new InMemoryDocument(resource, text, 0);73this._documentCache.set(resource, doc);74return doc;75} catch {76return undefined;77}78}79}808182