latex-language.ts 6.8 KB

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