latex-language.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. import { LRLanguage, foldNodeProp, foldInside } from '@codemirror/language'
  2. import { parser } from '../../lezer-latex/latex.mjs'
  3. import { styleTags, tags as t } from '@lezer/highlight'
  4. import * as termsModule from '../../lezer-latex/latex.terms.mjs'
  5. import { NodeProp } from '@lezer/common'
  6. import {
  7. Tokens,
  8. commentIsOpenFold,
  9. findClosingFoldComment,
  10. getFoldRange,
  11. } from '../../utils/tree-query'
  12. const styleOverrides: Record<string, any> = {
  13. DocumentClassCtrlSeq: t.keyword,
  14. UsePackageCtrlSeq: t.keyword,
  15. CiteCtrlSeq: t.keyword,
  16. CiteStarrableCtrlSeq: t.keyword,
  17. RefCtrlSeq: t.keyword,
  18. RefStarrableCtrlSeq: t.keyword,
  19. LabelCtrlSeq: t.keyword,
  20. }
  21. const styleEntry = (token: string, defaultStyle: any) => {
  22. return [token, styleOverrides[token] || defaultStyle]
  23. }
  24. const Styles = {
  25. ctrlSeq: Object.fromEntries(
  26. Tokens.ctrlSeq.map(token => styleEntry(token, t.tagName))
  27. ),
  28. ctrlSym: Object.fromEntries(
  29. Tokens.ctrlSym.map(token => styleEntry(token, t.literal))
  30. ),
  31. envName: Object.fromEntries(
  32. Tokens.envName.map(token => styleEntry(token, t.attributeValue))
  33. ),
  34. }
  35. const typeMap: Record<string, string[]> = {
  36. PartCtrlSeq: ['$SectioningCommand'],
  37. ChapterCtrlSeq: ['$SectioningCommand'],
  38. SectionCtrlSeq: ['$SectioningCommand'],
  39. SubSectionCtrlSeq: ['$SectioningCommand'],
  40. SubSubSectionCtrlSeq: ['$SectioningCommand'],
  41. ParagraphCtrlSeq: ['$SectioningCommand'],
  42. SubParagraphCtrlSeq: ['$SectioningCommand'],
  43. }
  44. export const LaTeXLanguage = LRLanguage.define({
  45. parser: parser.configure({
  46. props: [
  47. foldNodeProp.add({
  48. Comment: (node, state) => {
  49. if (commentIsOpenFold(node, state)) {
  50. const closingFoldNode = findClosingFoldComment(node, state)
  51. if (closingFoldNode) {
  52. return getFoldRange(node, closingFoldNode, state)
  53. }
  54. }
  55. return null
  56. },
  57. Group: foldInside,
  58. NonEmptyGroup: foldInside,
  59. TextArgument: foldInside,
  60. // TODO: Why isn't
  61. // `Content: node => node,`
  62. // enough? For some reason it doesn't work if there's a newline after
  63. // \section{a}, but works for \section{a}b
  64. $Environment: node => node.getChild('Content'),
  65. $SectioningCommand: node => {
  66. const BACKWARDS = -1
  67. const lastChild = node.resolveInner(node.to, BACKWARDS)
  68. const content = node.getChild('Content')
  69. if (!content) {
  70. return null
  71. }
  72. if (lastChild.type.is(termsModule.NewLine)) {
  73. // Ignore last newline for sectioning commands
  74. return { from: content!.from, to: lastChild.from }
  75. }
  76. if (lastChild.type.is(termsModule.Whitespace)) {
  77. // If the sectioningcommand is indented on a newline
  78. let sibling = lastChild.prevSibling
  79. while (sibling?.type.is(termsModule.Whitespace)) {
  80. sibling = sibling.prevSibling
  81. }
  82. if (sibling?.type.is(termsModule.NewLine)) {
  83. return { from: content!.from, to: sibling.from }
  84. }
  85. }
  86. if (lastChild.type.is(termsModule.BlankLine)) {
  87. // HACK: BlankLine can contain any number above 2 of \n's.
  88. // Include every one except for the last one
  89. return { from: content!.from, to: lastChild.to - 1 }
  90. }
  91. return content
  92. },
  93. }),
  94. // TODO: does this override groups defined in the grammar?
  95. NodeProp.group.add(type => {
  96. const types = []
  97. if (
  98. Tokens.ctrlSeq.includes(type.name) ||
  99. Tokens.ctrlSym.includes(type.name)
  100. ) {
  101. types.push('$CtrlSeq')
  102. } else if (Tokens.envName.includes(type.name)) {
  103. types.push('$EnvName')
  104. } else if (type.name.endsWith('Argument')) {
  105. types.push('$Argument')
  106. } else if (type.name.endsWith('Environment')) {
  107. types.push('$Environment')
  108. } else if (type.name.endsWith('Brace')) {
  109. types.push('$Brace')
  110. } else if (
  111. ['BracketMath', 'ParenMath', 'DollarMath'].includes(type.name)
  112. ) {
  113. types.push('$MathContainer')
  114. }
  115. if (type.name in typeMap) {
  116. types.push(...typeMap[type.name])
  117. }
  118. return types.length > 0 ? types : undefined
  119. }),
  120. styleTags({
  121. ...Styles.ctrlSeq,
  122. ...Styles.ctrlSym,
  123. ...Styles.envName,
  124. 'HrefCommand/ShortTextArgument/ShortArg/...': t.link,
  125. 'HrefCommand/UrlArgument/...': t.monospace,
  126. 'CtrlSeq Csname': t.tagName,
  127. 'DocumentClass/OptionalArgument/ShortOptionalArg/Normal':
  128. t.attributeValue,
  129. 'DocumentClass/ShortTextArgument/ShortArg/Normal': t.typeName,
  130. Number: t.number,
  131. OpenBrace: t.brace,
  132. CloseBrace: t.brace,
  133. OpenBracket: t.squareBracket,
  134. CloseBracket: t.squareBracket,
  135. Dollar: t.string,
  136. Math: t.string,
  137. 'Math/MathChar': t.string,
  138. 'Math/MathSpecialChar': t.string,
  139. 'Math/Number': t.string,
  140. 'MathGroup/OpenBrace MathGroup/CloseBrace': t.string,
  141. 'MathTextCommand/TextArgument/OpenBrace MathTextCommand/TextArgument/CloseBrace':
  142. t.string,
  143. 'MathOpening/LeftCtrlSeq MathClosing/RightCtrlSeq MathCommand/CtrlSeq MathTextCommand/CtrlSeq':
  144. t.literal,
  145. MathDelimiter: t.literal,
  146. DoubleDollar: t.keyword,
  147. Comment: t.comment,
  148. 'UsePackage/OptionalArgument/ShortOptionalArg/Normal': t.attributeValue,
  149. 'UsePackage/ShortTextArgument/ShortArg/Normal': t.tagName,
  150. 'LiteralArgContent VerbContent VerbatimContent LstInlineContent':
  151. t.string,
  152. 'NewCommand/LiteralArgContent': t.typeName,
  153. 'LabelArgument/ShortTextArgument/ShortArg/...': t.attributeValue,
  154. 'RefArgument/ShortTextArgument/ShortArg/...': t.attributeValue,
  155. 'BibKeyArgument/ShortTextArgument/ShortArg/...': t.attributeValue,
  156. 'ShortTextArgument/ShortArg/Normal': t.monospace,
  157. 'UrlArgument/LiteralArgContent': [t.attributeValue, t.url],
  158. 'FilePathArgument/LiteralArgContent': t.attributeValue,
  159. 'BareFilePathArgument/SpaceDelimitedLiteralArgContent':
  160. t.attributeValue,
  161. TrailingContent: t.comment,
  162. // TODO: t.strong, t.emphasis
  163. }),
  164. ],
  165. }),
  166. languageData: {
  167. commentTokens: { line: '%' },
  168. closeBrackets: { brackets: ['[', '{'] },
  169. closePrefixedBrackets: {
  170. brackets: {
  171. // $$ will produce $$ $$, but we set a single closing $ sign as the value
  172. // because inserting $ will already have added a closing bracket.
  173. $$: '$',
  174. $: '$',
  175. '\\(': '\\)',
  176. '\\[': '\\]',
  177. '\\$': false,
  178. '\\{': false,
  179. },
  180. },
  181. },
  182. })