-
Notifications
You must be signed in to change notification settings - Fork 538
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix #4045 Use AST to parse new commands for preview
- Loading branch information
Showing
3 changed files
with
70 additions
and
63 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,86 +1,93 @@ | ||
import * as vscode from 'vscode' | ||
import * as path from 'path' | ||
import type * as Ast from '@unified-latex/unified-latex-types' | ||
import { lw } from '../../../lw' | ||
import { stripCommentsAndVerbatim } from '../../../utils/utils' | ||
|
||
const logger = lw.log('Preview', 'Math') | ||
|
||
export async function findProjectNewCommand(ctoken?: vscode.CancellationToken): Promise<string> { | ||
export async function findNewCommand(ctoken?: vscode.CancellationToken): Promise<string> { | ||
let newcommand = '' | ||
const filepaths = [] | ||
const configuration = vscode.workspace.getConfiguration('latex-workshop') | ||
const newCommandFile = configuration.get('hover.preview.newcommand.newcommandFile') as string | ||
let commandsInConfigFile = '' | ||
if (newCommandFile !== '') { | ||
commandsInConfigFile = await loadNewCommandFromConfigFile(newCommandFile) | ||
const newcommandPath = await resolveNewCommandFile(configuration.get('hover.preview.newcommand.newcommandFile') as string) | ||
if (newcommandPath !== undefined) { | ||
filepaths.push(newcommandPath) | ||
if (lw.cache.get(newcommandPath) === undefined) { | ||
lw.cache.add(newcommandPath) | ||
} | ||
} | ||
|
||
if (!configuration.get('hover.preview.newcommand.parseTeXFile.enabled')) { | ||
return commandsInConfigFile | ||
if (configuration.get('hover.preview.newcommand.parseTeXFile.enabled') as boolean) { | ||
lw.cache.getIncludedTeX().forEach(filepath => filepaths.push(filepath)) | ||
} | ||
let commands: string[] = [] | ||
for (const tex of lw.cache.getIncludedTeX()) { | ||
for (const filepath of filepaths) { | ||
if (ctoken?.isCancellationRequested) { | ||
return '' | ||
} | ||
await lw.cache.wait(tex) | ||
const content = lw.cache.get(tex)?.content | ||
if (content === undefined) { | ||
continue | ||
await lw.cache.wait(filepath) | ||
const content = lw.cache.get(filepath)?.content | ||
const ast = lw.cache.get(filepath)?.ast | ||
if (content === undefined || ast === undefined) { | ||
logger.log(`Cannot parse the AST of ${filepath} .`) | ||
} else { | ||
newcommand += parseAst(content, ast).join('\n') + '\n' | ||
} | ||
commands = commands.concat(findNewCommand(content)) | ||
} | ||
return commandsInConfigFile + '\n' + postProcessNewCommands(commands.join('')) | ||
|
||
return newcommand | ||
} | ||
|
||
function postProcessNewCommands(commands: string): string { | ||
return commands.replace(/\\providecommand/g, '\\newcommand') | ||
.replace(/\\newcommand\*/g, '\\newcommand') | ||
.replace(/\\renewcommand\*/g, '\\renewcommand') | ||
.replace(/\\DeclarePairedDelimiter{(\\[a-zA-Z]+)}{([^{}]*)}{([^{}]*)}/g, '\\newcommand{$1}[2][]{#1$2 #2 #1$3}') | ||
function parseAst(content: string, node: Ast.Node): string[] { | ||
let macros = [] | ||
const args = node.type === 'macro' && node.args | ||
// \newcommand{\fix}[3][]{\chdeleted{#2}\chadded[comment={#1}]{#3}} | ||
// \newcommand\WARNING{\textcolor{red}{WARNING}} | ||
const isNewCommand = node.type === 'macro' && | ||
['renewcommand', 'newcommand'].includes(node.content) && | ||
node.args?.[2]?.content?.[0]?.type === 'macro' | ||
// \DeclarePairedDelimiterX\braketzw[2]{\langle}{\rangle}{#1\,\delimsize\vert\,\mathopen{}#2} | ||
const isDeclarePairedDelimiter = node.type === 'macro' && | ||
['DeclarePairedDelimiter', 'DeclarePairedDelimiterX', 'DeclarePairedDelimiterXPP'].includes(node.content) && | ||
node.args?.[0]?.content?.[0]?.type === 'macro' | ||
const isProvideCommand = node.type === 'macro' && | ||
['providecommand', 'DeclareMathOperator', 'DeclareRobustCommand'].includes(node.content) && | ||
node.args?.[1]?.content?.[0]?.type === 'macro' | ||
if (args && (isNewCommand || isDeclarePairedDelimiter || isProvideCommand)) { | ||
// \newcommand{\fix}[3][]{\chdeleted{#2}\chadded[comment={#1}]{#3}} | ||
// \newcommand\WARNING{\textcolor{red}{WARNING}} | ||
const start = node.position?.start.offset ?? 0 | ||
const lastArg = args[args.length - 1] | ||
const end = lastArg.content[lastArg.content.length - 1].position?.end.offset ?? -1 | ||
macros.push(content.slice(start, end + 1)) | ||
} | ||
|
||
if ('content' in node && typeof node.content !== 'string') { | ||
for (const subNode of node.content) { | ||
macros = [...macros, ...parseAst(content, subNode)] | ||
} | ||
} | ||
return macros | ||
} | ||
|
||
async function loadNewCommandFromConfigFile(newCommandFile: string) { | ||
let commandsString: string | undefined = '' | ||
if (newCommandFile === '') { | ||
return commandsString | ||
async function resolveNewCommandFile(filepath: string): Promise<string | undefined> { | ||
if (filepath === '') { | ||
return undefined | ||
} | ||
let newCommandFileAbs: string | ||
if (path.isAbsolute(newCommandFile)) { | ||
newCommandFileAbs = newCommandFile | ||
let filepathAbs: string | ||
if (path.isAbsolute(filepath)) { | ||
filepathAbs = filepath | ||
} else { | ||
if (lw.root.file.path === undefined) { | ||
await lw.root.find() | ||
} | ||
const rootDir = lw.root.dir.path | ||
if (rootDir === undefined) { | ||
logger.log(`Cannot identify the absolute path of new command file ${newCommandFile} without root file.`) | ||
return '' | ||
logger.log(`Cannot identify the absolute path of new command file ${filepath} without root file.`) | ||
return undefined | ||
} | ||
newCommandFileAbs = path.join(rootDir, newCommandFile) | ||
filepathAbs = path.join(rootDir, filepath) | ||
} | ||
commandsString = lw.file.read(newCommandFileAbs) | ||
if (commandsString === undefined) { | ||
logger.log(`Cannot read file ${newCommandFileAbs}`) | ||
return '' | ||
if (await lw.file.exists(vscode.Uri.file(filepathAbs))) { | ||
return filepathAbs | ||
} | ||
commandsString = commandsString.replace(/^\s*$/gm, '') | ||
commandsString = postProcessNewCommands(commandsString) | ||
return commandsString | ||
} | ||
|
||
function findNewCommand(content: string): string[] { | ||
const commands: string[] = [] | ||
const regex = /(\\(?:(?:(?:(?:re)?new|provide)command|DeclareMathOperator)(\*)?{\\[a-zA-Z]+}(?:\[[^[\]{}]*\])*{.*})|\\(?:def\\[a-zA-Z]+(?:#[0-9])*{.*})|\\DeclarePairedDelimiter{\\[a-zA-Z]+}{[^{}]*}{[^{}]*})/gm | ||
const noCommentContent = stripCommentsAndVerbatim(content) | ||
let result: RegExpExecArray | null | ||
do { | ||
result = regex.exec(noCommentContent) | ||
if (result) { | ||
let command = result[1] | ||
if (result[2]) { | ||
command = command.replace('*', '') | ||
} | ||
commands.push(command) | ||
} | ||
} while (result) | ||
return commands | ||
return undefined | ||
} |