completions.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { CompletionContext, CompletionSource } from '@codemirror/autocomplete'
  2. import { syntaxTree } from '@codemirror/language'
  3. import { EditorState } from '@codemirror/state'
  4. import { SyntaxNode } from '@lezer/common'
  5. import { ancestorOfNodeWithType } from './ancestors'
  6. export const ifInType = (
  7. type: string,
  8. source: CompletionSource
  9. ): CompletionSource => {
  10. return (context: CompletionContext) => {
  11. const tree = syntaxTree(context.state)
  12. let node: SyntaxNode | null = tree.resolveInner(context.pos, -1)
  13. while (node) {
  14. if (node.type.is(type)) {
  15. return source(context)
  16. }
  17. node = node.parent
  18. }
  19. return null
  20. }
  21. }
  22. function isInEmptyArgumentNodeOfType(state: EditorState, types: string[]) {
  23. const main = state.selection.main
  24. if (!main.empty) {
  25. return false
  26. }
  27. const pos = main.anchor
  28. const tree = syntaxTree(state)
  29. if (tree.length < pos) {
  30. return false
  31. }
  32. const nodeLeft = tree.resolveInner(pos, -1)
  33. if (!nodeLeft.type.is('OpenBrace')) {
  34. return false
  35. }
  36. const nodeRight = tree.resolveInner(pos, 1)
  37. if (!nodeRight.type.is('CloseBrace')) {
  38. return false
  39. }
  40. const ancestor = ancestorOfNodeWithType(nodeLeft, ...types)
  41. if (!ancestor) {
  42. return false
  43. }
  44. return ancestor.from === nodeLeft.from && ancestor.to === nodeRight.to
  45. }
  46. export function isInEmptyArgumentNodeForAutocomplete(state: EditorState) {
  47. return isInEmptyArgumentNodeOfType(state, [
  48. 'EnvNameGroup',
  49. 'BibliographyStyleArgument',
  50. 'BibliographyArgument',
  51. 'BibKeyArgument',
  52. 'DocumentClassArgument',
  53. 'FilePathArgument',
  54. 'RefArgument',
  55. 'PackageArgument',
  56. ])
  57. }
  58. export function isInEmptyCiteArgumentNode(state: EditorState) {
  59. return isInEmptyArgumentNodeOfType(state, ['BibKeyArgument'])
  60. }