Skip to content

Commit

Permalink
Regularize onDidChangeConfiguration API
Browse files Browse the repository at this point in the history
  • Loading branch information
James-Yu committed Nov 26, 2023
1 parent 85f3b1b commit a918f83
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 101 deletions.
13 changes: 4 additions & 9 deletions src/completion/bibtex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,10 @@ export class BibtexCompleter implements vscode.CompletionItemProvider {
}
this.bibtexFormatConfig = getBibtexFormatConfig(this.scope)
this.initialize()
vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (e.affectsConfiguration('latex-workshop.bibtex-format', this.scope) ||
e.affectsConfiguration('latex-workshop.bibtex-entries', this.scope) ||
e.affectsConfiguration('latex-workshop.bibtex-fields', this.scope) ||
e.affectsConfiguration('latex-workshop.intellisense', this.scope)) {
this.bibtexFormatConfig = getBibtexFormatConfig(this.scope)
this.initialize()
}
})
lw.onConfigChange(['bibtex-format', 'bibtex-entries', 'bibtex-fields', 'intellisense'], () => {
this.bibtexFormatConfig = getBibtexFormatConfig(this.scope)
this.initialize()
}, this.scope)
vscode.window.onDidChangeActiveTextEditor((e: vscode.TextEditor | undefined) => {
if (e && lw.file.hasBibLangId(e.document.languageId)) {
const wsFolder = vscode.workspace.getWorkspaceFolder(e.document.uri)
Expand Down
10 changes: 4 additions & 6 deletions src/completion/completer/atsuggestion.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as vscode from 'vscode'
import * as fs from 'fs'
import { lw, registerDisposable } from '../../lw'
import { lw } from '../../lw'
import type {IProvider, IProviderArgs} from '../latex'
import {escapeRegExp} from '../../utils/utils'

Expand All @@ -23,11 +23,9 @@ export class AtSuggestion implements IProvider {

const allSuggestions: {[key: string]: AtSuggestionItemEntry} = JSON.parse(fs.readFileSync(`${lw.extensionRoot}/data/at-suggestions.json`).toString()) as DataAtSuggestionJsonType
this.initialize(allSuggestions)
registerDisposable(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (e.affectsConfiguration('latex-workshop.intellisense.atSuggestion.user')) {
this.initialize(allSuggestions)
}
}))
lw.onConfigChange('intellisense.atSuggestion.user', () => {
this.initialize(allSuggestions)
})
}

private initialize(suggestions: {[key: string]: AtSuggestionItemEntry}) {
Expand Down
10 changes: 3 additions & 7 deletions src/completion/completer/command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as vscode from 'vscode'
import * as fs from 'fs'
import type * as Ast from '@unified-latex/unified-latex-types'
import { lw, registerDisposable } from '../../lw'
import { lw } from '../../lw'
import { FileCache } from '../../types'

import type { IProvider, ICompletionItem, PkgType, IProviderArgs } from '../latex'
Expand Down Expand Up @@ -55,13 +55,9 @@ export class Command implements IProvider {
const symbols: { [key: string]: CmdType } = JSON.parse(fs.readFileSync(`${lw.extensionRoot}/data/unimathsymbols.json`).toString()) as DataUnimathSymbolsJsonType
Object.entries(symbols).forEach(([key, symbol]) => this.defaultSymbols.push(this.entryCmdToCompletion(key, symbol)))

registerDisposable(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (!e.affectsConfiguration('latex-workshop.intellisense.command.user') &&
!e.affectsConfiguration('latex-workshop.intellisense.package.exclude')) {
return
}
lw.onConfigChange(['intellisense.command.user', 'intellisense.package.exclude'], () => {
this.initialize(lw.completer.environment)
}))
})
}

initialize(environment: Environment) {
Expand Down
9 changes: 2 additions & 7 deletions src/completion/completer/environment.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as vscode from 'vscode'
import * as fs from 'fs'
import type * as Ast from '@unified-latex/unified-latex-types'
import { lw, registerDisposable } from '../../lw'
import { lw } from '../../lw'
import type { FileCache } from '../../types'
import type { ICompletionItem, IProvider, IProviderArgs } from '../latex'
import { CmdEnvSuggestion, splitSignatureString, filterNonLetterSuggestions, filterArgumentHint } from './completerutils'
Expand Down Expand Up @@ -42,12 +42,7 @@ export class Environment implements IProvider {
private readonly packageEnvsForBegin= new Map<string, CmdEnvSuggestion[]>()

constructor() {
registerDisposable(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (!e.affectsConfiguration('latex-workshop.intellisense.package.exclude')) {
return
}
this.initialize()
}))
lw.onConfigChange('intellisense.package.exclude', () => this.initialize())
}

