latex-language.ts 6.5 KB

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