math.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { getEnvironmentName } from './environments'
  2. import { EditorState } from '@codemirror/state'
  3. import { SyntaxNode, SyntaxNodeRef } from '@lezer/common'
  4. import { ancestorNodeOfType } from './ancestors'
  5. export const mathAncestorNode = (state: EditorState, pos: number) =>
  6. ancestorNodeOfType(state, pos, '$MathContainer') ||
  7. ancestorNodeOfType(state, pos, 'EquationEnvironment') ||
  8. // NOTE: EquationArrayEnvironment can be nested inside EquationEnvironment
  9. ancestorNodeOfType(state, pos, 'EquationArrayEnvironment')
  10. export const parseMathContainer = (
  11. state: EditorState,
  12. nodeRef: SyntaxNodeRef,
  13. ancestorNode: SyntaxNode
  14. ) => {
  15. // the content of the Math element, without braces
  16. const innerContent = state.doc.sliceString(nodeRef.from, nodeRef.to).trim()
  17. if (!innerContent.length) {
  18. return null
  19. }
  20. let content = innerContent
  21. let displayMode = false
  22. let passToMathJax = true
  23. if (ancestorNode.type.is('$Environment')) {
  24. const environmentName = getEnvironmentName(ancestorNode, state)
  25. if (environmentName) {
  26. // use the outer content of environments that MathJax supports
  27. // https://docs.mathjax.org/en/latest/input/tex/macros/index.html#environments
  28. if (environmentName === 'tikzcd') {
  29. passToMathJax = false
  30. }
  31. if (environmentName !== 'math' && environmentName !== 'displaymath') {
  32. content = state.doc
  33. .sliceString(ancestorNode.from, ancestorNode.to)
  34. .trim()
  35. }
  36. if (environmentName !== 'math') {
  37. displayMode = true
  38. }
  39. }
  40. } else {
  41. if (
  42. ancestorNode.type.is('BracketMath') ||
  43. Boolean(ancestorNode.getChild('DisplayMath'))
  44. ) {
  45. displayMode = true
  46. }
  47. }
  48. return { content, displayMode, passToMathJax }
  49. }