Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions src/renderer/src/lib/monaco-languages/register-latex.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest'
import {
LATEX_LANGUAGE_ID,
latexLanguageConfiguration,
latexMonarchLanguage,
registerLatexLanguage
} from './register-latex'

function createMonacoMock(existing: { id: string }[] = []) {
return {
languages: {
getLanguages: vi.fn(() => existing),
register: vi.fn(),
setLanguageConfiguration: vi.fn(),
setMonarchTokensProvider: vi.fn()
}
}
}

describe('registerLatexLanguage', () => {
it('registers LaTeX extensions with a Monarch tokens provider', () => {
const monaco = createMonacoMock()

registerLatexLanguage(monaco as never)

expect(monaco.languages.register).toHaveBeenCalledWith({
id: LATEX_LANGUAGE_ID,
extensions: ['.tex', '.ltx', '.latex', '.sty'],
aliases: ['LaTeX', 'latex', 'TeX', 'tex']
})
expect(monaco.languages.setLanguageConfiguration).toHaveBeenCalledWith(
LATEX_LANGUAGE_ID,
latexLanguageConfiguration
)
expect(monaco.languages.setMonarchTokensProvider).toHaveBeenCalledWith(
LATEX_LANGUAGE_ID,
latexMonarchLanguage
)
})

it('is idempotent when the language is already registered', () => {
const monaco = createMonacoMock([{ id: LATEX_LANGUAGE_ID }])

registerLatexLanguage(monaco as never)

expect(monaco.languages.register).not.toHaveBeenCalled()
})

it('tokenizes comments and commands in the Monarch root state', () => {
expect(latexMonarchLanguage.tokenizer.root).toEqual(
expect.arrayContaining([
expect.arrayContaining([/%.*$/, 'comment']),
expect.arrayContaining([expect.any(RegExp), 'keyword'])
])
)
})
})
119 changes: 119 additions & 0 deletions src/renderer/src/lib/monaco-languages/register-latex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import type * as Monaco from 'monaco-editor'

type MonacoModule = typeof Monaco

export const LATEX_LANGUAGE_ID = 'latex'

export const latexLanguageConfiguration: Monaco.languages.LanguageConfiguration = {
comments: {
lineComment: '%'
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '$', close: '$' },
{ open: '`', close: "'" }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: '$', close: '$' }
]
}

// Why: Full VS Code LaTeX TextMate grammars pull dozens of embedded language
// scopes (python, julia, …). A presentation-only Monarch tokenizer covers
// comments, commands, environments, and math delimiters without that graph.
export const latexMonarchLanguage: Monaco.languages.IMonarchLanguage = {
defaultToken: '',
tokenPostfix: '.latex',
ignoreCase: false,

tokenizer: {
root: [
{ include: '@whitespace' },
// Line comments
[/%.*$/, 'comment'],
// Display / inline math environments
[/\\\[/, 'string', '@displayMathBracket'],
[/\\\(/, 'string', '@inlineMathParen'],
[/\$\$/, 'string', '@displayMathDollar'],
[/\$/, 'string', '@inlineMathDollar'],
// \begin{env} / \end{env}
[
/\\(begin|end)\s*\{[a-zA-Z*]+\}/,
{
cases: {
'@default': 'keyword'
}
}
],
// Commands: \command, \command*, \\, and special single-char commands
[/\\(?:[a-zA-Z]+|[^a-zA-Z\s])/, 'keyword'],
Comment on lines +49 to +59

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Literal dollars change later colors

The rules read text inside \verb and verbatim as LaTeX syntax. For example, \verb|$HOME| starts inlineMathDollar, and a verbatim block containing $HOME does the same. Neither closing construct leaves that state, so ordinary text afterward stays colored as math until another dollar sign appears.

Add literal-text rules before the general command and environment rules. Test that text after each closing construct returns to normal colors.

// Grouping braces / optional args
[/[{}]/, '@brackets'],
[/[[\]]/, '@brackets'],
// Plain text
[/[^\\%$[\]{}]+/, '']
],

whitespace: [[/[ \t\r\n]+/, 'white']],

displayMathBracket: [
[/\\\]/, 'string', '@pop'],
[/%.*$/, 'comment'],
[/\\(?:[a-zA-Z]+|[^a-zA-Z\s])/, 'keyword'],
[/[^\\%\]]+/, 'string'],
[/./, 'string']
],

inlineMathParen: [
[/\\\)/, 'string', '@pop'],
[/%.*$/, 'comment'],
[/\\(?:[a-zA-Z]+|[^a-zA-Z\s])/, 'keyword'],
[/[^\\%)]+/, 'string'],
[/./, 'string']
],

displayMathDollar: [
[/\$\$/, 'string', '@pop'],
[/%.*$/, 'comment'],
[/\\(?:[a-zA-Z]+|[^a-zA-Z\s])/, 'keyword'],
[/[^\\%$]+/, 'string'],
[/./, 'string']
],