initialize() {
Expand Down
11 changes: 4 additions & 7 deletions src/extras/counter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,11 @@ export class Counter {
// gotoLine status item has priority 100.5 and selectIndentation item has priority 100.4
this.status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100.45)
this.loadConfiguration(this.getWorkspace())
vscode.workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('latex-workshop.texcount', this.getWorkspace()) || e.affectsConfiguration('latex-workshop.docker.enabled')) {
this.loadConfiguration(this.getWorkspace())
this.updateStatusVisibility()

}
})
this.updateStatusVisibility()
lw.onConfigChange(['texcount', 'docker.enabled'], () => {
this.loadConfiguration(this.getWorkspace())
this.updateStatusVisibility()
})
vscode.window.onDidChangeActiveTextEditor((e: vscode.TextEditor | undefined) => {
if (e && lw.file.hasTexLangId(e.document.languageId)) {
this.loadConfiguration(e.document.uri)
Expand Down
10 changes: 3 additions & 7 deletions src/extras/math-preview-panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,9 @@ export class MathPreviewPanel {
private needCursor: boolean

constructor() {
const configuration = vscode.workspace.getConfiguration('latex-workshop')
this.needCursor = configuration.get('mathpreviewpanel.cursor.enabled', false)
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration('latex-workshop.mathpreviewpanel.cursor.enabled')) {
const conf = vscode.workspace.getConfiguration('latex-workshop')
this.needCursor = conf.get('mathpreviewpanel.cursor.enabled', false)
}
this.needCursor = vscode.workspace.getConfiguration('latex-workshop').get('mathpreviewpanel.cursor.enabled', false)
lw.onConfigChange('mathpreviewpanel.cursor.enabled', () => {
this.needCursor = vscode.workspace.getConfiguration('latex-workshop').get('mathpreviewpanel.cursor.enabled', false)
})
}

Expand Down
9 changes: 2 additions & 7 deletions src/lint/latex-formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import * as cs from 'cross-spawn'
import * as path from 'path'
import * as fs from 'fs'
import * as os from 'os'
import { lw, registerDisposable } from '../lw'
import { lw } from '../lw'
import {replaceArgumentPlaceholders} from '../utils/utils'


Expand Down Expand Up @@ -194,12 +194,7 @@ class LatexFormatterProvider implements vscode.DocumentFormattingEditProvider, v
if (!currentOs) {
logger.log('LaTexFormatter: Unsupported OS')
}

registerDisposable(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (e.affectsConfiguration('latex-workshop.latexindent.path')) {
formatter = ''
}
}))
lw.onConfigChange('latexindent.path', () => formatter = '')
}

