Rename private properties.

This commit is contained in:
CismonX 2021-05-25 12:16:56 +08:00
parent 0651e8187d
commit 1dbafb6c97
Signed by: cismonx
GPG Key ID: 3094873E29A482FB
14 changed files with 213 additions and 213 deletions

View File

@ -36,31 +36,31 @@ export default class ContextMapping implements vscode.Disposable {
* @returns * @returns
*/ */
getDocumentContext(document: vscode.TextDocument) { getDocumentContext(document: vscode.TextDocument) {
let documentContext = this.map.get(document); let documentContext = this._map.get(document);
if (documentContext === undefined) { if (documentContext === undefined) {
documentContext = new DocumentContext(this.globalContext, document); documentContext = new DocumentContext(this._globalContext, document);
this.map.set(document, documentContext); this._map.set(document, documentContext);
} }
return documentContext; return documentContext;
} }
dispose() { dispose() {
this.map.forEach(documentContext => documentContext.getPreview()?.close()); this._map.forEach(documentContext => documentContext.getPreview()?.close());
} }
constructor(private readonly globalContext: GlobalContext) { constructor(private readonly _globalContext: GlobalContext) {
globalContext.subscribe( _globalContext.subscribe(
vscode.commands.registerTextEditorCommand('texinfo.preview.show', this.showPreview.bind(this)), vscode.commands.registerTextEditorCommand('texinfo.preview.show', this._showPreview.bind(this)),
vscode.commands.registerCommand('texinfo.preview.goto', this.gotoPreview.bind(this)), vscode.commands.registerCommand('texinfo.preview.goto', this._gotoPreview.bind(this)),
vscode.workspace.onDidChangeTextDocument(this.onDocumentUpdate.bind(this)), vscode.workspace.onDidChangeTextDocument(this._onDocumentUpdate.bind(this)),
vscode.workspace.onDidCloseTextDocument(this.onDocumentClose.bind(this)), vscode.workspace.onDidCloseTextDocument(this._onDocumentClose.bind(this)),
vscode.workspace.onDidSaveTextDocument(this.onDocumentSave.bind(this)), vscode.workspace.onDidSaveTextDocument(this._onDocumentSave.bind(this)),
); );
} }
private readonly map = new Map<vscode.TextDocument, DocumentContext>(); private readonly _map = new Map<vscode.TextDocument, DocumentContext>();
private tryGetDocumentContext(document: vscode.TextDocument) { private _tryGetDocumentContext(document: vscode.TextDocument) {
return document.languageId === 'texinfo' ? this.getDocumentContext(document) : undefined; return document.languageId === 'texinfo' ? this.getDocumentContext(document) : undefined;
} }
@ -70,24 +70,24 @@ export default class ContextMapping implements vscode.Disposable {
* @param document * @param document
* @param nodeName * @param nodeName
*/ */
private gotoPreview(document: vscode.TextDocument, nodeName: string) { private _gotoPreview(document: vscode.TextDocument, nodeName: string) {
this.getDocumentContext(document).initPreview().goto(nodeName); this.getDocumentContext(document).initPreview().goto(nodeName);
} }
private onDocumentClose(document: vscode.TextDocument) { private _onDocumentClose(document: vscode.TextDocument) {
this.map.get(document)?.getPreview()?.close(); this._map.get(document)?.getPreview()?.close();
this.map.delete(document); this._map.delete(document);
} }
private onDocumentSave(document: vscode.TextDocument) { private _onDocumentSave(document: vscode.TextDocument) {
const documentContext = this.tryGetDocumentContext(document); const documentContext = this._tryGetDocumentContext(document);
if (documentContext === undefined) return; if (documentContext === undefined) return;
documentContext.foldingRange.clear(); documentContext.foldingRange.clear();
documentContext.getPreview()?.updateWebview(); documentContext.getPreview()?.updateWebview();
} }
private onDocumentUpdate(event: vscode.TextDocumentChangeEvent) { private _onDocumentUpdate(event: vscode.TextDocumentChangeEvent) {
const documentContext = this.tryGetDocumentContext(event.document); const documentContext = this._tryGetDocumentContext(event.document);
if (documentContext?.foldingRange.update(event.contentChanges)) { if (documentContext?.foldingRange.update(event.contentChanges)) {
documentContext.documentSymbol.clear(); documentContext.documentSymbol.clear();
} }
@ -98,7 +98,7 @@ export default class ContextMapping implements vscode.Disposable {
* *
* @param editor The editor where the document is being held. * @param editor The editor where the document is being held.
*/ */
private async showPreview(editor: vscode.TextEditor) { private async _showPreview(editor: vscode.TextEditor) {
const document = editor.document; const document = editor.document;
// Only show preview for saved files, as we're not gonna send document content to `makeinfo` via STDIN. // Only show preview for saved files, as we're not gonna send document content to `makeinfo` via STDIN.
// Instead, the file will be loaded from disk. // Instead, the file will be loaded from disk.

View File

@ -35,18 +35,18 @@ export default class DocumentContext {
readonly documentSymbol = new DocumentSymbolContext(this); readonly documentSymbol = new DocumentSymbolContext(this);
initPreview() { initPreview() {
return this.preview ??= new PreviewContext(this); return this._preview ??= new PreviewContext(this);
} }
getPreview() { getPreview() {
return this.preview; return this._preview;
} }
closePreview() { closePreview() {
this.preview = undefined; this._preview = undefined;
} }
constructor(readonly globalContext: GlobalContext, readonly document: vscode.TextDocument) {} constructor(readonly globalContext: GlobalContext, readonly document: vscode.TextDocument) {}
private preview?: PreviewContext; private _preview?: PreviewContext;
} }

View File

@ -30,25 +30,25 @@ import { FoldingRange, Optional } from '../utils/types';
export default class DocumentSymbolContext { export default class DocumentSymbolContext {
get documentSymbols() { get documentSymbols() {
return this._documentSymbols ??= this.calculcateDocumentSymbols(); return this._documentSymbols ??= this._calculcateDocumentSymbols();
} }
clear() { clear() {
this._documentSymbols = undefined; this._documentSymbols = undefined;
} }
constructor(private readonly documentContext: DocumentContext) {} constructor(private readonly _documentContext: DocumentContext) {}
private _documentSymbols?: vscode.DocumentSymbol[]; private _documentSymbols?: vscode.DocumentSymbol[];
private readonly document = this.documentContext.document; private readonly _document = this._documentContext.document;
/** /**
* Calculate document symbols based on folding ranges. * Calculate document symbols based on folding ranges.
*/ */
private calculcateDocumentSymbols() { private _calculcateDocumentSymbols() {
const ranges = Array<Optional<FoldingRange>>(this.document.lineCount); const ranges = Array<Optional<FoldingRange>>(this._document.lineCount);
this.documentContext.foldingRange.foldingRanges this._documentContext.foldingRange.foldingRanges
.filter(range => range.kind === undefined) .filter(range => range.kind === undefined)
.forEach(range => ranges[range.start] = range); .forEach(range => ranges[range.start] = range);
return foldingRangeToSymbols(ranges, 0, ranges.length); return foldingRangeToSymbols(ranges, 0, ranges.length);

View File

@ -36,15 +36,15 @@ export default class FoldingRangeContext {
* Get VSCode folding ranges from the context. * Get VSCode folding ranges from the context.
*/ */
get foldingRanges() { get foldingRanges() {
return this._foldingRanges ?? this.calculateFoldingRanges(); return this._foldingRanges ?? this._calculateFoldingRanges();
} }
/** /**
* Get node values of document as VSCode code lenses. * Get node values of document as VSCode code lenses.
*/ */
get nodeValues() { get nodeValues() {
this._foldingRanges ?? this.calculateFoldingRanges(); this._foldingRanges ?? this._calculateFoldingRanges();
return this.nodes; return this._nodes;
} }
/** /**
@ -53,14 +53,14 @@ export default class FoldingRangeContext {
* @param events Events describing the changes in the document. * @param events Events describing the changes in the document.
*/ */
update(events: readonly vscode.TextDocumentContentChangeEvent[]) { update(events: readonly vscode.TextDocumentContentChangeEvent[]) {
this.contentMayChange = true; this._contentMayChange = true;
if (this._foldingRanges === undefined) return false; if (this._foldingRanges === undefined) return false;
const eol = this.document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n'; const eol = this._document.eol === vscode.EndOfLine.LF ? '\n' : '\r\n';
for (const event of events) { for (const event of events) {
// Clear cached folding range when line count changes. // Clear cached folding range when line count changes.
if (event.text.split(eol).length !== 1 || event.range.start.line !== event.range.end.line) { if (event.text.split(eol).length !== 1 || event.range.start.line !== event.range.end.line) {
this._foldingRanges = undefined; this._foldingRanges = undefined;
this.nodes = []; this._nodes = [];
return true; return true;
} }
} }
@ -68,34 +68,34 @@ export default class FoldingRangeContext {
} }
clear() { clear() {
if (this.contentMayChange) { if (this._contentMayChange) {
this._foldingRanges = undefined; this._foldingRanges = undefined;
} }
} }
constructor(private readonly documentContext: DocumentContext) {} constructor(private readonly _documentContext: DocumentContext) {}
private readonly document = this.documentContext.document; private readonly _document = this._documentContext.document;
/** /**
* Regex for matching subsection/section/chapter (-like) commands. * Regex for matching subsection/section/chapter (-like) commands.
*/ */
private static readonly nodeFormat = RegExp('^@(?:(node)|(subsection|unnumberedsubsec|appendixsubsec|subheading)|' + private static readonly _nodeFormat = RegExp('^@(?:(node)|(subsection|unnumberedsubsec|appendixsubsec|subheading)' +
'(section|unnumberedsec|appendixsec|heading)|(chapter|unnumbered|appendix|majorheading|chapheading)) (.*)$'); '|(section|unnumberedsec|appendixsec|heading)|(chapter|unnumbered|appendix|majorheading|chapheading)) (.*)$');
private _foldingRanges?: FoldingRange[]; private _foldingRanges?: FoldingRange[];
private nodes = <vscode.CodeLens[]>[]; private _nodes = <vscode.CodeLens[]>[];
private commentRange?: Range; private _commentRange?: Range;
private headerStart?: number; private _headerStart?: number;
private closingChapter?: number; private _closingChapter?: number;
private closingSection?: number; private _closingSection?: number;
private closingSubsection?: number; private _closingSubsection?: number;
private contentMayChange = true; private _contentMayChange = true;
private addRange(start: number, end: number, extraArgs: { private _addRange(start: number, end: number, extraArgs: {
name?: string, name?: string,
detail?: string, detail?: string,
kind?: vscode.FoldingRangeKind kind?: vscode.FoldingRangeKind
@ -110,15 +110,15 @@ export default class FoldingRangeContext {
* @param start Starting line number. * @param start Starting line number.
* @param end Ending line number. * @param end Ending line number.
*/ */
private calculateFoldingRanges() { private _calculateFoldingRanges() {
this.contentMayChange = false; this._contentMayChange = false;
this._foldingRanges = []; this._foldingRanges = [];
this.clearTemporaries(); this._clearTemporaries();
let closingBlocks = <NamedLine[]>[]; let closingBlocks = <NamedLine[]>[];
let lastLine = this.document.lineCount - 1; let lastLine = this._document.lineCount - 1;
let verbatim = false; let verbatim = false;
for (let idx = lastLine; idx >= 0; --idx) { for (let idx = lastLine; idx >= 0; --idx) {
const line = this.document.lineAt(idx).text.trimLeft(); const line = this._document.lineAt(idx).text.trimLeft();
if (!line.startsWith('@')) continue; if (!line.startsWith('@')) continue;
if (!verbatim) { if (!verbatim) {
if (line === '@bye') { if (line === '@bye') {
@ -126,10 +126,10 @@ export default class FoldingRangeContext {
// Abort anything after `@bye`. // Abort anything after `@bye`.
this._foldingRanges = []; this._foldingRanges = [];
closingBlocks = []; closingBlocks = [];
this.clearTemporaries(); this._clearTemporaries();
continue; continue;
} }
if (this.processComment(line, idx)) continue; if (this._processComment(line, idx)) continue;
} }
// Process block. // Process block.
if (line.startsWith('@end ')) { if (line.startsWith('@end ')) {
@ -141,93 +141,93 @@ export default class FoldingRangeContext {
closingBlocks.push({ name: name, line: idx }); closingBlocks.push({ name: name, line: idx });
continue; continue;
} }
if (!verbatim && this.processNode(line, idx, lastLine)) continue; if (!verbatim && this._processNode(line, idx, lastLine)) continue;
const closingBlock = closingBlocks.pop(); const closingBlock = closingBlocks.pop();
if (closingBlock === undefined) continue; if (closingBlock === undefined) continue;
if (line.substring(1, closingBlock.name.length + 2).trim() === closingBlock.name) { if (line.substring(1, closingBlock.name.length + 2).trim() === closingBlock.name) {
this.addRange(idx, closingBlock.line, { name: closingBlock.name }); this._addRange(idx, closingBlock.line, { name: closingBlock.name });
// If `verbatim == true` goes here, this line must be the `@verbatim` line. // If `verbatim == true` goes here, this line must be the `@verbatim` line.
verbatim = false; verbatim = false;
} else { } else {
closingBlocks.push(closingBlock); closingBlocks.push(closingBlock);
} }
} }
if (this.commentRange !== undefined) { if (this._commentRange !== undefined) {
this.addRange(this.commentRange.start, this.commentRange.end, { kind: vscode.FoldingRangeKind.Comment }); this._addRange(this._commentRange.start, this._commentRange.end, { kind: vscode.FoldingRangeKind.Comment });
} }
return this._foldingRanges; return this._foldingRanges;
} }
private clearTemporaries() { private _clearTemporaries() {
this.commentRange = undefined; this._commentRange = undefined;
this.headerStart = undefined; this._headerStart = undefined;
this.nodes = []; this._nodes = [];
this.closingSubsection = this.closingSection = this.closingChapter = undefined; this._closingSubsection = this._closingSection = this._closingChapter = undefined;
} }
private getLastTextLine(lineNum: number, limit = 3) { private _getLastTextLine(lineNum: number, limit = 3) {
for (let idx = lineNum; idx > lineNum - limit; --idx) { for (let idx = lineNum; idx > lineNum - limit; --idx) {
const line = this.document.lineAt(idx).text; const line = this._document.lineAt(idx).text;
if (line.startsWith('@node ')) return idx - 1; if (line.startsWith('@node ')) return idx - 1;
if (line === '') return idx; if (line === '') return idx;
} }
return lineNum; return lineNum;
} }
private processComment(lineText: string, lineNum: number) { private _processComment(lineText: string, lineNum: number) {
if (!lineText.startsWith('@c')) return false; if (!lineText.startsWith('@c')) return false;
if (!lineText.startsWith(' ', 2) && !lineText.startsWith('omment ', 2)) { if (!lineText.startsWith(' ', 2) && !lineText.startsWith('omment ', 2)) {
return false; return false;
} }
// Check for opening/closing header. // Check for opening/closing header.
if (lineText.startsWith('%**', lineText[2] === ' ' ? 3 : 9)) { if (lineText.startsWith('%**', lineText[2] === ' ' ? 3 : 9)) {
if (this.headerStart === undefined) { if (this._headerStart === undefined) {
this.headerStart = lineNum; this._headerStart = lineNum;
} else { } else {
this.addRange(lineNum, this.headerStart, { kind: vscode.FoldingRangeKind.Region }); this._addRange(lineNum, this._headerStart, { kind: vscode.FoldingRangeKind.Region });
this.headerStart = undefined; this._headerStart = undefined;
} }
return true; return true;
} }
if (this.commentRange === undefined) { if (this._commentRange === undefined) {
this.commentRange = { start: lineNum, end: lineNum }; this._commentRange = { start: lineNum, end: lineNum };
} else if (this.commentRange.start - 1 === lineNum) { } else if (this._commentRange.start - 1 === lineNum) {
this.commentRange.start = lineNum; this._commentRange.start = lineNum;
} else { } else {
this.addRange(this.commentRange.start, this.commentRange.end, { kind: vscode.FoldingRangeKind.Comment }); this._addRange(this._commentRange.start, this._commentRange.end, { kind: vscode.FoldingRangeKind.Comment });
this.commentRange = undefined; this._commentRange = undefined;
} }
return true; return true;
} }
private processNode(lineText: string, lineNum: number, lastLineNum: number) { private _processNode(lineText: string, lineNum: number, lastLineNum: number) {
const result = lineText.match(FoldingRangeContext.nodeFormat); const result = lineText.match(FoldingRangeContext._nodeFormat);
if (result === null) return false; if (result === null) return false;
// Node identifier. // Node identifier.
if (result[1] !== undefined) { if (result[1] !== undefined) {
this.nodes.push(new vscode.CodeLens(lineNumToRange(lineNum), { this._nodes.push(new vscode.CodeLens(lineNumToRange(lineNum), {
title: '$(go-to-file) Goto node in preview', title: '$(go-to-file) Goto node in preview',
command: 'texinfo.preview.goto', command: 'texinfo.preview.goto',
arguments: [this.document, result[5]], arguments: [this._document, result[5]],
})); }));
return true; return true;
} }
// Subsection level node. // Subsection level node.
if (result[2] !== undefined) { if (result[2] !== undefined) {
this.addRange(lineNum, this.closingSubsection ?? lastLineNum, { name: result[2], detail: result[5] }); this._addRange(lineNum, this._closingSubsection ?? lastLineNum, { name: result[2], detail: result[5] });
this.closingSubsection = this.getLastTextLine(lineNum - 1); this._closingSubsection = this._getLastTextLine(lineNum - 1);
return true; return true;
} }
// Section level node. // Section level node.
if (result[3] !== undefined) { if (result[3] !== undefined) {
this.addRange(lineNum, this.closingSection ?? lastLineNum, { name: result[3], detail: result[5] }); this._addRange(lineNum, this._closingSection ?? lastLineNum, { name: result[3], detail: result[5] });
this.closingSubsection = this.closingSection = this.getLastTextLine(lineNum - 1); this._closingSubsection = this._closingSection = this._getLastTextLine(lineNum - 1);
return true; return true;
} }
// Chapter level node. // Chapter level node.
if (result[4] !== undefined) { if (result[4] !== undefined) {
this.addRange(lineNum, this.closingChapter ?? lastLineNum, { name: result[4], detail: result[5] }); this._addRange(lineNum, this._closingChapter ?? lastLineNum, { name: result[4], detail: result[5] });
this.closingSubsection = this.closingSection = this.closingChapter = this.getLastTextLine(lineNum - 1); this._closingSubsection = this._closingSection = this._closingChapter = this._getLastTextLine(lineNum - 1);
return true; return true;
} }
return false; return false;

View File

@ -31,82 +31,82 @@ import { getNodeHtmlRef, prompt } from '../utils/misc';
export default class PreviewContext { export default class PreviewContext {
close() { close() {
this.disposables.forEach(event => event.dispose()); this._disposables.forEach(event => event.dispose());
this.panel.dispose(); this._panel.dispose();
this.documentContext.closePreview(); this._documentContext.closePreview();
// Only show diagnostic information when the preview is active. // Only show diagnostic information when the preview is active.
this.diagnosis.delete(this.document); this._diagnosis.delete(this._document);
} }
goto(nodeName: string) { goto(nodeName: string) {
this.panel.webview.postMessage({ command: 'goto', value: getNodeHtmlRef(nodeName) }); this._panel.webview.postMessage({ command: 'goto', value: getNodeHtmlRef(nodeName) });
} }
show() { show() {
this.panel.reveal(); this._panel.reveal();
} }
async updateWebview() { async updateWebview() {
if (this.updating) { if (this._updating) {
this.pendingUpdate = true; this._pendingUpdate = true;
return; return;
} }
this.updating = true; this._updating = true;
this.pendingUpdate = false; this._pendingUpdate = false;
// Inform the user that the preview is updating if `makeinfo` takes too long. // Inform the user that the preview is updating if `makeinfo` takes too long.
setTimeout(() => this.updating && this.updateTitle(), 500); setTimeout(() => this._updating && this._updateTitle(), 500);
const initFile = this.globalContext.extensionPath + '/ext/html-preview.pm'; const initFile = this._globalContext.extensionPath + '/ext/html-preview.pm';
const converter = new Converter(this.document.fileName, initFile, this.globalContext.options, this.logger); const converter = new Converter(this._document.fileName, initFile, this._globalContext.options, this._logger);
const { data, error } = await converter.toHTML(path => this.panel.webview.asWebviewUri(path), this.script); const { data, error } = await converter.toHTML(path => this._panel.webview.asWebviewUri(path), this._script);
if (error) { if (error) {
this.logger.log(error); this._logger.log(error);
this.diagnosis.update(this.document, error); this._diagnosis.update(this._document, error);
} else { } else {
this.diagnosis.delete(this.document); this._diagnosis.delete(this._document);
} }
if (data === undefined) { if (data === undefined) {
prompt(`Failed to show preview for ${this.document.fileName}.`, 'Show log', true) prompt(`Failed to show preview for ${this._document.fileName}.`, 'Show log', true)
.then(result => result && this.logger.show()); .then(result => result && this._logger.show());
} else { } else {
this.panel.webview.html = data; this._panel.webview.html = data;
} }
this.updating = false; this._updating = false;
this.updateTitle(); this._updateTitle();
this.pendingUpdate && this.updateWebview(); this._pendingUpdate && this.updateWebview();
} }
constructor(private readonly documentContext: DocumentContext) { constructor(private readonly _documentContext: DocumentContext) {
this.panel = vscode.window.createWebviewPanel('texinfo.preview', '', vscode.ViewColumn.Beside, this._panel = vscode.window.createWebviewPanel('texinfo.preview', '', vscode.ViewColumn.Beside,
{ enableFindWidget: true, retainContextWhenHidden: true, enableScripts: true }); { enableFindWidget: true, retainContextWhenHidden: true, enableScripts: true });
this.disposables.push(this.panel.onDidDispose(() => this.close())); this._disposables.push(this._panel.onDidDispose(() => this.close()));
this.updateTitle(); this._updateTitle();
this.updateWebview(); this.updateWebview();
} }
private readonly document = this.documentContext.document; private readonly _document = this._documentContext.document;
private readonly globalContext = this.documentContext.globalContext; private readonly _globalContext = this._documentContext.globalContext;
private readonly diagnosis = this.globalContext.diagnosis; private readonly _diagnosis = this._globalContext.diagnosis;
private readonly logger = this.globalContext.logger; private readonly _logger = this._globalContext.logger;
private readonly disposables = <vscode.Disposable[]>[]; private readonly _disposables = <vscode.Disposable[]>[];
private readonly panel: vscode.WebviewPanel; private readonly _panel: vscode.WebviewPanel;
/** /**
* Whether a preview update request is pending. * Whether a preview update request is pending.
*/ */
private pendingUpdate = false; private _pendingUpdate = false;
/** /**
* Whether the preview is updating. * Whether the preview is updating.
*/ */
private updating = false; private _updating = false;
/** /**
* Generate script used for jumping to the corresponding location of preview with code lens. * Generate script used for jumping to the corresponding location of preview with code lens.
*/ */
private get script() { private get _script() {
if (!this.globalContext.options.enableCodeLens) return undefined; if (!this._globalContext.options.enableCodeLens) return undefined;
return "window.addEventListener('message', event => {" + return "window.addEventListener('message', event => {" +
"const message = event.data;" + "const message = event.data;" +
"switch (message.command) {" + "switch (message.command) {" +
@ -119,9 +119,9 @@ export default class PreviewContext {
"})"; "})";
} }
private updateTitle() { private _updateTitle() {
const updating = this.updating ? '(Updating) ' : ''; const updating = this._updating ? '(Updating) ' : '';
const fileName = path.basename(this.document.fileName); const fileName = path.basename(this._document.fileName);
this.panel.title = `${updating}Preview ${fileName}`; this._panel.title = `${updating}Preview ${fileName}`;
} }
} }

View File

@ -34,7 +34,7 @@ export default class Diagnosis implements vscode.Disposable {
* @param document * @param document
*/ */
delete(document: vscode.TextDocument) { delete(document: vscode.TextDocument) {
this.diagnostics.delete(document.uri); this._diagnostics.delete(document.uri);
} }
/** /**
@ -49,14 +49,14 @@ export default class Diagnosis implements vscode.Disposable {
.filter(line => line.startsWith(fileName)) .filter(line => line.startsWith(fileName))
.map(line => logLineToDiagnostic(line.substring(fileName.length + 1))) .map(line => logLineToDiagnostic(line.substring(fileName.length + 1)))
.filter(isDefined); .filter(isDefined);
this.diagnostics.set(document.uri, diagnostics); this._diagnostics.set(document.uri, diagnostics);
} }
dispose() { dispose() {
this.diagnostics.dispose(); this._diagnostics.dispose();
} }
private readonly diagnostics = vscode.languages.createDiagnosticCollection('texinfo'); private readonly _diagnostics = vscode.languages.createDiagnosticCollection('texinfo');
} }
/** /**

View File

@ -33,27 +33,27 @@ export default class Indicator implements vscode.Disposable {
} }
dispose() { dispose() {
this.statusBarItem.dispose(); this._statusBarItem.dispose();
} }
constructor(private readonly globalContext: GlobalContext) { constructor(private readonly globalContext: GlobalContext) {
globalContext.subscribe( globalContext.subscribe(
vscode.commands.registerCommand('texinfo.indicator.click', this.click.bind(this)), vscode.commands.registerCommand('texinfo.indicator.click', this._click.bind(this)),
vscode.window.onDidChangeActiveTextEditor(this.refresh.bind(this)), vscode.window.onDidChangeActiveTextEditor(this._refresh.bind(this)),
); );
this.updateStatus().then(() => this.refresh(vscode.window.activeTextEditor)); this._updateStatus().then(() => this._refresh(vscode.window.activeTextEditor));
} }
private _canDisplayPreview = false; private _canDisplayPreview = false;
private readonly statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100); private readonly _statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
/** /**
* Calls when the status bar item is clicked. * Calls when the status bar item is clicked.
*/ */
private async click() { private async _click() {
await this.updateStatus(); await this._updateStatus();
this.refresh(vscode.window.activeTextEditor); this._refresh(vscode.window.activeTextEditor);
} }
/** /**
@ -61,18 +61,18 @@ export default class Indicator implements vscode.Disposable {
* *
* @param editor * @param editor
*/ */
private refresh(editor?: vscode.TextEditor) { private _refresh(editor?: vscode.TextEditor) {
if (editor?.document.languageId === 'texinfo') { if (editor?.document.languageId === 'texinfo') {
this.statusBarItem.show(); this._statusBarItem.show();
} else { } else {
this.statusBarItem.hide(); this._statusBarItem.hide();
} }
} }
/** /**
* Update the installation status of GNU Texinfo, by checking `makeinfo --version`. * Update the installation status of GNU Texinfo, by checking `makeinfo --version`.
*/ */
private async updateStatus() { private async _updateStatus() {
const options = this.globalContext.options; const options = this.globalContext.options;
const output = await exec(options.makeinfo, ['--version'], options.maxSize); const output = await exec(options.makeinfo, ['--version'], options.maxSize);
const result = output.data?.match(/\(GNU texinfo\) (.*)\n/); const result = output.data?.match(/\(GNU texinfo\) (.*)\n/);
@ -92,8 +92,8 @@ export default class Indicator implements vscode.Disposable {
tooltip = `GNU Texinfo (${options.makeinfo}) is not correctly installed or configured.`; tooltip = `GNU Texinfo (${options.makeinfo}) is not correctly installed or configured.`;
this._canDisplayPreview = false; this._canDisplayPreview = false;
} }
this.statusBarItem.command = 'texinfo.indicator.click'; this._statusBarItem.command = 'texinfo.indicator.click';
this.statusBarItem.text = `${icon} GNU Texinfo ${version}`; this._statusBarItem.text = `${icon} GNU Texinfo ${version}`;
this.statusBarItem.tooltip = tooltip; this._statusBarItem.tooltip = tooltip;
} }
} }

View File

@ -28,16 +28,16 @@ export default class Logger implements vscode.Disposable {
log(message: string) { log(message: string) {
const dateTime = new Date().toLocaleString(undefined, { hour12: false }); const dateTime = new Date().toLocaleString(undefined, { hour12: false });
this.outputChannel.appendLine(`[ ${dateTime} ]\n${message}`); this._outputChannel.appendLine(`[ ${dateTime} ]\n${message}`);
} }
show() { show() {
this.outputChannel.show(true); this._outputChannel.show(true);
} }
dispose() { dispose() {
this.outputChannel.dispose(); this._outputChannel.dispose();
} }
private readonly outputChannel = vscode.window.createOutputChannel('Texinfo'); private readonly _outputChannel = vscode.window.createOutputChannel('Texinfo');
} }

View File

@ -29,72 +29,72 @@ import * as vscode from 'vscode';
export default class Options { export default class Options {
get enableSnippets() { get enableSnippets() {
return this.getBoolean('completion.enableSnippets'); return this._getBoolean('completion.enableSnippets');
} }
get hideSnippetCommands() { get hideSnippetCommands() {
return this.getBoolean('completion.hideSnippetCommands'); return this._getBoolean('completion.hideSnippetCommands');
} }
get noWarnings() { get noWarnings() {
return this.getBoolean('diagnosis.noWarnings'); return this._getBoolean('diagnosis.noWarnings');
} }
get enableCodeLens() { get enableCodeLens() {
return this.getBoolean('enableCodeLens'); return this._getBoolean('enableCodeLens');
} }
get makeinfo() { get makeinfo() {
return this.getString('makeinfo'); return this._getString('makeinfo');
} }
get customCSS() { get customCSS() {
return this.getString('preview.customCSS'); return this._getString('preview.customCSS');
} }
get errorLimit() { get errorLimit() {
return this.getNumber('preview.errorLimit'); return this._getNumber('preview.errorLimit');
} }
get includePaths() { get includePaths() {
return this.getArray('preview.includePaths'); return this._getArray('preview.includePaths');
} }
get maxSize() { get maxSize() {
return this.getNumber('preview.maxSize') * 1024 * 1024; return this._getNumber('preview.maxSize') * 1024 * 1024;
} }
get noHeaders() { get noHeaders() {
return this.getBoolean('preview.noHeaders'); return this._getBoolean('preview.noHeaders');
} }
get noNumberSections() { get noNumberSections() {
return this.getBoolean('preview.noNumberSections'); return this._getBoolean('preview.noNumberSections');
} }
get noValidation() { get noValidation() {
return this.getBoolean('preview.noValidation'); return this._getBoolean('preview.noValidation');
} }
get variables() { get variables() {
return this.getArray('preview.variables'); return this._getArray('preview.variables');
} }
private readonly configuration = vscode.workspace.getConfiguration('texinfo'); private readonly _configuration = vscode.workspace.getConfiguration('texinfo');
private getArray(section: string): readonly string[] { private _getArray(section: string): readonly string[] {
return this.configuration.get(section, []); return this._configuration.get(section, []);
} }
private getBoolean(section: string) { private _getBoolean(section: string) {
return this.configuration.get(section, false); return this._configuration.get(section, false);
} }
private getNumber(section: string) { private _getNumber(section: string) {
return this.configuration.get(section, 0); return this._configuration.get(section, 0);
} }
private getString(section: string) { private _getString(section: string) {
return this.configuration.get(section, ''); return this._configuration.get(section, '');
} }
} }

View File

@ -28,10 +28,10 @@ import GlobalContext from '../global_context';
export default class CodeLensProvider implements vscode.CodeLensProvider { export default class CodeLensProvider implements vscode.CodeLensProvider {
provideCodeLenses(document: vscode.TextDocument) { provideCodeLenses(document: vscode.TextDocument) {
if (!this.globalContext.options.enableCodeLens) return undefined; if (!this._globalContext.options.enableCodeLens) return undefined;
if (!this.globalContext.indicator.canDisplayPreview) return undefined; if (!this._globalContext.indicator.canDisplayPreview) return undefined;
return this.globalContext.contextMapping.getDocumentContext(document).foldingRange.nodeValues; return this._globalContext.contextMapping.getDocumentContext(document).foldingRange.nodeValues;
} }
constructor(private readonly globalContext: GlobalContext) {} constructor(private readonly _globalContext: GlobalContext) {}
} }

View File

@ -39,9 +39,9 @@ export default class CompletionItemProvider implements vscode.CompletionItemProv
* which means that GFDL applies to lines 46-365 of this file, while the remainder * which means that GFDL applies to lines 46-365 of this file, while the remainder
* is under GPL like other source code files of the project. * is under GPL like other source code files of the project.
*/ */
private get completionItems() { private _getCompletionItems() {
const enableSnippets = this.oldOptions.enableSnippets; const enableSnippets = this._oldOptions.enableSnippets;
const hideSnippetCommands = this.oldOptions.hideSnippetCommands; const hideSnippetCommands = this._oldOptions.hideSnippetCommands;
return this._completionItems ??= [ return this._completionItems ??= [
command('ampchar', 'Insert an ampersand, "&"', { hasEmptyBrace: true }), command('ampchar', 'Insert an ampersand, "&"', { hasEmptyBrace: true }),
command('atchar', 'Insert an at sign, "@"', { hasEmptyBrace: true }), command('atchar', 'Insert an at sign, "@"', { hasEmptyBrace: true }),
@ -387,25 +387,25 @@ export default class CompletionItemProvider implements vscode.CompletionItemProv
if (document.getText(new vscode.Range(position.translate(0, -1), position)) !== '@') return undefined; if (document.getText(new vscode.Range(position.translate(0, -1), position)) !== '@') return undefined;
} }
// Check whether options has changed. // Check whether options has changed.
const newOptions = this.globalContext.options; const newOptions = this._globalContext.options;
if (this.oldOptions !== newOptions) { if (this._oldOptions !== newOptions) {
this.oldOptions = newOptions; this._oldOptions = newOptions;
this._completionItems = undefined; this._completionItems = undefined;
} }
if (position.character === 1) return this.completionItems; if (position.character === 1) return this._getCompletionItems();
// Check whether the '@' character is escaped. // Check whether the '@' character is escaped.
if (document.getText(new vscode.Range(position.translate(0, -2), position.translate(0, -1))) === '@') { if (document.getText(new vscode.Range(position.translate(0, -2), position.translate(0, -1))) === '@') {
return undefined; return undefined;
} else { } else {
return this.completionItems; return this._getCompletionItems();
} }
} }
constructor(private readonly globalContext: GlobalContext) {} constructor(private readonly _globalContext: GlobalContext) {}
private _completionItems?: CompletionItem[]; private _completionItems?: CompletionItem[];
private oldOptions = this.globalContext.options; private _oldOptions = this._globalContext.options;
} }
/** /**

View File

@ -28,8 +28,8 @@ import GlobalContext from '../global_context';
export default class DocumentSymbolProvider implements vscode.DocumentSymbolProvider { export default class DocumentSymbolProvider implements vscode.DocumentSymbolProvider {
provideDocumentSymbols(document: vscode.TextDocument) { provideDocumentSymbols(document: vscode.TextDocument) {
return this.globalContext.contextMapping.getDocumentContext(document).documentSymbol.documentSymbols; return this._globalContext.contextMapping.getDocumentContext(document).documentSymbol.documentSymbols;
} }
constructor(private readonly globalContext: GlobalContext) {} constructor(private readonly _globalContext: GlobalContext) {}
} }

View File

@ -28,8 +28,8 @@ import GlobalContext from '../global_context';
export default class FoldingRangeProvider implements vscode.FoldingRangeProvider { export default class FoldingRangeProvider implements vscode.FoldingRangeProvider {
provideFoldingRanges(document: vscode.TextDocument) { provideFoldingRanges(document: vscode.TextDocument) {
return this.globalContext.contextMapping.getDocumentContext(document).foldingRange.foldingRanges; return this._globalContext.contextMapping.getDocumentContext(document).foldingRange.foldingRanges;
} }
constructor(private readonly globalContext: GlobalContext) {} constructor(private readonly _globalContext: GlobalContext) {}
} }

View File

@ -32,37 +32,37 @@ import { Operator } from './types';
export default class Converter { export default class Converter {
async toHTML(imgTransformer: Operator<vscode.Uri>, insertScript?: string) { async toHTML(imgTransformer: Operator<vscode.Uri>, insertScript?: string) {
const newPath = imgTransformer(vscode.Uri.file(path.dirname(this.path))).toString() + '/'; const newPath = imgTransformer(vscode.Uri.file(path.dirname(this._path))).toString() + '/';
const options = ['-o-', '--no-split', '--html', `--error-limit=${this.options.errorLimit}`, const options = ['-o-', '--no-split', '--html', `--error-limit=${this._options.errorLimit}`,
`--init-file=${this.initFile}`, '-D', `__vscode_texinfo_image_uri_base ${newPath}`]; `--init-file=${this._initFile}`, '-D', `__vscode_texinfo_image_uri_base ${newPath}`];
this.options.noHeaders && options.push('--no-headers'); this._options.noHeaders && options.push('--no-headers');
this.options.noNumberSections && options.push('--no-number-sections'); this._options.noNumberSections && options.push('--no-number-sections');
this.options.noValidation && options.push('--no-validate'); this._options.noValidation && options.push('--no-validate');
this.options.noWarnings && options.push('--no-warn'); this._options.noWarnings && options.push('--no-warn');
insertScript !== undefined && options.push('-c', `EXTRA_HEAD <script>${insertScript}</script>`); insertScript !== undefined && options.push('-c', `EXTRA_HEAD <script>${insertScript}</script>`);
this.addIncludePaths(this.options.includePaths, options); this._addIncludePaths(this._options.includePaths, options);
this.defineVariables(this.options.variables, options); this._defineVariables(this._options.variables, options);
this.includeCustomCSS(this.options.customCSS, options); this._includeCustomCSS(this._options.customCSS, options);
return await exec(this.options.makeinfo, options.concat(this.path), this.options.maxSize); return await exec(this._options.makeinfo, options.concat(this._path), this._options.maxSize);
} }
constructor( constructor(
private readonly path: string, private readonly _path: string,
private readonly initFile: string, private readonly _initFile: string,
private readonly options: Options, private readonly _options: Options,
private readonly logger: Logger, private readonly _logger: Logger,
) {} ) {}
private addIncludePaths(paths: readonly string[], options: string[]) { private _addIncludePaths(paths: readonly string[], options: string[]) {
const separator = process.platform === 'win32' ? ';' : ':'; const separator = process.platform === 'win32' ? ';' : ':';
options.push('-I', paths.join(separator)); options.push('-I', paths.join(separator));
} }
private defineVariables(variables: readonly string[], options: string[]) { private _defineVariables(variables: readonly string[], options: string[]) {
variables.forEach(varName => options.push('-D', varName)); variables.forEach(varName => options.push('-D', varName));
} }
private includeCustomCSS(cssFileURI: string, options: string[]) { private _includeCustomCSS(cssFileURI: string, options: string[]) {
if (!cssFileURI) return; if (!cssFileURI) return;
try { try {
const uri = vscode.Uri.parse(cssFileURI, true); const uri = vscode.Uri.parse(cssFileURI, true);
@ -78,7 +78,7 @@ export default class Converter {
throw URIError; throw URIError;
} }
} catch (e) { } catch (e) {
this.logger.log(`Cannot load custom CSS. Invalid URI: '${cssFileURI}'`); this._logger.log(`Cannot load custom CSS. Invalid URI: '${cssFileURI}'`);
} }
} }
} }