environments.ts 8.1 KB

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