Adapt to eslint v9 and fix all issues

This commit is contained in:
James Yu 2024-09-06 10:38:16 +08:00
parent b00aa0fc4d
commit 534c88b4e6
21 changed files with 358 additions and 190 deletions

View File

@ -1,13 +0,0 @@
dev/*.js
types/**/*.ts
resources/**/*.js
out
node_modules
viewer/viewer.mjs
.idea/
__pycache__/
.mypy_cache/
.pytest_cache/
.venv/
.vscode/.ropeproject
vscode.proposed.d.ts

View File

@ -1,113 +0,0 @@
{
"env": {
"node": true,
"es6": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"project": "./tsconfig.eslint.json"
},
"rules": {
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-parameter-properties": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/prefer-interface": "off",
"@typescript-eslint/member-delimiter-style": ["error", {
"multiline": {"delimiter": "comma", "requireLast": false},
"singleline": {"delimiter": "comma", "requireLast": false}
}],
"@typescript-eslint/naming-convention": ["error",
{
"selector": "default",
"format": ["camelCase", "PascalCase", "UPPER_CASE"],
"leadingUnderscore": "allow"
},
{
"selector": "method",
"format": ["camelCase"]
},
{
"selector": "function",
"format": ["camelCase"]
},
{
"selector": "typeLike",
"format": ["PascalCase"]
},
{
"selector": "objectLiteralProperty",
"format": null
}
],
"@typescript-eslint/semi": ["error", "never", { "beforeStatementContinuationChars": "always" }],
"@typescript-eslint/type-annotation-spacing": ["error", { "before": false, "after": true, "overrides": { "arrow": { "before": true, "after": true }}}],
"@typescript-eslint/consistent-type-assertions": ["error", { "assertionStyle": "as", "objectLiteralTypeAssertions": "never" }],
"@typescript-eslint/no-empty-interface": [ "error", { "allowSingleExtends": true } ],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-invalid-this": "error",
"@typescript-eslint/no-invalid-void-type": "error",
"@typescript-eslint/no-misused-promises": [ "error", { "checksVoidReturn": { "arguments": false } } ],
"no-shadow": "off",
"@typescript-eslint/no-shadow": "error",
"@typescript-eslint/no-unsafe-argument": "error",
"@typescript-eslint/no-unsafe-assignment": "error",
"@typescript-eslint/no-unsafe-call": "error",
"@typescript-eslint/no-unsafe-return": "error",
"no-unused-expressions": "off",
"@typescript-eslint/no-unused-expressions": "error",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error", { "args": "none" }],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-readonly": "error",
"no-return-await": "off",
"@typescript-eslint/return-await": "error",
"require-await": "off",
"@typescript-eslint/require-await": "error",
"@typescript-eslint/unbound-method": "error",
"curly": "error",
"default-case": "error",
"eol-last": "error",
"eqeqeq": ["error", "always"],
"func-call-spacing": ["error", "never"],
"no-caller": "error",
"no-constant-condition": ["error", { "checkLoops": false }],
"no-eval": "error",
"no-multiple-empty-lines": "error",
"no-multi-spaces": ["error", { "ignoreEOLComments": true }],
"no-new-wrappers": "error",
"no-trailing-spaces": "error",
"no-empty": ["error", { "allowEmptyCatch": true }],
"object-shorthand": "error",
"one-var": ["error", { "initialized": "never", "uninitialized": "never" }],
"prefer-arrow-callback": [ "error" ],
"quotes": ["error", "single", {"avoidEscape": true}],
"space-before-function-paren": ["error", {"anonymous": "always", "named": "never", "asyncArrow": "always"}]
},
"overrides": [
{
"files": ["viewer/**/*.ts"],
"parserOptions": {
"ecmaVersion": 2018,
"project": "./tsconfig.eslint.viewer.json"
},
"rules": {
"@typescript-eslint/naming-convention": ["error", { "selector": "interface", "prefix": ["I"], "format": ["PascalCase"] }],
"@typescript-eslint/no-unnecessary-type-assertion": "off",
"@typescript-eslint/ban-ts-comment": "off"
}
}
]
}

View File

