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

Add optional $uri to get the actual uri of a document #88

Merged
merged 1 commit into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog

## 0.3.0-alpha.1 UNRELEASED
- Added optional `$uri` property on `ITextDocument` which lets implementers provide an actual uri instead of a string. This helps reduce the number of calls to `URI.parse`.

## 0.2.0 October 31, 2022
- Added diagnostics for unused link definitions.
- Added diagnostics for duplicated link definitions.
Expand Down
7 changes: 3 additions & 4 deletions src/languageFeatures/codeActions/extractLinkDef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
import { CancellationToken } from 'vscode-languageserver';
import * as lsp from 'vscode-languageserver-types';
import * as nls from 'vscode-nls';
import { URI } from 'vscode-uri';
import { comparePosition, translatePosition } from '../../types/position';
import { makeRange, rangeIntersects } from '../../types/range';
import { getLine, ITextDocument } from '../../types/textDocument';
import { getDocUri, getLine, ITextDocument } from '../../types/textDocument';
import { WorkspaceEditBuilder } from '../../util/editBuilder';
import { ExternalHref, HrefKind, InternalHref, LinkDefinitionSet, MdDocumentLinksInfo, MdInlineLink, MdLink, MdLinkDefinition, MdLinkKind, MdLinkProvider } from '../documentLinks';
import { getExistingDefinitionBlock } from '../organizeLinkDefs';
Expand Down Expand Up @@ -81,7 +80,7 @@ export class MdExtractLinkDefinitionCodeActionProvider {

private _getExtractLinkAction(doc: ITextDocument, linkInfo: MdDocumentLinksInfo, targetLink: MdInlineLink<InternalHref | ExternalHref>): lsp.CodeAction {
const builder = new WorkspaceEditBuilder();
const resource = URI.parse(doc.uri);
const resource = getDocUri(doc);
const placeholder = this._getPlaceholder(linkInfo.definitions);

// Rewrite all inline occurrences of the link
Expand Down Expand Up @@ -110,7 +109,7 @@ export class MdExtractLinkDefinitionCodeActionProvider {
command: {
command: 'vscodeMarkdownLanguageservice.rename',
title: 'Rename',
arguments: [URI.parse(doc.uri), renamePosition],
arguments: [getDocUri(doc), renamePosition],
}
};
}
Expand Down
5 changes: 2 additions & 3 deletions src/languageFeatures/codeActions/removeLinkDefinition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@

import * as lsp from 'vscode-languageserver-types';
import * as nls from 'vscode-nls';
import { URI } from 'vscode-uri';
import { makeRange, rangeIntersects } from '../../types/range';
import { ITextDocument } from '../../types/textDocument';
import { getDocUri, ITextDocument } from '../../types/textDocument';
import { WorkspaceEditBuilder } from '../../util/editBuilder';
import { DiagnosticCode } from '../diagnostics';
import { MdLinkDefinition } from '../documentLinks';
Expand Down Expand Up @@ -57,7 +56,7 @@ export class MdRemoveLinkDefinitionCodeActionProvider {
const builder = new WorkspaceEditBuilder();

const range = definition.source.range;
builder.replace(URI.parse(doc.uri), makeRange(range.start.line, 0, range.start.line + 1, 0), '');
builder.replace(getDocUri(doc), makeRange(range.start.line, 0, range.start.line + 1, 0), '');

return { title, kind: lsp.CodeActionKind.QuickFix, edit: builder.renameFragment() };
}
Expand Down
8 changes: 3 additions & 5 deletions src/languageFeatures/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { LsConfiguration } from '../config';
import { MdTableOfContentsProvider } from '../tableOfContents';
import { translatePosition } from '../types/position';
import { modifyRange } from '../types/range';
import { ITextDocument } from '../types/textDocument';
import { getDocUri, ITextDocument } from '../types/textDocument';
import { Disposable, IDisposable } from '../util/dispose';
import { looksLikeMarkdownPath } from '../util/file';
import { Limiter } from '../util/limiter';
Expand Down Expand Up @@ -178,7 +178,7 @@ export class DiagnosticComputer {
}

// Current doc always implicitly exists
statCache.set(URI.parse(doc.uri), { exists: true });
statCache.set(getDocUri(doc), { exists: true });

return {
links: links,
Expand Down Expand Up @@ -626,14 +626,12 @@ export class DiagnosticsManager extends Disposable implements IPullDiagnosticsMa
}

public async computeDiagnostics(doc: ITextDocument, options: DiagnosticOptions, token: CancellationToken): Promise<lsp.Diagnostic[]> {
const uri = URI.parse(doc.uri);

const results = await this._computer.compute(doc, options, token);
if (token.isCancellationRequested) {
return [];
}

this._linkWatcher.updateLinksForDocument(uri, results.links, results.statCache);
this._linkWatcher.updateLinksForDocument(getDocUri(doc), results.links, results.statCache);
return results.diagnostics;
}

Expand Down
12 changes: 6 additions & 6 deletions src/languageFeatures/documentLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { IMdParser } from '../parser';
import { MdTableOfContentsProvider } from '../tableOfContents';
import { translatePosition } from '../types/position';
import { makeRange, rangeContains } from '../types/range';
import { getLine, ITextDocument } from '../types/textDocument';
import { getDocUri, getLine, ITextDocument } from '../types/textDocument';
import { coalesce } from '../util/arrays';
import { Disposable } from '../util/dispose';
import { r } from '../util/string';
Expand Down Expand Up @@ -205,7 +205,7 @@ function createMdLink(

let linkTarget: ExternalHref | InternalHref | undefined;
try {
linkTarget = createHref(URI.parse(document.uri), link, workspace);
linkTarget = createHref(getDocUri(document), link, workspace);
} catch {
return undefined;
}
Expand All @@ -229,7 +229,7 @@ function createMdLink(
href: linkTarget,
source: {
hrefText: link,
resource: URI.parse(document.uri),
resource: getDocUri(document),
range: { start: linkStart, end: linkEnd },
targetRange,
hrefRange,
Expand Down Expand Up @@ -449,7 +449,7 @@ export class MdLinkComputer {

private *_getAutoLinks(document: ITextDocument, noLinkRanges: NoLinkRanges): Iterable<MdLink> {
const text = document.getText();
const docUri = URI.parse(document.uri);
const docUri = getDocUri(document);
for (const match of text.matchAll(autoLinkPattern)) {
const linkOffset = (match.index ?? 0);
const linkStart = document.positionAt(linkOffset);
Expand Down Expand Up @@ -553,7 +553,7 @@ export class MdLinkComputer {
source: {
hrefText: reference,
pathText: reference,
resource: URI.parse(document.uri),
resource: getDocUri(document),
range: { start: linkStart, end: linkEnd },
targetRange: hrefRange,
hrefRange: hrefRange,
Expand All @@ -569,7 +569,7 @@ export class MdLinkComputer {

private *_getLinkDefinitions(document: ITextDocument, noLinkRanges: NoLinkRanges): Iterable<MdLinkDefinition> {
const text = document.getText();
const docUri = URI.parse(document.uri);
const docUri = getDocUri(document);
for (const match of text.matchAll(definitionPattern)) {
const offset = (match.index ?? 0);
const linkStart = document.positionAt(offset);
Expand Down
4 changes: 2 additions & 2 deletions src/languageFeatures/fileRename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { CancellationToken } from 'vscode-languageserver';
import * as lsp from 'vscode-languageserver-types';
import { URI, Utils } from 'vscode-uri';
import { isExcludedPath, LsConfiguration } from '../config';
import { ITextDocument } from '../types/textDocument';
import { getDocUri, ITextDocument } from '../types/textDocument';
import { Disposable } from '../util/dispose';
import { WorkspaceEditBuilder } from '../util/editBuilder';
import { looksLikeMarkdownPath } from '../util/file';
Expand Down Expand Up @@ -197,7 +197,7 @@ export class MdFileRenameProvider extends Disposable {
}
}

return this._addLinkRenameEdit(URI.parse(doc.uri), link, oldLink.resource, builder);
return this._addLinkRenameEdit(getDocUri(doc), link, oldLink.resource, builder);
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/languageFeatures/pathCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { IMdParser } from '../parser';
import { TableOfContents } from '../tableOfContents';
import { translatePosition } from '../types/position';
import { makeRange } from '../types/range';
import { getLine, ITextDocument } from '../types/textDocument';
import { getDocUri, getLine, ITextDocument } from '../types/textDocument';
import { Schemes } from '../util/schemes';
import { r } from '../util/string';
import { FileStat, getWorkspaceFolder, IWorkspace, openLinkToMarkdownFile } from '../workspace';
Expand Down Expand Up @@ -375,6 +375,6 @@ export class MdPathCompletionProvider {
}

private _getFileUriOfTextDocument(document: ITextDocument): URI {
return this._workspace.getContainingDocument?.(URI.parse(document.uri))?.uri ?? URI.parse(document.uri);
return this._workspace.getContainingDocument?.(getDocUri(document))?.uri ?? getDocUri(document);
}
}
6 changes: 3 additions & 3 deletions src/languageFeatures/references.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { IMdParser } from '../parser';
import { MdTableOfContentsProvider, TocEntry } from '../tableOfContents';
import { translatePosition } from '../types/position';
import { areRangesEqual, modifyRange, rangeContains } from '../types/range';
import { ITextDocument } from '../types/textDocument';
import { getDocUri, ITextDocument } from '../types/textDocument';
import { Disposable } from '../util/dispose';
import { looksLikeMarkdownPath } from '../util/file';
import { IWorkspace, statLinkToMarkdownFile } from '../workspace';
Expand Down Expand Up @@ -137,7 +137,7 @@ export class MdReferencesProvider extends Disposable {

for (const link of links) {
if (link.href.kind === HrefKind.Internal
&& looksLikeLinkToResource(this._configuration, link.href, URI.parse(document.uri))
&& looksLikeLinkToResource(this._configuration, link.href, getDocUri(document))
&& this._parser.slugifier.fromHeading(link.href.fragment).value === header.slug.value
) {
references.push({
Expand All @@ -163,7 +163,7 @@ export class MdReferencesProvider extends Disposable {
if (link.kind === MdLinkKind.Definition) {
// We could be in either the ref name or the definition
if (rangeContains(link.ref.range, position)) {
return Array.from(this._getReferencesToLinkReference(docLinks, link.ref.text, { resource: URI.parse(document.uri), range: link.ref.range }));
return Array.from(this._getReferencesToLinkReference(docLinks, link.ref.text, { resource: getDocUri(document), range: link.ref.range }));
} else if (rangeContains(link.source.hrefRange, position)) {
return this._getReferencesToLink(docLinks, link, position, token);
}
Expand Down
6 changes: 3 additions & 3 deletions src/languageFeatures/rename.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { ILogger, LogLevel } from '../logging';
import { ISlugifier } from '../slugify';
import { arePositionsEqual, translatePosition } from '../types/position';
import { modifyRange, rangeContains } from '../types/range';
import { ITextDocument } from '../types/textDocument';
import { getDocUri, ITextDocument } from '../types/textDocument';
import { Disposable } from '../util/dispose';
import { WorkspaceEditBuilder } from '../util/editBuilder';
import { Schemes } from '../util/schemes';
Expand Down Expand Up @@ -221,7 +221,7 @@ export class MdRenameProvider extends Disposable {
const version = document.version;

if (this._cachedRefs
&& this._cachedRefs.resource.fsPath === URI.parse(document.uri).fsPath
&& this._cachedRefs.resource.fsPath === getDocUri(document).fsPath
&& this._cachedRefs.version === document.version
&& arePositionsEqual(this._cachedRefs.position, position)
) {
Expand All @@ -239,7 +239,7 @@ export class MdRenameProvider extends Disposable {
}

this._cachedRefs = {
resource: URI.parse(document.uri),
resource: getDocUri(document),
version,
position,
references,
Expand Down
6 changes: 3 additions & 3 deletions src/tableOfContents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { ILogger, LogLevel } from './logging';
import { IMdParser, Token } from './parser';
import { githubSlugifier, ISlugifier, Slug } from './slugify';
import { makeRange } from './types/range';
import { getLine, ITextDocument } from './types/textDocument';
import { getDocUri, getLine, ITextDocument } from './types/textDocument';
import { Disposable } from './util/dispose';
import { IWorkspace } from './workspace';
import { MdDocumentInfoCache } from './workspaceCache';
Expand Down Expand Up @@ -73,7 +73,7 @@ export class TableOfContents {
}

public static async createForContainingDoc(parser: IMdParser, workspace: IWorkspace, document: ITextDocument, token: CancellationToken): Promise<TableOfContents> {
const context = workspace.getContainingDocument?.(URI.parse(document.uri));
const context = workspace.getContainingDocument?.(getDocUri(document));
if (context) {
const entries = (await Promise.all(Array.from(context.children, async cell => {
const doc = await workspace.openMarkdownDocument(cell.uri);
Expand All @@ -89,7 +89,7 @@ export class TableOfContents {
}

private static async _buildToc(parser: IMdParser, document: ITextDocument, token: CancellationToken): Promise<TocEntry[]> {
const docUri = URI.parse(document.uri);
const docUri = getDocUri(document);

const toc: TocEntry[] = [];
const tokens = await parser.tokenize(document);
Expand Down
6 changes: 4 additions & 2 deletions src/test/inMemoryDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,18 @@ export class InMemoryDocument implements ITextDocument {

private _doc: TextDocument;

public readonly $uri: URI;
public readonly uri: string;

constructor(
uri: URI,
contents: string,
public version = 0,
) {
this.$uri = uri;
this.uri = uri.toString();

this._doc = TextDocument.create(uri.toString(), 'markdown', version, contents);
this._doc = TextDocument.create(this.uri, 'markdown', version, contents);
}

get lineCount(): number {
Expand All @@ -38,7 +40,7 @@ export class InMemoryDocument implements ITextDocument {

updateContent(newContent: string) {
++this.version;
this._doc = TextDocument.create(this.uri.toString(), 'markdown', this.version, newContent);
this._doc = TextDocument.create(this.uri, 'markdown', this.version, newContent);
}

applyEdits(textEdits: lsp.TextEdit[]): string {
Expand Down
12 changes: 6 additions & 6 deletions src/test/inMemoryWorkspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as assert from 'assert';
import * as path from 'path';
import { Emitter } from 'vscode-languageserver';
import { URI } from 'vscode-uri';
import { ITextDocument } from '../types/textDocument';
import { getDocUri, ITextDocument } from '../types/textDocument';
import { Disposable } from '../util/dispose';
import { ResourceMap } from '../util/resourceMap';
import { FileStat, FileWatcherOptions, IFileSystemWatcher, IWorkspaceWithWatching } from '../workspace';
Expand Down Expand Up @@ -46,7 +46,7 @@ export class InMemoryWorkspace extends Disposable implements IWorkspaceWithWatch

for (const doc of documents) {
if (doc instanceof InMemoryDocument) {
this._documents.set(URI.parse(doc.uri), doc);
this._documents.set(getDocUri(doc), doc);
} else {
this._additionalFiles.set(doc);
}
Expand Down Expand Up @@ -112,20 +112,20 @@ export class InMemoryWorkspace extends Disposable implements IWorkspaceWithWatch

private _getAllKnownFilePaths(): string[] {
return [
...Array.from(this._documents.values(), doc => URI.parse(doc.uri).fsPath),
...Array.from(this._documents.values(), doc => getDocUri(doc).fsPath),
...Array.from(this._additionalFiles.keys(), uri => uri.fsPath),
];
}

public updateDocument(document: ITextDocument) {
this._documents.set(URI.parse(document.uri), document);
this._documents.set(getDocUri(document), document);
this._onDidChangeMarkdownDocumentEmitter.fire(document);
}

public createDocument(document: ITextDocument) {
assert.ok(!this._documents.has(URI.parse(document.uri)));
assert.ok(!this._documents.has(getDocUri(document)));

this._documents.set(URI.parse(document.uri), document);
this._documents.set(getDocUri(document), document);
this._onDidCreateMarkdownDocumentEmitter.fire(document);
}

Expand Down
10 changes: 10 additions & 0 deletions src/types/textDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import { Position, Range } from 'vscode-languageserver-types';
import { URI } from 'vscode-uri';
import { makeRange } from './range';

/**
Expand All @@ -14,6 +15,11 @@ export interface ITextDocument {
* The uri of the document, as a string.
*/
readonly uri: string;

/**
* The uri of the document, as a URI.
*/
readonly $uri?: URI;

/**
* Version number of the document's content.
Expand Down Expand Up @@ -41,3 +47,7 @@ export interface ITextDocument {
export function getLine(doc: ITextDocument, line: number): string {
return doc.getText(makeRange(line, 0, line, Number.MAX_VALUE)).replace(/\r?\n$/, '');
}

export function getDocUri(doc: ITextDocument): URI {
return doc.$uri ?? URI.parse(doc.uri);
}
Loading