inlineMathDollar: [
[/\$/, 'string', '@pop'],
[/%.*$/, 'comment'],
[/\\(?:[a-zA-Z]+|[^a-zA-Z\s])/, 'keyword'],
[/[^\\%$]+/, 'string'],
[/./, 'string']
]
}
}

export function registerLatexLanguage(monaco: MonacoModule): void {
const languageAlreadyRegistered = monaco.languages
.getLanguages()
.some((language) => language.id === LATEX_LANGUAGE_ID)
if (languageAlreadyRegistered) {
return
}

monaco.languages.register({
id: LATEX_LANGUAGE_ID,
// Why: .cls stays Apex. Main already maps that extension and tests AccountService.cls.
extensions: ['.tex', '.ltx', '.latex', '.sty'],
aliases: ['LaTeX', 'latex', 'TeX', 'tex']
})
monaco.languages.setLanguageConfiguration(LATEX_LANGUAGE_ID, latexLanguageConfiguration)
monaco.languages.setMonarchTokensProvider(LATEX_LANGUAGE_ID, latexMonarchLanguage)
}
52 changes: 52 additions & 0 deletions src/renderer/src/lib/monaco-languages/register-matlab.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { describe, expect, it, vi } from 'vitest'
import {
MATLAB_LANGUAGE_ID,
loadMatlabTextMateGrammar,
matlabLanguageConfiguration,
registerMatlabLanguage
} from './register-matlab'

function createMonacoMock() {
return {
languages: {
getLanguages: vi.fn(() => []),
register: vi.fn(),
setLanguageConfiguration: vi.fn(),
registerTokensProviderFactory: vi.fn()
}
}
}

describe('registerMatlabLanguage', () => {
it('maps .m to the TextMate-backed matlab language', () => {
const monaco = createMonacoMock()

registerMatlabLanguage(monaco as never)

expect(monaco.languages.register).toHaveBeenCalledWith({
id: MATLAB_LANGUAGE_ID,
extensions: ['.m'],
aliases: ['MATLAB', 'matlab']
})
expect(monaco.languages.setLanguageConfiguration).toHaveBeenCalledWith(
MATLAB_LANGUAGE_ID,
matlabLanguageConfiguration
)
expect(monaco.languages.registerTokensProviderFactory).toHaveBeenCalledWith(
MATLAB_LANGUAGE_ID,
expect.objectContaining({ create: expect.any(Function) })
)
})
})

describe('loadMatlabTextMateGrammar', () => {
it('loads the vendored MATLAB TextMate grammar', async () => {
const grammar = await loadMatlabTextMateGrammar()

expect(grammar).toMatchObject({
name: MATLAB_LANGUAGE_ID,
scopeName: 'source.matlab',
fileTypes: ['m']
})
})
})
53 changes: 53 additions & 0 deletions src/renderer/src/lib/monaco-languages/register-matlab.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type * as Monaco from 'monaco-editor'
import type { LanguageRegistration } from 'shiki/core'
import { registerTextMateLanguage } from './textmate-language-registration'

type MonacoModule = typeof Monaco

export const MATLAB_LANGUAGE_ID = 'matlab'

export const matlabLanguageConfiguration: Monaco.languages.LanguageConfiguration = {
comments: {
lineComment: '%'
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
autoClosingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: "'", close: "'" },

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Do not auto-close the MATLAB transpose operator.

When a user types A' at the end of a line, this pair can insert another ' and leave A''. In MATLAB, ' is an operator, so the inserted character changes the expression. Remove the single-quote auto-closing pair; keep string highlighting in the grammar. (code.visualstudio.com)

{ open: '"', close: '"' }
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: "'", close: "'" },
{ open: '"', close: '"' }
]
}

export async function loadMatlabTextMateGrammar(): Promise<LanguageRegistration> {
// Why: MathWorks MATLAB TextMate grammar (BSD-style; see matlab-LICENSE.txt).
const grammarModule = await import('./textmate-grammars/matlab.tmLanguage.json')
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: TextMate injects the $self/$base repository entries a registration's type requires; real tokenization tests validate this vendored JSON.
const grammar = grammarModule.default as unknown as LanguageRegistration
return { ...grammar, name: MATLAB_LANGUAGE_ID }
}

export function registerMatlabLanguage(monaco: MonacoModule): void {
registerTextMateLanguage(monaco, {
language: {
id: MATLAB_LANGUAGE_ID,
// Why: #10363 — prefer MATLAB over Monaco's objective-c association for .m.
extensions: ['.m'],
aliases: ['MATLAB', 'matlab']
},
configuration: matlabLanguageConfiguration,
loadGrammar: loadMatlabTextMateGrammar
Comment on lines +50 to +51

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 MATLAB tokens remain uncolored

The registration passes TextMate names directly to Monaco. The grammar marks function as storage.type.function.matlab and numbers as constant.numeric.matlab, which the default editor themes do not color. These remain plain despite the new highlighting support.

Map these names to Monaco’s keyword and number tokens, as the other TextMate registrations do, and test the resulting colors.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Copyright 2018 The MathWorks, Inc.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Loading