@ -5,16 +5,20 @@ import type { DependencyRaw, EnvironmentRaw, MacroRaw, PackageRaw } from '../src
let _defaultMacros: string[] = []
function isDefaultMacro(macro: string, defaults?: string[]): boolean {
if (defaults === undefined && _defaultMacros.length === 0) {
_defaultMacros = Object.keys(JSON.parse(fs.readFileSync('../data/commands.json').toString()))
_defaultMacros = (JSON.parse(fs.readFileSync('../data/macros.json').toString()) as MacroRaw[]).map(
(m) => m.name + (m.arg?.format ?? '')
)
}
defaults = defaults ?? _defaultMacros
return defaults.includes(macro)
}
let _unimathSymbols: { [key: string]: { detail?: string; documentation?: string } } = {}
let _unimathSymbols: { [key: string]: { command: string, detail: string, documentation: string } } = {}
function getUnimathSymbol(macro: string, defaults?: typeof _unimathSymbols) {
if (defaults === undefined && Object.keys(_unimathSymbols).length === 0) {
defaults = JSON.parse(fs.readFileSync('../data/unimathsymbols.json').toString())
_unimathSymbols = JSON.parse(fs.readFileSync('../data/unimathsymbols.json').toString()) as {
[key: string]: { command: string, detail: string, documentation: string }
}
}
defaults = defaults ?? _unimathSymbols
return defaults[macro]
@ -92,13 +96,13 @@ function parseKeys(pkg: PackageRaw, lines: string[], tag: string): void {
if (match === null) {
break
}
snippet = snippet.replace(/%<([^%]*?)%>/, `$$\{${index}:${match[1]}\}`)
snippet = snippet.replace(/%<([^%]*?)%>/, `$$\{${index}:${match[1]}}`)
index++
}
const match = /^([^#]*?)(=)?#([^%#]+)$/.exec(snippet)
if (match) {
// cache=#true,false => cache=${1|true,false|}
snippet = match[1] + (match[2] === '=' ? `=$\{${index}|${match[3]}|\}` : '')
snippet = match[1] + (match[2] === '=' ? `=$\{${index}|${match[3]}|}` : '')
} else {
// numbersep=##L => numbersep=
snippet = snippet.split('#')[0]
@ -121,7 +125,7 @@ function assignKeys(pkg: PackageRaw, tag: string) {
}
context = context.split('#')[0]
const isEnv = context.startsWith('\\begin')
let name = context.startsWith('\\begin') ? context.slice(7, -1) : context.slice(1)
const name = context.startsWith('\\begin') ? context.slice(7, -1) : context.slice(1)
for (const candidate of isEnv ? pkg.envs : pkg.macros) {
if (candidate.name === name && candidate.arg) {
const keyPos = findKeyPos(candidate.arg.snippet)
@ -138,10 +142,10 @@ function assignKeys(pkg: PackageRaw, tag: string) {
}
function findKeyPos(snippet: string): number {
const matches = snippet.matchAll(/\{\$\{([^\{\}]*)\}\}|\[\$([^\[\]]*)\]|\<\$([^\<\>]*)\>|\|\$([^\<\>]*)\|/g)
const matches = snippet.matchAll(/\{\$\{([^{}]*)\}\}|\[\$([^[\]]*)\]|<\$([^<>]*)>|\|\$([^<>]*)\|/g)
let index = 0
for (const match of matches) {
const context = (match[1] ?? match[2] ?? match[3] ?? match[4]).replace(/[\{\}0-9:]+/g, '')
const context = (match[1] ?? match[2] ?? match[3] ?? match[4]).replace(/[{}0-9:]+/g, '')
if (
context.startsWith('keys') ||
context.startsWith('keyvals') ||
@ -175,7 +179,7 @@ function parseEnv(pkg: PackageRaw, line: string, ifCond?: string): void {
function parseMacro(pkg: PackageRaw, line: string, ifCond?: string): void {
// Special cases in latex-document
if ((/\\left[^a-zA-Z]/.test(line) && /\\right/.test(line)) || /\\right[^a-zA-Z]/.test(line)) {
if ((/\\left[^a-zA-Z]/.test(line) && line.includes('\\right')) || /\\right[^a-zA-Z]/.test(line)) {
return
}
// Special cases in latex-document
@ -187,7 +191,7 @@ function parseMacro(pkg: PackageRaw, line: string, ifCond?: string): void {
const pairs = { '(': ')', '[': ']', '|': '|' }
const macro: MacroRaw = { name: match[1] + (match[2] ?? '') }
if (match[2] === '(' || match[2] === '[' || match[2] === '|') {
macro.arg = { format: match[2] + pairs[match[2]], snippet: `$\{1\}${match[1]}${pairs[match[2]]}` }
macro.arg = { format: match[2] + pairs[match[2]], snippet: `$\{1}${match[1]}${pairs[match[2]]}` }
}
pkg.macros.push(macro)
return
@ -197,7 +201,7 @@ function parseMacro(pkg: PackageRaw, line: string, ifCond?: string): void {
// \mint[%<options%>]{%<language%>}|%<code%>|#M
// \mintinline[keys]{language}{verbatimSymbol}#S
// \mintinline{%<language%>}|%<code%>|#M
const match = /\\([^[\{\n]*?)((?:\{|\[|\(|\|)[^#\n]*)?(?:#(.*))?$/.exec(line)
const match = /\\([^[{\n]*?)((?:\{|\[|\(|\|)[^#\n]*)?(?:#(.*))?$/.exec(line)
if (match === null) {
console.error('Unknown macro line: ' + line)
return
@ -232,16 +236,16 @@ function constructMacroEnv(
}
if (match[2]) {
const arg = match[2]
.replace(/\{[^\{\}]*\}/g, '{}')
.replace(/\[[^\[\]]*\]/g, '[]')
.replace(/(?<![\{\s:\[])(\<)([a-zA-Z\s]*)(\>)/g, '<>')
.replace(/\|[^\|]*\|/g, '||')
.replace(/\([^\(\)]*\)/g, '()')
.replace(/\{[^{}]*\}/g, '{}')
.replace(/\[[^[\]]*\]/g, '[]')
.replace(/(?<![{\s:[])(<)([a-zA-Z\s]*)(>)/g, '<>')
.replace(/\|[^|]*\|/g, '||')
.replace(/\([^()]*\)/g, '()')
if (arg !== '') {
context.arg = { format: arg, snippet: createSnippet(match[2]) }
}
}
if (/[^A-Za-z0-9\{\}\[\]\<\>\|\(\)\*_^:,\s]/.test(context.name + context.arg?.format)) {
if (/[^A-Za-z0-9{}[\]<>|()*_^:,\s]/.test(context.name + context.arg?.format)) {
return
}
return context
@ -251,9 +255,9 @@ function createSnippet(arg: string): string {
let index = 1
// {} [] <> ||
for (const regexp of [
/(\{)(?![\$0-9])([^\{\}]*)(\})/,
/(\[)(?!\$)([^\[\]]*)(\])/,
/(?<![\{\s:\[])(\<)(?!\$)([a-zA-Z\s]*)(\>)/,
/(\{)(?![$0-9])([^{}]*)(\})/,
/(\[)(?!\$)([^[\]]*)(\])/,
/(?<![{\s:[])(<)(?!\$)([a-zA-Z\s]*)(>)/,
/(\|)(?!\$)([^|]*)(\|)/,
]) {
while (true) {
@ -276,7 +280,7 @@ function createSnippet(arg: string): string {
'(' +
match[1]
.split(',')
.map((val) => `$$\{${index++}:${val}\}`)
.map((val) => `$$\{${index++}:${val}}`)
.join(',') +
')'
)
@ -287,7 +291,7 @@ function createSnippet(arg: string): string {
if (tabPos === -1) {
break
}
arg = arg.replace('%|', `$$\{${index++}\}`)
arg = arg.replace('%|', `$$\{${index++}}`)
}
return arg
}
@ -299,7 +303,7 @@ function findArg(arg: string, regexp: RegExp, index: number): string | false {
}
return arg.replace(
regexp,
`${match[1]}$$\{${index}:${match[2].replaceAll('%<', '').replaceAll('%>', '')}\}${match[3]}`
`${match[1]}$$\{${index}:${match[2].replaceAll('%<', '').replaceAll('%>', '')}}${match[3]}`
)
}
@ -323,15 +327,15 @@ function parseFiles(files: string[], folder: string) {
}
function parseExpl3() {
const content = fs.readFileSync(`expl3.cwl`).toString()
const content = fs.readFileSync('expl3.cwl').toString()
const pkg: PackageRaw = { deps: [], macros: [], envs: [], keys: {}, args: [] }
parseLines(pkg, content.split('\n'))
pkg.macros.push({
name: 'ExplSyntaxOn',
arg: { format: '', snippet: '\n\t$0\n\\ExplSyntaxOff' },
doc: 'Insert an \\ExplSyntax block'
doc: 'Insert an \\ExplSyntax block',
})
fs.writeFileSync(`../data/packages/expl3.json`, JSON.stringify(pkg, null, 2))
fs.writeFileSync('../data/packages/expl3.json', JSON.stringify(pkg, null, 2))
}
function parseEssential() {

View File

@ -1,3 +1,5 @@
/* global console */
import fs from 'fs'
import path from 'path'
import {download, getCommitSha, expandConfigurationFile} from'vscode-extend-language'

211
eslint.config.mjs Normal file
View File

@ -0,0 +1,211 @@
import globals from "globals";
import tsParser from "@typescript-eslint/parser";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
import stylistic from "@stylistic/eslint-plugin";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});
export default [{
ignores: [
"dev/*.js",
"types/**/*.ts",
"resources/**/*.js",
"**/out",
"**/node_modules",
"viewer/viewer.mjs",
"**/.idea/",
"**/__pycache__/",
"**/.mypy_cache/",
"**/.pytest_cache/",
"**/.venv/",
".vscode/",
".vscode-test/",
"**/vscode.proposed.d.ts",
],
}, ...compat.extends("eslint:recommended", "plugin:@typescript-eslint/recommended"), {
files: ["**/*.ts", "**/*.js"],
plugins: {
'@stylistic': stylistic,
},
languageOptions: {
globals: {
...globals.node,
Atomics: "readonly",
SharedArrayBuffer: "readonly",
},
parser: tsParser,
ecmaVersion: 2018,
sourceType: "commonjs",
parserOptions: {
project: "./tsconfig.eslint.json",
},
},
rules: {
"@stylistic/member-delimiter-style": ["error", {
multiline: {
delimiter: "comma",
requireLast: false,
},
singleline: {
delimiter: "comma",
requireLast: false,
},
}],
"@stylistic/semi": ["error", "never", {
beforeStatementContinuationChars: "always",
}],
"@stylistic/type-annotation-spacing": "error",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-parameter-properties": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/prefer-interface": "off",
"@typescript-eslint/naming-convention": ["error", {
selector: "default",
format: ["camelCase", "PascalCase", "UPPER_CASE"],
leadingUnderscore: "allow",
}, {
selector: "method",
format: ["camelCase"],
}, {
selector: "function",
format: ["camelCase"],
}, {
selector: "typeLike",
format: ["PascalCase"],
}, {
selector: "objectLiteralProperty",
format: null,
}],
"@typescript-eslint/consistent-type-assertions": ["error", {
assertionStyle: "as",
objectLiteralTypeAssertions: "never",
}],
"@typescript-eslint/no-empty-interface": ["error", {
allowSingleExtends: true,
}],
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-invalid-this": "error",
"@typescript-eslint/no-invalid-void-type": "error",
"@typescript-eslint/no-misused-promises": ["error", {
checksVoidReturn: {
arguments: false,
},
}],
"no-shadow": "off",
"@typescript-eslint/no-shadow": "error",
"@typescript-eslint/no-unsafe-argument": "error",
"@typescript-eslint/no-unsafe-assignment": "error",
"@typescript-eslint/no-unsafe-call": "error",
"@typescript-eslint/no-unsafe-return": "error",
"no-unused-expressions": "off",
"@typescript-eslint/no-unused-expressions": "error",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": ["error", {
args: "all",
argsIgnorePattern: "^_",
caughtErrorsIgnorePattern: "^_"
}],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-readonly": "error",
"no-return-await": "off",
"@typescript-eslint/return-await": "error",
"require-await": "off",
"@typescript-eslint/require-await": "error",
"@typescript-eslint/unbound-method": "error",
curly: "error",
"default-case": "error",
"eol-last": "error",
eqeqeq: ["error", "always"],
"func-call-spacing": ["error", "never"],
"no-caller": "error",
"no-constant-condition": ["error", {
checkLoops: false,
}],
"no-eval": "error",
"no-multiple-empty-lines": "error",
"no-multi-spaces": ["error", {
ignoreEOLComments: true,
}],
"no-new-wrappers": "error",
"no-trailing-spaces": "error",
"no-empty": ["error", {
allowEmptyCatch: true,
}],
"object-shorthand": "error",
"one-var": ["error", {
initialized: "never",
uninitialized: "never",
}],
"prefer-arrow-callback": ["error"],
quotes: ["error", "single", {
avoidEscape: true,
}],
"space-before-function-paren": ["error", {
anonymous: "always",
named: "never",
asyncArrow: "always",
}],
},
}, {
files: ["viewer/**/*.ts"],
languageOptions: {
ecmaVersion: 2018,
sourceType: "script",
parserOptions: {
project: "./tsconfig.eslint.viewer.json",
},
},
rules: {
"@typescript-eslint/naming-convention": ["error", {
selector: "interface",
prefix: ["I"],
format: ["PascalCase"],
}],
"@typescript-eslint/no-unnecessary-type-assertion": "off",
"@typescript-eslint/ban-ts-comment": "off",
},
}];

73
package-lock.json generated
View File

@ -21,6 +21,7 @@
"ws": "8.18.0"
},
"devDependencies": {
"@stylistic/eslint-plugin": "^2.7.2",
"@types/cross-spawn": "6.0.6",
"@types/glob": "8.1.0",
"@types/micromatch": "4.0.9",
@ -1068,6 +1069,53 @@
"integrity": "sha512-sXXKG+uL9IrKqViTtao2Ws6dy0znu9sOaP1di/jKGW1M6VssO8vlpXCQcpZ+jisQ1tTFAC5Jo/EOzFbggBagFQ==",
"dev": true
},
"node_modules/@stylistic/eslint-plugin": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin/-/eslint-plugin-2.7.2.tgz",
"integrity": "sha512-3DVLU5HEuk2pQoBmXJlzvrxbKNpu2mJ0SRqz5O/CJjyNCr12ZiPcYMEtuArTyPOk5i7bsAU44nywh1rGfe3gKQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/eslint": "^9.6.1",
"@typescript-eslint/utils": "^8.3.0",
"eslint-visitor-keys": "^4.0.0",
"espree": "^10.1.0",
"estraverse": "^5.3.0",
"picomatch": "^4.0.2"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"peerDependencies": {
"eslint": ">=8.40.0"
}
},
"node_modules/@stylistic/eslint-plugin/node_modules/eslint-visitor-keys": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.0.0.tgz",
"integrity": "sha512-OtIRv/2GyiF6o/d8K7MYKKbXrOUBIK6SfkIRM4Z0dY3w+LiQ0vy3F57m0Z71bjbyeiWFiHJ8brqnmE6H6/jEuw==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
}
},
"node_modules/@stylistic/eslint-plugin/node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/@types/braces": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/braces/-/braces-3.0.4.tgz",
@ -1092,6 +1140,24 @@
"@types/node": "*"
}
},
"node_modules/@types/eslint": {
"version": "9.6.1",
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz",
"integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "*",
"@types/json-schema": "*"
}
},
"node_modules/@types/estree": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz",
"integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/form-data": {
"version": "0.0.33",
"resolved": "https://registry.npmjs.org/@types/form-data/-/form-data-0.0.33.tgz",
@ -1117,6 +1183,13 @@
"integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==",
"dev": true
},
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
"integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/micromatch": {
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/micromatch/-/micromatch-4.0.9.tgz",

View File

@ -2598,6 +2598,7 @@
"ws": "8.18.0"
},
"devDependencies": {
"@stylistic/eslint-plugin": "^2.7.2",
"@types/cross-spawn": "6.0.6",
"@types/glob": "8.1.0",
"@types/micromatch": "4.0.9",

View File

@ -388,8 +388,8 @@ function isMikTeX(): boolean {
} else {
state.isMikTeX = false
}
} catch (e) {
logger.log('Cannot run `pdflatex` to determine if we are using MiKTeX.')
} catch (err) {
logger.logError('Cannot run `pdflatex` to determine if we are using MiKTeX.', err)
state.isMikTeX = false
}
}

View File

@ -310,7 +310,7 @@ function entryEnvToCompletion(item: EnvironmentInfo, type: EnvSnippetType): CmdE
if (item.detail) {
suggestion.label = item.detail
}
suggestion.filterText = item.detail,
suggestion.filterText = item.detail
suggestion.insertText = new vscode.SnippetString(`${prefix}${item.name}}${snippet}\\end{${item.name}}`)
return suggestion
}

View File

@ -105,7 +105,9 @@ abstract class InputAbstract implements CompletionProvider {
suggestions.push(item)
}
})
} catch (error) {}
} catch (err) {
logger.logError(`Error reading directory ${dir} .` ,err)
}
})
return suggestions
}

View File

@ -34,9 +34,9 @@ function initialize() {
const excludeDefault = (vscode.workspace.getConfiguration('latex-workshop').get('intellisense.package.exclude') as string[]).includes('lw-default')
const macros = excludeDefault ? [] : JSON.parse(fs.readFileSync(`${lw.extensionRoot}/data/macros.json`, {encoding: 'utf8'})) as (MacroRaw & { action?: string })[]
const mathMacros = excludeDefault ? [] : (JSON.parse(fs.readFileSync(`${lw.extensionRoot}/data/packages/tex.json`, {encoding: 'utf8'})) as PackageRaw).macros
let all: (MacroRaw & { package: string, action?: string })[] = [...macros, ...mathMacros].map(macro => {
let all: (MacroRaw & { package: string, action?: string })[] = [...macros, ...mathMacros].map(m => {
const macroInfo = {
...macro,
...m,
package: 'latex',
}
return macroInfo
@ -46,13 +46,13 @@ function initialize() {
const userCmds = vscode.workspace.getConfiguration('latex-workshop').get('intellisense.command.user') as {[key: string]: string}
Object.entries(userCmds).forEach(([key, snippet]) => {
const candidate = all.find(macro => macro.name + (macro.arg?.format ?? '') === key)
const candidate = all.find(m => m.name + (m.arg?.format ?? '') === key)
if (candidate && snippet !== '') {
candidate.name = ''
candidate.arg = { format: snippet, snippet }
candidate.package = 'user'
} else if (candidate && snippet === '') {
all = all.filter(macro => macro !== candidate)
all = all.filter(m => m !== candidate)
} else {
all.push({ name: key, package: 'user', arg: { format: '', snippet } })
}
@ -61,7 +61,7 @@ function initialize() {
data.defaultCmds = []
// Initialize default macros and the ones in `tex.json`
all.forEach(macro => data.defaultCmds.push(entryCmdToCompletion(macro, macro.package, macro.action)))
all.forEach(m => data.defaultCmds.push(entryCmdToCompletion(m, m.package, m.action)))
// Initialize default env begin-end pairs
defaultEnvs.forEach(cmd => {
@ -416,12 +416,12 @@ function entryCmdToCompletion(item: MacroRaw, packageName?: string, postAction?:
suggestion.insertText = item.name
}
suggestion.filterText = item.detail ?? item.name
suggestion.detail = item.detail ?? `\\${item.arg?.snippet?.replace(/\$\{\d+:([^$}]*)\}/g, '$1')}` ?? `\\${item.name}`
suggestion.detail = item.detail ?? (item.arg?.snippet ? `\\${item.arg?.snippet?.replace(/\$\{\d+:([^$}]*)\}/g, '$1')}` : `\\${item.name}`)
suggestion.documentation = item.doc ?? `Macro \\${item.name}${item.arg?.format ?? ''}.`
if (packageName) {
suggestion.documentation += ` From package: ${packageName}.`
}
suggestion.sortText = (item.name + item.arg?.format ?? '').replace(/^[a-zA-Z]/, c => {
suggestion.sortText = (item.name + (item.arg?.format ?? '')).replace(/^[a-zA-Z]/, c => {
const n = c.match(/[a-z]/) ? c.toUpperCase().charCodeAt(0): c.toLowerCase().charCodeAt(0)
return n !== undefined ? n.toString(16): c
})
@ -435,7 +435,7 @@ function entryCmdToCompletion(item: MacroRaw, packageName?: string, postAction?:
}
function setPackageCmds(packageName: string, macros: MacroRaw[]) {
data.packageCmds.set(packageName, macros.map(macro => entryCmdToCompletion(macro, packageName)))
data.packageCmds.set(packageName, macros.map(m => entryCmdToCompletion(m, packageName)))
}
function getPackageCmds(packageName: string) {

View File

@ -64,8 +64,8 @@ function load(packageName: string) {
lw.completion.macro.setPackageCmds(packageName, packageData.macros)
data.loaded.push(packageName)
} catch (e) {
logger.log(`Cannot parse intellisense file: ${filePath}`)
} catch (err) {
logger.logError(`Cannot parse intellisense file: ${filePath}`, err)
}
}

View File

@ -327,6 +327,8 @@ async function findInWorkspace(): Promise<string | undefined> {
logger.log(`Found files that might be root, choose the first one: ${candidates} .`)
return candidates[0]
}
} catch (e) {}
} catch (err) {
logger.logError('Error finding root file in workspace', err)
}
return
}

View File

@ -139,7 +139,8 @@ function format(document: vscode.TextDocument, range?: vscode.Range): Thenable<v
try {
fs.unlinkSync(temporaryFile)
fs.unlinkSync(documentDirectory + path.sep + 'indent.log')
} catch (ignored) {
} catch (err) {
logger.logError('Error when removing temporary file', err)
}
}

View File

@ -53,7 +53,7 @@ async function bib(s: string, options?: bibtexParser.ParserOptions): Promise<bib
}
function stringify(ast: Ast.Ast): string {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return
return toString(ast)
}

View File

@ -17,7 +17,7 @@ function parseLaTeX(content: string): Ast.Root {
}
function parseArgs(ast: Ast.Root, macros: Ast.MacroInfoRecord) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
attachMacroArgs(ast, macros)
}

View File

@ -19,7 +19,7 @@ export async function onMath(document: vscode.TextDocument, tex: TeXMathEnv, mac
} catch(e) {
if (macros !== '') {
logger.log(`Failed rendering MathJax ${typesetArg} . Try removing macro definitions.`)
return await onMath(document, tex, '')
return onMath(document, tex, '')
} else {
logger.logError(`Failed rendering MathJax ${typesetArg} .`, e)
throw e

View File

@ -144,36 +144,36 @@ export type TeXMathEnv = {
}
export type PackageRaw = {
deps: DependencyRaw[]
macros: MacroRaw[]
envs: EnvironmentRaw[]
keys: { [key: string]: string[] }
deps: DependencyRaw[],
macros: MacroRaw[],
envs: EnvironmentRaw[],
keys: { [key: string]: string[] },
args: string[]
}
export type DependencyRaw = {
name: string
name: string,
if?: string
}
export type EnvironmentRaw = {
name: string
arg?: { format: string; snippet: string; keys?: string[]; keyPos?: number }
if?: string
name: string,
arg?: { format: string, snippet: string, keys?: string[], keyPos?: number },
if?: string,
unusual?: boolean
}
export type MacroRaw = {
name: string
arg?: { format: string; snippet: string; keys?: string[]; keyPos?: number }
if?: string
unusual?: boolean
detail?: string
name: string,
arg?: { format: string, snippet: string, keys?: string[], keyPos?: number },
if?: string,
unusual?: boolean,
detail?: string,
doc?: string
}
export type EnvironmentInfo = EnvironmentRaw & {
package: string
package: string,
detail: string
}

View File

@ -28,9 +28,7 @@ export function convertFilenameEncoding(filePath: string): string | undefined {
if (fs.existsSync(fpath)) {
return fpath
}
} catch (e) {
}
} catch (_) {}
}
return
}

View File

@ -34,7 +34,7 @@ async function main() {
await runTestSuites('unittest')
await runTestSuites('testground')
await runTestSuites('multiroot')
} catch (err) {
} catch (_) {
console.error('Failed to run tests')
process.exit(1)
}

View File

@ -22,7 +22,7 @@ const webViewerLoaded = new Promise<void>((resolve) => {
// https://github.com/James-Yu/LaTeX-Workshop/pull/4220#issuecomment-2034520751
try {
parent.document.addEventListener('webviewerloaded', () => resolve() )
} catch(err) { /* do nothing */ }
} catch(_) { /* do nothing */ }
})
// For the details of the initialization of PDF.js,