public provideDocumentFormattingEdits(document: vscode.TextDocument, _options: vscode.FormattingOptions, _token: vscode.CancellationToken): vscode.ProviderResult<vscode.TextEdit[]> {
Expand Down
46 changes: 37 additions & 9 deletions src/lw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import type * as commands from './core/commands'

/* eslint-disable */
export const lw = {
extensionContext: Object.create(null) as vscode.ExtensionContext,
extensionRoot: '',
constant: {} as typeof constant,
log: {} as typeof log.getLogger,
Expand Down Expand Up @@ -62,7 +61,8 @@ export const lw = {
graphicsPreview: Object.create(null) as GraphicsPreview,
mathPreview: Object.create(null) as MathPreview,
mathPreviewPanel: Object.create(null) as MathPreviewPanel,
commands: Object.create(null) as typeof commands
commands: Object.create(null) as typeof commands,
onConfigChange
}
/* eslint-enable */

Expand All @@ -79,13 +79,41 @@ const constant = {
}
lw.constant = constant

let disposables: { dispose(): any }[] = []

export function registerDisposable(...items: vscode.Disposable[]) {
if (lw.extensionContext.subscriptions) {
lw.extensionContext.subscriptions.push(...disposables, ...items)
disposables = []
let disposables: vscode.Disposable[] | undefined = undefined
const tempDisposables: vscode.Disposable[] = []
/**
* Handle configuration changes and invoke the specified callback function when
* relevant configurations are updated.
*
* @param {string[]} [configs] - Optional. An array of configuration keys to
* monitor for changes.
* @param {Function} [callback] - Optional. The callback function to be executed
* when relevant configurations change.
* @param {vscode.ConfigurationScope} [scope] - Optional. The configuration
* scope to consider when checking for changes.
* @param {vscode.Disposable[]} [extensionDisposables] - Optional. An array of
* disposables associated with the extension. If provided, the function sets
* the global disposables array to extensionDisposables and adds
* tempDisposables to it. If not provided, the function creates a disposable
* to listen for configuration changes and adds it to tempDisposables.
*/
function onConfigChange(configs?: string | string[], callback?: () => void, scope?: vscode.ConfigurationScope, extensionDisposables?: vscode.Disposable[]) {
if (extensionDisposables) {
disposables = extensionDisposables
disposables.push(...tempDisposables)
tempDisposables.length = 0
return
}
const disposable = vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (configs && callback &&
[ configs ].flat().some(config => e.affectsConfiguration(`latex-workshop.${config}`, scope))) {
callback()
}
})
if (disposables === undefined) {
tempDisposables.push(disposable)
} else {
disposables = [...disposables, ...items]
disposables.push(...tempDisposables, disposable)
tempDisposables.length = 0
}
}
35 changes: 14 additions & 21 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as vscode from 'vscode'
import * as path from 'path'
import { lw, registerDisposable } from './lw'
import { lw } from './lw'
lw.extensionRoot = path.resolve(`${__dirname}/../../`)
import { log } from './utils/logger'
lw.log = log.getLogger
Expand Down Expand Up @@ -56,7 +56,7 @@ import * as commander from './core/commands'
const logger = lw.log('Extension')

function initialize(extensionContext: vscode.ExtensionContext) {
lw.extensionContext = extensionContext
lw.onConfigChange(undefined, undefined, undefined, extensionContext.subscriptions)
lw.lwfs = new LwFileSystem()
lw.viewer = new Viewer()
lw.server = new Server()
Expand All @@ -79,7 +79,6 @@ function initialize(extensionContext: vscode.ExtensionContext) {
lw.mathPreview = new MathPreview()
lw.mathPreviewPanel = new MathPreviewPanel()
lw.commands = commander
registerDisposable()

void parser.reset()
log.initStatusBarItem()
Expand Down Expand Up @@ -328,16 +327,13 @@ function registerProviders(extensionContext: vscode.ExtensionContext) {
extensionContext.subscriptions.push(triggerDisposable)
}
registerTrigger()
extensionContext.subscriptions.push(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (e.affectsConfiguration('latex-workshop.intellisense.triggers.latex')) {
if (triggerDisposable) {
triggerDisposable.dispose()
triggerDisposable = undefined
}
registerTrigger()
lw.onConfigChange('intellisense.triggers.latex', () => {
if (triggerDisposable) {
triggerDisposable.dispose()
triggerDisposable = undefined
}
return
}))
registerTrigger()
})

let atSuggestionDisposable: vscode.Disposable | undefined
const registerAtSuggestion = () => {
Expand All @@ -349,16 +345,13 @@ function registerProviders(extensionContext: vscode.ExtensionContext) {
}
}
registerAtSuggestion()
extensionContext.subscriptions.push(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (e.affectsConfiguration('latex-workshop.intellisense.atSuggestion.trigger.latex')) {
if (atSuggestionDisposable) {
atSuggestionDisposable.dispose()
atSuggestionDisposable = undefined
}
registerAtSuggestion()
lw.onConfigChange('intellisense.atSuggestion.trigger.latex', () => {
if (atSuggestionDisposable) {
atSuggestionDisposable.dispose()
atSuggestionDisposable = undefined
}
return
}))
registerAtSuggestion()
})

extensionContext.subscriptions.push(
vscode.languages.registerCodeActionsProvider(latexSelector, lw.codeActions),
Expand Down
25 changes: 4 additions & 21 deletions src/preview/viewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type ws from 'ws'
import * as path from 'path'
import * as os from 'os'
import * as cs from 'cross-spawn'
import { lw, registerDisposable } from '../lw'
import { lw } from '../lw'
import type { SyncTeXRecordForward } from '../locate/synctex'
import { getCurrentThemeLightness } from '../utils/theme'
import type { ClientRequest, PdfViewerParams, PdfViewerState } from '../../types/latex-workshop-protocol-types/index'
Expand All @@ -27,26 +27,9 @@ export class Viewer {
this.refreshExistingViewer(pdfPath)
}
})
registerDisposable(vscode.workspace.onDidChangeConfiguration((e: vscode.ConfigurationChangeEvent) => {
if (e.affectsConfiguration('latex-workshop.view.pdf.invertMode.enabled') ||
e.affectsConfiguration('latex-workshop.view.pdf.invert') ||
e.affectsConfiguration('latex-workshop.view.pdf.invertMode.brightness') ||
e.affectsConfiguration('latex-workshop.view.pdf.invertMode.grayscale') ||
e.affectsConfiguration('latex-workshop.view.pdf.invertMode.hueRotate') ||
e.affectsConfiguration('latex-workshop.view.pdf.invertMode.sepia') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.light.pageColorsForeground') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.light.pageColorsBackground') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.light.backgroundColor') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.light.pageBorderColor') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.dark.pageColorsForeground') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.dark.pageColorsBackground') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.dark.backgroundColor') ||
e.affectsConfiguration('latex-workshop.view.pdf.color.dark.pageBorderColor') ||
e.affectsConfiguration('latex-workshop.view.pdf.internal.synctex.keybinding')) {
this.reloadExistingViewer()
}
return
}))
lw.onConfigChange(['view.pdf.invert', 'view.pdf.invertMode', 'view.pdf.color', 'view.pdf.internal'], () => {
this.reloadExistingViewer()
})
}

reloadExistingViewer(): void {
Expand Down

0 comments on commit a918f83

Please sign in to comment.