environments.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import { ensureSyntaxTree } from '@codemirror/language'
  2. import { EditorState } from '@codemirror/state'
  3. import { SyntaxNode, SyntaxNodeRef } from '@lezer/common'
  4. import { previousSiblingIs } from './common'
  5. import { NodeIntersectsChangeFn, ProjectionItem } from './projection'
  6. import { FigureData } from '../../extensions/figure-modal'
  7. const HUNDRED_MS = 100
  8. export class Environment extends ProjectionItem {
  9. readonly title: string = ''
  10. readonly type: 'usage' | 'definition' = 'usage'
  11. readonly raw: string = ''
  12. }
  13. export const enterNode = (
  14. state: EditorState,
  15. node: SyntaxNodeRef,
  16. items: Environment[],
  17. nodeIntersectsChange: NodeIntersectsChangeFn
  18. ): any => {
  19. if (node.type.is('EnvNameGroup')) {
  20. if (!nodeIntersectsChange(node.node)) {
  21. return false
  22. }
  23. if (!node.node.prevSibling?.type.is('Begin')) {
  24. return false
  25. }
  26. const openBraceNode = node.node.getChild('OpenBrace')
  27. if (!openBraceNode) {
  28. return false
  29. }
  30. const envNameNode = openBraceNode.node.nextSibling
  31. if (!envNameNode) {
  32. return false
  33. }
  34. const envNameText = state.doc.sliceString(envNameNode.from, envNameNode.to)
  35. if (envNameText.length < 1) {
  36. return false
  37. }
  38. const thisEnvironmentName: Environment = {
  39. title: envNameText,
  40. from: envNameNode.from,
  41. to: envNameNode.to,
  42. line: state.doc.lineAt(envNameNode.from).number,
  43. type: 'usage',
  44. raw: state.sliceDoc(node.from, node.to),
  45. }
  46. items.push(thisEnvironmentName)
  47. } else if (
  48. node.type.is('NewEnvironment') ||
  49. node.type.is('RenewEnvironment')
  50. ) {
  51. if (!nodeIntersectsChange(node.node)) {
  52. // This should already be in `items`
  53. return false
  54. }
  55. const envNameNode = node.node.getChild('LiteralArgContent')
  56. if (!envNameNode) {
  57. return
  58. }
  59. const envNameText = state.doc.sliceString(envNameNode.from, envNameNode.to)
  60. if (!envNameText) {
  61. return
  62. }
  63. const thisEnvironmentName: Environment = {
  64. title: envNameText,
  65. from: envNameNode.from,
  66. to: envNameNode.to,
  67. line: state.doc.lineAt(envNameNode.from).number,
  68. type: 'definition',
  69. raw: state.sliceDoc(node.from, node.to),
  70. }
  71. items.push(thisEnvironmentName)
  72. }
  73. }
  74. export const cursorIsAtBeginEnvironment = (
  75. state: EditorState,
  76. pos: number
  77. ): boolean | undefined => {
  78. const tree = ensureSyntaxTree(state, pos, HUNDRED_MS)
  79. if (!tree) {
  80. return
  81. }
  82. let thisNode = tree.resolve(pos)
  83. if (!thisNode) {
  84. return
  85. }
  86. if (
  87. thisNode.type.is('EnvNameGroup') &&
  88. previousSiblingIs(state, pos, 'Begin')
  89. ) {
  90. return true
  91. } else if (
  92. thisNode.type.is('$Environment') ||
  93. (thisNode.type.is('LaTeX') && pos === state.doc.length) // We're at the end of the document
  94. ) {
  95. // We're at a malformed `\begin{`, resolve leftward
  96. thisNode = tree.resolve(pos, -1)
  97. if (!thisNode) {
  98. return
  99. }
  100. // TODO: may need to handle various envnames
  101. if (thisNode.type.is('OpenBrace') || thisNode.type.is('$EnvName')) {
  102. return true
  103. }
  104. }
  105. }
  106. export const cursorIsAtEndEnvironment = (
  107. state: EditorState,
  108. pos: number
  109. ): boolean | undefined => {
  110. const tree = ensureSyntaxTree(state, pos, HUNDRED_MS)
  111. if (!tree) {
  112. return
  113. }
  114. let thisNode = tree.resolve(pos)
  115. if (!thisNode) {
  116. return
  117. }
  118. if (
  119. thisNode.type.is('EnvNameGroup') &&
  120. previousSiblingIs(state, pos, 'End')
  121. ) {
  122. return true
  123. } else if (thisNode.type.is('$Environment') || thisNode.type.is('Content')) {
  124. // We're at a malformed `\end{`, resolve leftward
  125. thisNode = tree.resolve(pos, -1)
  126. if (!thisNode) {
  127. return
  128. }
  129. // TODO: may need to handle various envnames
  130. if (thisNode.type.is('OpenBrace') || thisNode.type.is('EnvName')) {
  131. return true
  132. }
  133. }
  134. }
  135. /**
  136. *
  137. * @param node A node of type `$Environment`, `BeginEnv`, or `EndEnv`
  138. * @param state The editor state to read the name from
  139. * @returns The editor name or null if a name cannot be found
  140. */
  141. export function getEnvironmentName(
  142. node: SyntaxNode | null,
  143. state: EditorState
  144. ): string | null {
  145. if (node?.type.is('$Environment')) {
  146. node = node.getChild('BeginEnv')
  147. }
  148. if (!node?.type.is('BeginEnv') && !node?.type.is('EndEnv')) {
  149. return null
  150. }
  151. const nameNode = node
  152. ?.getChild('EnvNameGroup')
  153. ?.getChild('OpenBrace')?.nextSibling
  154. if (!nameNode) {
  155. return null
  156. }
  157. // the name node is a parameter in the grammar, so we have no good way to
  158. // target the specific type
  159. if (nameNode.type.is('CloseBrace')) {
  160. return null
  161. }
  162. return state.sliceDoc(nameNode.from, nameNode.to)
  163. }
  164. export const getUnstarredEnvironmentName = (
  165. node: SyntaxNode | null,
  166. state: EditorState
  167. ): string | undefined => getEnvironmentName(node, state)?.replace(/\*$/, '')
  168. export function getEnvironmentArguments(environmentNode: SyntaxNode) {
  169. return environmentNode.getChild('BeginEnv')?.getChildren('TextArgument')
  170. }
  171. export function parseFigureData(
  172. figureEnvironmentNode: SyntaxNode,
  173. state: EditorState
  174. ): FigureData | null {
  175. let caption: FigureData['caption'] = null
  176. let label: FigureData['label'] = null
  177. let file: FigureData['file'] | undefined
  178. let width: FigureData['width']
  179. let unknownGraphicsArguments: FigureData['unknownGraphicsArguments']
  180. let graphicsCommand: FigureData['graphicsCommand'] | undefined
  181. let graphicsCommandArguments: FigureData['graphicsCommandArguments'] = null
  182. const from = figureEnvironmentNode.from
  183. const to = figureEnvironmentNode.to
  184. let error = false
  185. figureEnvironmentNode.cursor().iterate((node: SyntaxNodeRef) => {
  186. if (error) {
  187. return false
  188. }
  189. if (node.type.is('Caption')) {
  190. if (caption) {
  191. // Multiple captions
  192. error = true
  193. return false
  194. }
  195. caption = {
  196. from: node.from,
  197. to: node.to,
  198. }
  199. }
  200. if (node.type.is('Label')) {
  201. if (label) {
  202. // Multiple labels
  203. error = true
  204. return false
  205. }
  206. label = {
  207. from: node.from,
  208. to: node.to,
  209. }
  210. }
  211. if (node.type.is('IncludeGraphics') || node.type.is('IncludeSvg')) {
  212. const isIncludeSvg = node.type.is('IncludeSvg')
  213. if (file) {
  214. // Multiple figure
  215. error = true
  216. return false
  217. }
  218. graphicsCommand = {
  219. from: node.from,
  220. to: node.to,
  221. }
  222. const argumentNodeName = isIncludeSvg
  223. ? 'IncludeSvgArgument'
  224. : 'IncludeGraphicsArgument'
  225. const content = node.node
  226. .getChild(argumentNodeName)
  227. ?.getChild('FilePathArgument')
  228. ?.getChild('LiteralArgContent')
  229. if (!content) {
  230. error = true
  231. return false
  232. }
  233. // \includesvg stores path without .svg extension, but we add it for consistency
  234. file = {
  235. from: content.from,
  236. to: content.to,
  237. path:
  238. state.sliceDoc(content.from, content.to) +
  239. (isIncludeSvg ? '.svg' : ''),
  240. }
  241. const optionalArgs = node.node
  242. .getChild('OptionalArgument')
  243. ?.getChild('ShortOptionalArg')
  244. if (!optionalArgs) {
  245. width = undefined
  246. return false
  247. }
  248. graphicsCommandArguments = {
  249. from: optionalArgs.from,
  250. to: optionalArgs.to,
  251. }
  252. const optionalArgContent = state.sliceDoc(
  253. optionalArgs.from,
  254. optionalArgs.to
  255. )
  256. const widthMatch = optionalArgContent.match(
  257. /^width=([0-9]|(?:[0-9]*\.[0-9]+)|(?:[0-9]+\.))\\(linewidth|pagewidth|textwidth|hsize|columnwidth)$/
  258. )
  259. if (widthMatch) {
  260. width = parseFloat(widthMatch[1])
  261. if (widthMatch[2] !== 'linewidth') {
  262. // We shouldn't edit any width other that linewidth
  263. unknownGraphicsArguments = optionalArgContent
  264. }
  265. } else {
  266. unknownGraphicsArguments = optionalArgContent
  267. }
  268. }
  269. })
  270. if (error) {
  271. return null
  272. }
  273. if (graphicsCommand === undefined || file === undefined) {
  274. return null
  275. }
  276. return new FigureData({
  277. caption,
  278. label,
  279. file,
  280. from,
  281. to,
  282. width,
  283. unknownGraphicsArguments,
  284. graphicsCommand,
  285. graphicsCommandArguments,
  286. })
  287. }