Skip to content

Commit

Permalink
fix: API: Update DocValidator (#5115)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason3S authored Dec 26, 2023
1 parent f3bc4a3 commit 33dd2f8
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 9 deletions.
19 changes: 19 additions & 0 deletions packages/cspell-lib/api/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,10 @@ declare class SuggestionError extends Error {
constructor(message: string, code: string);
}

/**
* A range of text in a document.
* The range is inclusive of the startPos and exclusive of the endPos.
*/
interface MatchRange {
startPos: number;
endPos: number;
Expand Down Expand Up @@ -787,6 +791,21 @@ declare class DocumentValidator {
checkDocumentDirectives(forceCheck?: boolean): ValidationIssue[];
get document(): TextDocument;
updateDocumentText(text: string): Promise<void>;
/**
* Get the calculated ranges of text that should be included in the spell checking.
* @returns MatchRanges of text to include.
*/
getCheckedTextRanges(): MatchRange[];
traceWord(word: string): {
word: string;
found: boolean;
foundWord: string | undefined;
forbidden: boolean;
noSuggest: boolean;
dictName: string;
dictSource: string;
errors: Error[] | undefined;
}[];
private defaultParser;
private _checkParsedText;
private addPossibleError;
Expand Down
20 changes: 18 additions & 2 deletions packages/cspell-lib/src/lib/textValidation/docValidator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,14 @@ describe('docValidator', () => {
const doc = td(__filename, '/** This is some code */');
const dVal = new DocumentValidator(doc, {}, {});
expect(dVal.document).toBe(doc);
// dVal.prepareSync();
// expect(dVal.checkText([0, 0], '', [])).toEqual([]);
});

test('getCheckedTextRanges', async () => {
const text = '/** This is some code */';
const doc = td(__filename, text);
const dVal = new DocumentValidator(doc, {}, {});
await dVal.prepare();
expect(dVal.getCheckedTextRanges()).toEqual([{ startPos: 0, endPos: text.length }]);
});

test.each`
Expand Down Expand Up @@ -263,6 +269,16 @@ describe('shouldCheckDocument', () => {
);
});

describe('docValidator trace', () => {
test('trace word', async () => {
const text = '/** This is some code */';
const doc = td(__filename, text);
const dVal = new DocumentValidator(doc, {}, {});
await dVal.prepare();
expect(dVal.traceWord('Code')).toEqual(ac([oc({ dictName: 'en_us', foundWord: 'code' })]));
});
});

function extractRawText(text: string, issues: ValidationIssue[]): string[] {
return issues.map((issue) => {
const start = issue.offset;
Expand Down
39 changes: 39 additions & 0 deletions packages/cspell-lib/src/lib/textValidation/docValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { catchPromiseError, toError } from '../util/errors.js';
import { AutoCache } from '../util/simpleCache.js';
import type { MatchRange } from '../util/TextRange.js';
import { uriToFilePath } from '../util/Uri.js';
import { toFilePathOrHref } from '../util/url.js';
import { defaultMaxDuplicateProblems, defaultMaxNumberOfProblems } from './defaultConstants.js';
import { determineTextDocumentSettings } from './determineTextDocumentSettings.js';
import type { TextValidator } from './lineValidatorFactory.js';
Expand Down Expand Up @@ -320,6 +321,40 @@ export class DocumentValidator {
await this._updatePrep();
}

/**
* Get the calculated ranges of text that should be included in the spell checking.
* @returns MatchRanges of text to include.
*/
public getCheckedTextRanges(): MatchRange[] {
assert(this._preparations, ERROR_NOT_PREPARED);
return this._preparations.includeRanges;
}

public traceWord(word: string) {
assert(this._preparations, ERROR_NOT_PREPARED);
const dictCollection = this._preparations.dictionary;
const config = this._preparations.config;

const opts = {
ignoreCase: true,
allowCompoundWords: config.allowCompoundWords || false,
};

const trace = dictCollection.dictionaries
.map((dict) => ({ dict, findResult: dict.find(word, opts) }))
.map(({ dict, findResult }) => ({
word,
found: !!findResult?.found,
foundWord: findResult?.found || undefined,
forbidden: findResult?.forbidden || false,
noSuggest: findResult?.noSuggest || false,
dictName: dict.name,
dictSource: toFilePathOrHref(dict.source),
errors: normalizeErrors(dict.getErrors?.()),
}));
return trace;
}

private defaultParser(): Iterable<ParsedText> {
return pipeSync(
this.document.getLines(),
Expand Down Expand Up @@ -521,3 +556,7 @@ function recordPerfTime(timings: PerfTimings, name: string): () => void {
function timePromise<T>(timings: PerfTimings, name: string, p: Promise<T>): Promise<T> {
return p.finally(recordPerfTime(timings, name));
}

function normalizeErrors(errors: Error[] | undefined): Error[] | undefined {
return errors?.length ? errors : undefined;
}
10 changes: 3 additions & 7 deletions packages/cspell-lib/src/lib/trace.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { fileURLToPath } from 'node:url';

import type { CSpellSettings, DictionaryId, LocaleId } from '@cspell/cspell-types';
import { genSequence } from 'gensequence';

import type { LanguageId } from './LanguageIds.js';
import { toInternalSettings } from './Settings/CSpellSettingsServer.js';
import { finalizeSettings, mergeSettings } from './Settings/index.js';
import { calcSettingsForLanguageId } from './Settings/LanguageSettings.js';
import { finalizeSettings, mergeSettings } from './Settings/index.js';
import type { HasOptions, SpellingDictionaryCollection } from './SpellingDictionary/index.js';
import { getDictionaryInternal, refreshDictionaryCache } from './SpellingDictionary/index.js';
import { toFilePathOrHref } from './util/url.js';
import * as util from './util/util.js';

export interface TraceResult {
Expand Down Expand Up @@ -115,8 +114,5 @@ export async function* traceWordsAsync(
}

function dictSourceToFilename(source: string): string {
if (source.startsWith('file:')) {
return fileURLToPath(source);
}
return source;
return toFilePathOrHref(source);
}
4 changes: 4 additions & 0 deletions packages/cspell-lib/src/lib/util/TextRange.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import * as GS from 'gensequence';

/**
* A range of text in a document.
* The range is inclusive of the startPos and exclusive of the endPos.
*/
export interface MatchRange {
startPos: number;
endPos: number;
Expand Down

0 comments on commit 33dd2f8

Please sign in to comment.