Skip to content

Commit

Permalink
Merge 6f9a9f2 into 76a7432
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason3S committed Mar 8, 2022
2 parents 76a7432 + 6f9a9f2 commit faf6197
Show file tree
Hide file tree
Showing 9 changed files with 152 additions and 39 deletions.
137 changes: 115 additions & 22 deletions packages/cspell-lib/api/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,57 @@ declare namespace text_d {
declare type LanguageId = string;
declare function getLanguagesForExt(ext: string): string[];

declare type DocumentUri = URI;
interface Position {
line: number;
character: number;
}
interface TextDocumentLine {
readonly text: string;
readonly offset: number;
readonly position: Position;
}
/**
* A simple text document. Not to be implemented. The document keeps the content
* as string.
*/
interface TextDocument {
/**
* The associated URI for this document. Most documents have the __file__-scheme, indicating that they
* represent files on disk. However, some documents may have other schemes indicating that they are not
* available on disk.
*/
readonly uri: DocumentUri;
/**
* The identifier of the language associated with this document.
*/
readonly languageId: string | string[];
/**
* The version number of this document (it will increase after each
* change, including undo/redo).
*/
readonly version: number;
/**
* the raw Document Text
*/
readonly text: string;
/**
* The natural language locale.
*/
readonly locale?: string | undefined;
positionAt(offset: number): Position;
offsetAt(position: Position): number;
lineAt(offset: number): TextDocumentLine;
}
interface CreateTextDocumentParams {
uri: DocumentUri | string;
content: string;
languageId?: string | string[] | undefined;
locale?: string | undefined;
version?: number | undefined;
}
declare function createTextDocument({ uri, content, languageId, locale, version, }: CreateTextDocumentParams): TextDocument;

/**
* Handles loading of `.pnp.js` and `.pnp.js` files.
*/
Expand Down Expand Up @@ -490,6 +541,48 @@ declare enum IncludeExcludeFlag {
}
declare function checkText(text: string, settings: CSpellUserSettings): Promise<CheckTextInfo>;

interface DocumentValidatorOptions extends ValidateTextOptions {
/**
* Optional path to a configuration file.
* If given, it will be used instead of searching for a configuration file.
*/
configFile?: string;
/**
* Prevents searching for local configuration files
* By default the spell checker looks for configuration files
* starting at the location of given filename.
* If `configFile` is defined it will still be loaded instead of searching.
* `false` will override the value in `settings.noConfigSearch`.
* @defaultValue undefined
*/
noConfigSearch?: boolean;
}
declare class DocumentValidator {
readonly options: DocumentValidatorOptions;
readonly settings: CSpellUserSettings;
private _document;
private _ready;
readonly errors: Error[];
private _prepared;
private _preparations;
/**
* @param doc - Document to validate
* @param config - configuration to use (not finalized).
*/
constructor(doc: TextDocument, options: DocumentValidatorOptions, settings: CSpellUserSettings);
get ready(): boolean;
prepareSync(): void;
prepare(): Promise<void>;
private _prepareAsync;
checkText(range: SimpleRange, _text: string, _scope: string[]): ValidationIssue[];
get document(): TextDocument;
private addPossibleError;
private catchError;
private errorCatcherWrapper;
}
declare type Offset = number;
declare type SimpleRange = readonly [Offset, Offset];

interface SpellCheckFileOptions extends ValidateTextOptions {
/**
* Optional path to a configuration file.
Expand Down Expand Up @@ -566,27 +659,6 @@ declare function fileToDocument(file: string): Document;
declare function fileToDocument(file: string, text: string, languageId?: string, locale?: string): DocumentWithText;
declare function fileToDocument(file: string, text?: string, languageId?: string, locale?: string): Document | DocumentWithText;

interface TraceResult {
word: string;
found: boolean;
foundWord: string | undefined;
forbidden: boolean;
noSuggest: boolean;
dictName: string;
dictSource: string;
dictActive: boolean;
configSource: string;
errors: Error[] | undefined;
}
interface TraceOptions {
languageId?: LanguageId | LanguageId[];
locale?: LocaleId;
ignoreCase?: boolean;
allowCompoundWords?: boolean;
}
declare function traceWords(words: string[], settings: CSpellSettings, options: TraceOptions | undefined): Promise<TraceResult[]>;
declare function traceWordsAsync(words: Iterable<string> | AsyncIterable<string>, settings: CSpellSettings, options: TraceOptions | undefined): AsyncIterableIterator<TraceResult[]>;

interface SuggestedWordBase extends SuggestionResult {
dictionaries: string[];
}
Expand Down Expand Up @@ -646,6 +718,27 @@ declare class SuggestionError extends Error {
constructor(message: string, code: string);
}

interface TraceResult {
word: string;
found: boolean;
foundWord: string | undefined;
forbidden: boolean;
noSuggest: boolean;
dictName: string;
dictSource: string;
dictActive: boolean;
configSource: string;
errors: Error[] | undefined;
}
interface TraceOptions {
languageId?: LanguageId | LanguageId[];
locale?: LocaleId;
ignoreCase?: boolean;
allowCompoundWords?: boolean;
}
declare function traceWords(words: string[], settings: CSpellSettings, options: TraceOptions | undefined): Promise<TraceResult[]>;
declare function traceWordsAsync(words: Iterable<string> | AsyncIterable<string>, settings: CSpellSettings, options: TraceOptions | undefined): AsyncIterableIterator<TraceResult[]>;

declare type Console = typeof console;
interface Logger {
log: Console['log'];
Expand Down Expand Up @@ -680,4 +773,4 @@ declare function resolveFile(filename: string, relativeTo: string): ResolveFileR
declare function clearCachedFiles(): Promise<void>;
declare function getDictionary(settings: CSpellUserSettings): Promise<SpellingDictionaryCollection>;

export { CheckTextInfo, ConfigurationDependencies, DetermineFinalDocumentSettingsResult, Document, ENV_CSPELL_GLOB_ROOT, ExcludeFilesGlobMap, ExclusionFunction, exclusionHelper_d as ExclusionHelper, ImportError, ImportFileRefWithError, IncludeExcludeFlag, IncludeExcludeOptions, index_link_d as Link, Logger, SpellCheckFileOptions, SpellCheckFileResult, SpellingDictionary, SpellingDictionaryCollection, SpellingDictionaryLoadError, SuggestOptions, SuggestedWord, SuggestionError, SuggestionOptions, SuggestionsForWordResult, text_d as Text, TextInfoItem, TraceOptions, TraceResult, ValidationIssue, calcOverrideSettings, checkFilenameMatchesGlob, checkText, clearCachedFiles, clearCachedSettingsFiles, combineTextAndLanguageSettings, combineTextAndLanguageSettings as constructSettingsForText, createSpellingDictionary, currentSettingsFileVersion, defaultConfigFilenames, defaultFileName, defaultFileName as defaultSettingsFilename, determineFinalDocumentSettings, extractDependencies, extractImportErrors, fileToDocument, finalizeSettings, getCachedFileSize, getDefaultSettings, getDictionary, getGlobalSettings, getLanguagesForExt, getLogger, getSources, isBinaryFile, isSpellingDictionaryLoadError, loadConfig, loadPnP, loadPnPSync, mergeInDocSettings, mergeSettings, readRawSettings, readSettings, readSettingsFiles, refreshDictionaryCache, resolveFile, searchForConfig, sectionCSpell, setLogger, spellCheckDocument, spellCheckFile, suggestionsForWord, suggestionsForWords, traceWords, traceWordsAsync, validateText };
export { CheckTextInfo, ConfigurationDependencies, CreateTextDocumentParams, DetermineFinalDocumentSettingsResult, Document, DocumentValidator, DocumentValidatorOptions, ENV_CSPELL_GLOB_ROOT, ExcludeFilesGlobMap, ExclusionFunction, exclusionHelper_d as ExclusionHelper, ImportError, ImportFileRefWithError, IncludeExcludeFlag, IncludeExcludeOptions, index_link_d as Link, Logger, SpellCheckFileOptions, SpellCheckFileResult, SpellingDictionary, SpellingDictionaryCollection, SpellingDictionaryLoadError, SuggestOptions, SuggestedWord, SuggestionError, SuggestionOptions, SuggestionsForWordResult, text_d as Text, TextDocument, TextDocumentLine, TextInfoItem, TraceOptions, TraceResult, ValidationIssue, calcOverrideSettings, checkFilenameMatchesGlob, checkText, clearCachedFiles, clearCachedSettingsFiles, combineTextAndLanguageSettings, combineTextAndLanguageSettings as constructSettingsForText, createSpellingDictionary, createTextDocument, currentSettingsFileVersion, defaultConfigFilenames, defaultFileName, defaultFileName as defaultSettingsFilename, determineFinalDocumentSettings, extractDependencies, extractImportErrors, fileToDocument, finalizeSettings, getCachedFileSize, getDefaultSettings, getDictionary, getGlobalSettings, getLanguagesForExt, getLogger, getSources, isBinaryFile, isSpellingDictionaryLoadError, loadConfig, loadPnP, loadPnPSync, mergeInDocSettings, mergeSettings, readRawSettings, readSettings, readSettingsFiles, refreshDictionaryCache, resolveFile, searchForConfig, sectionCSpell, setLogger, spellCheckDocument, spellCheckFile, suggestionsForWord, suggestionsForWords, traceWords, traceWordsAsync, validateText };
2 changes: 1 addition & 1 deletion packages/cspell-lib/src/Models/TextDocument.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Uri } from './Uri';
describe('TextDocument', () => {
test('create', () => {
const content = '/** this is some code */';
const doc = createTextDocument(__filename, content);
const doc = createTextDocument({ uri: __filename, content });
expect(doc.text).toBe(content);
expect(doc.languageId).toContain('typescript');
expect(doc.uri).toBeInstanceOf(Uri);
Expand Down
22 changes: 15 additions & 7 deletions packages/cspell-lib/src/Models/TextDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,21 @@ class TextDocumentImpl implements TextDocument {
}
}

export function createTextDocument(
uri: DocumentUri | string,
content: string,
languageId?: string | string[],
locale?: string,
version?: number
): TextDocument {
export interface CreateTextDocumentParams {
uri: DocumentUri | string;
content: string;
languageId?: string | string[] | undefined;
locale?: string | undefined;
version?: number | undefined;
}

export function createTextDocument({
uri,
content,
languageId,
locale,
version,
}: CreateTextDocumentParams): TextDocument {
version = version ?? 1;
uri = Uri.toUri(uri);
languageId = languageId ?? getLanguagesForBasename(Uri.basename(uri));
Expand Down
2 changes: 2 additions & 0 deletions packages/cspell-lib/src/__snapshots__/index.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ Object {
"userWords": "userWords",
"words": "words",
},
"DocumentValidator": [Function],
"ENV_CSPELL_GLOB_ROOT": "CSPELL_GLOB_ROOT",
"ExclusionHelper": Object {
"extractGlobsFromExcludeFilesGlobMap": [Function],
Expand Down Expand Up @@ -122,6 +123,7 @@ Object {
"combineTextAndLanguageSettings": [Function],
"constructSettingsForText": [Function],
"createSpellingDictionary": [Function],
"createTextDocument": [Function],
"currentSettingsFileVersion": "0.2",
"defaultConfigFilenames": Array [
"package.json",
Expand Down
13 changes: 8 additions & 5 deletions packages/cspell-lib/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { CSpellUserSettings } from '@cspell/cspell-types';
import * as ExclusionHelper from './exclusionHelper';
import { clearCachedSettingsFiles } from './Settings';
import { CSpellUserSettings } from '@cspell/cspell-types';
import { toInternalSettings } from './Settings/CSpellSettingsServer';
import * as Link from './Settings/index.link';
import { refreshDictionaryCache, getDictionaryInternal, SpellingDictionaryCollection } from './SpellingDictionary';
import { getDictionaryInternal, refreshDictionaryCache, SpellingDictionaryCollection } from './SpellingDictionary';
import * as Text from './util/text';

export * from '@cspell/cspell-types';
export * from 'cspell-io';
export { ExcludeFilesGlobMap, ExclusionFunction } from './exclusionHelper';
export { getLanguagesForExt } from './LanguageIds';
export { createTextDocument } from './Models/TextDocument';
export type { CreateTextDocumentParams, TextDocument, TextDocumentLine } from './Models/TextDocument';
export * from './Settings';
export * from '@cspell/cspell-types';
export { defaultFileName as defaultSettingsFilename } from './Settings';
export {
combineTextAndLanguageSettings,
Expand Down Expand Up @@ -39,10 +41,11 @@ export {
SuggestionResult,
SuggestOptions,
} from './SpellingDictionary';
export { SuggestionError, suggestionsForWord, suggestionsForWords } from './suggestions';
export type { SuggestedWord, SuggestionOptions, SuggestionsForWordResult } from './suggestions';
export { DocumentValidator, DocumentValidatorOptions } from './textValidation';
export { traceWords, traceWordsAsync } from './trace';
export type { TraceOptions, TraceResult } from './trace';
export { suggestionsForWord, suggestionsForWords, SuggestionError } from './suggestions';
export type { SuggestedWord, SuggestionOptions, SuggestionsForWordResult } from './suggestions';
export { getLogger, Logger, setLogger } from './util/logger';
export { resolveFile } from './util/resolveFile';
export {
Expand Down
7 changes: 6 additions & 1 deletion packages/cspell-lib/src/spellCheckFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,12 @@ export function determineFinalDocumentSettings(
document: DocumentWithText,
settings: CSpellUserSettings
): DetermineFinalDocumentSettingsResult {
const doc = createTextDocument(document.uri, document.text, document.languageId, document.locale);
const doc = createTextDocument({
uri: document.uri,
content: document.text,
languageId: document.languageId,
locale: document.locale,
});
return {
document,
settings: determineTextDocumentSettings(doc, settings),
Expand Down
4 changes: 2 additions & 2 deletions packages/cspell-lib/src/textValidation/docValidator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,13 @@ describe('docValidator', () => {
});

function td(uri: string, content: string, languageId?: string, locale?: string, version = 1): TextDocument {
return createTextDocument(uri, content, languageId, locale, version);
return createTextDocument({ uri, content, languageId, locale, version });
}

async function _loadDoc(filename: string): Promise<TextDocument> {
const content = await fs.readFile(filename, 'utf8');

return createTextDocument(filename, content);
return createTextDocument({ uri: filename, content });
}

function loadDoc(filename: string) {
Expand Down
2 changes: 1 addition & 1 deletion packages/cspell-lib/src/textValidation/docValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export class DocumentValidator {
// Determine doc settings.
// Calc include ranges
// Load dictionaries
assert(!this._ready);
if (this._ready) return;

const { options, settings } = this;

Expand Down
2 changes: 2 additions & 0 deletions packages/cspell-lib/src/textValidation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ export { calcTextInclusionRanges } from './textValidator';
export type { CheckOptions, IncludeExcludeOptions, ValidationOptions, ValidationResult } from './textValidator';
export { checkText, IncludeExcludeFlag, validateText } from './validator';
export type { CheckTextInfo, TextInfoItem, ValidateTextOptions, ValidationIssue } from './validator';
export { DocumentValidator } from './docValidator';
export type { DocumentValidatorOptions } from './docValidator';

0 comments on commit faf6197

Please sign in to comment.