index.d.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import * as _codemirror_state from '@codemirror/state';
  2. import { EditorState, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
  3. import { EditorView, KeyBinding, Command } from '@codemirror/view';
  4. import * as _lezer_common from '@lezer/common';
  5. interface CompletionConfig {
  6. /**
  7. When enabled (defaults to true), autocompletion will start
  8. whenever the user types something that can be completed.
  9. */
  10. activateOnTyping?: boolean;
  11. /**
  12. Override the completion sources used. By default, they will be
  13. taken from the `"autocomplete"` [language
  14. data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) (which should hold
  15. [completion sources](https://codemirror.net/6/docs/ref/#autocomplete.CompletionSource) or arrays
  16. of [completions](https://codemirror.net/6/docs/ref/#autocomplete.Completion)).
  17. */
  18. override?: readonly CompletionSource[] | null;
  19. /**
  20. Determines whether the completion tooltip is closed when the
  21. editor loses focus. Defaults to true.
  22. */
  23. closeOnBlur?: boolean;
  24. /**
  25. The maximum number of options to render to the DOM.
  26. */
  27. maxRenderedOptions?: number;
  28. /**
  29. Set this to false to disable the [default completion
  30. keymap](https://codemirror.net/6/docs/ref/#autocomplete.completionKeymap). (This requires you to
  31. add bindings to control completion yourself. The bindings should
  32. probably have a higher precedence than other bindings for the
  33. same keys.)
  34. */
  35. defaultKeymap?: boolean;
  36. /**
  37. By default, completions are shown below the cursor when there is
  38. space. Setting this to true will make the extension put the
  39. completions above the cursor when possible.
  40. */
  41. aboveCursor?: boolean;
  42. /**
  43. This can be used to add additional CSS classes to completion
  44. options.
  45. */
  46. optionClass?: (completion: Completion) => string;
  47. /**
  48. By default, the library will render icons based on the
  49. completion's [type](https://codemirror.net/6/docs/ref/#autocomplete.Completion.type) in front of
  50. each option. Set this to false to turn that off.
  51. */
  52. icons?: boolean;
  53. /**
  54. This option can be used to inject additional content into
  55. options. The `render` function will be called for each visible
  56. completion, and should produce a DOM node to show. `position`
  57. determines where in the DOM the result appears, relative to
  58. other added widgets and the standard content. The default icons
  59. have position 20, the label position 50, and the detail position 70.
  60. */
  61. addToOptions?: {
  62. render: (completion: Completion, state: EditorState) => Node | null;
  63. position: number;
  64. }[];
  65. }
  66. /**
  67. Objects type used to represent individual completions.
  68. */
  69. interface Completion {
  70. /**
  71. The label to show in the completion picker. This is what input
  72. is matched agains to determine whether a completion matches (and
  73. how well it matches).
  74. */
  75. label: string;
  76. /**
  77. An optional short piece of information to show (with a different
  78. style) after the label.
  79. */
  80. detail?: string;
  81. /**
  82. Additional info to show when the completion is selected. Can be
  83. a plain string or a function that'll render the DOM structure to
  84. show when invoked.
  85. */
  86. info?: string | ((completion: Completion) => (Node | null | Promise<Node | null>));
  87. /**
  88. How to apply the completion. The default is to replace it with
  89. its [label](https://codemirror.net/6/docs/ref/#autocomplete.Completion.label). When this holds a
  90. string, the completion range is replaced by that string. When it
  91. is a function, that function is called to perform the
  92. completion. If it fires a transaction, it is responsible for
  93. adding the [`pickedCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.pickedCompletion)
  94. annotation to it.
  95. */
  96. apply?: string | ((view: EditorView, completion: Completion, from: number, to: number) => void);
  97. /**
  98. The type of the completion. This is used to pick an icon to show
  99. for the completion. Icons are styled with a CSS class created by
  100. appending the type name to `"cm-completionIcon-"`. You can
  101. define or restyle icons by defining these selectors. The base
  102. library defines simple icons for `class`, `constant`, `enum`,
  103. `function`, `interface`, `keyword`, `method`, `namespace`,
  104. `property`, `text`, `type`, and `variable`.
  105. Multiple types can be provided by separating them with spaces.
  106. */
  107. type?: string;
  108. /**
  109. When given, should be a number from -99 to 99 that adjusts how
  110. this completion is ranked compared to other completions that
  111. match the input as well as this one. A negative number moves it
  112. down the list, a positive number moves it up.
  113. */
  114. boost?: number;
  115. }
  116. /**
  117. An instance of this is passed to completion source functions.
  118. */
  119. declare class CompletionContext {
  120. /**
  121. The editor state that the completion happens in.
  122. */
  123. readonly state: EditorState;
  124. /**
  125. The position at which the completion is happening.
  126. */
  127. readonly pos: number;
  128. /**
  129. Indicates whether completion was activated explicitly, or
  130. implicitly by typing. The usual way to respond to this is to
  131. only return completions when either there is part of a
  132. completable entity before the cursor, or `explicit` is true.
  133. */
  134. readonly explicit: boolean;
  135. /**
  136. Create a new completion context. (Mostly useful for testing
  137. completion sources—in the editor, the extension will create
  138. these for you.)
  139. */
  140. constructor(
  141. /**
  142. The editor state that the completion happens in.
  143. */
  144. state: EditorState,
  145. /**
  146. The position at which the completion is happening.
  147. */
  148. pos: number,
  149. /**
  150. Indicates whether completion was activated explicitly, or
  151. implicitly by typing. The usual way to respond to this is to
  152. only return completions when either there is part of a
  153. completable entity before the cursor, or `explicit` is true.
  154. */
  155. explicit: boolean);
  156. /**
  157. Get the extent, content, and (if there is a token) type of the
  158. token before `this.pos`.
  159. */
  160. tokenBefore(types: readonly string[]): {
  161. from: number;
  162. to: number;
  163. text: string;
  164. type: _lezer_common.NodeType;
  165. } | null;
  166. /**
  167. Get the match of the given expression directly before the
  168. cursor.
  169. */
  170. matchBefore(expr: RegExp): {
  171. from: number;
  172. to: number;
  173. text: string;
  174. } | null;
  175. /**
  176. Yields true when the query has been aborted. Can be useful in
  177. asynchronous queries to avoid doing work that will be ignored.
  178. */
  179. get aborted(): boolean;
  180. /**
  181. Allows you to register abort handlers, which will be called when
  182. the query is
  183. [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
  184. */
  185. addEventListener(type: "abort", listener: () => void): void;
  186. }
  187. /**
  188. Given a a fixed array of options, return an autocompleter that
  189. completes them.
  190. */
  191. declare function completeFromList(list: readonly (string | Completion)[]): CompletionSource;
  192. /**
  193. Wrap the given completion source so that it will only fire when the
  194. cursor is in a syntax node with one of the given names.
  195. */
  196. declare function ifIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
  197. /**
  198. Wrap the given completion source so that it will not fire when the
  199. cursor is in a syntax node with one of the given names.
  200. */
  201. declare function ifNotIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
  202. /**
  203. The function signature for a completion source. Such a function
  204. may return its [result](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult)
  205. synchronously or as a promise. Returning null indicates no
  206. completions are available.
  207. */
  208. declare type CompletionSource = (context: CompletionContext) => CompletionResult | null | Promise<CompletionResult | null>;
  209. /**
  210. Interface for objects returned by completion sources.
  211. */
  212. interface CompletionResult {
  213. /**
  214. The start of the range that is being completed.
  215. */
  216. from: number;
  217. /**
  218. The end of the range that is being completed. Defaults to the
  219. main cursor position.
  220. */
  221. to?: number;
  222. /**
  223. The completions returned. These don't have to be compared with
  224. the input by the source—the autocompletion system will do its
  225. own matching (against the text between `from` and `to`) and
  226. sorting.
  227. */
  228. options: readonly Completion[];
  229. /**
  230. When given, further typing or deletion that causes the part of
  231. the document between ([mapped](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) `from`
  232. and `to` to match this regular expression or predicate function
  233. will not query the completion source again, but continue with
  234. this list of options. This can help a lot with responsiveness,
  235. since it allows the completion list to be updated synchronously.
  236. */
  237. validFor?: RegExp | ((text: string, from: number, to: number, state: EditorState) => boolean);
  238. /**
  239. By default, the library filters and scores completions. Set
  240. `filter` to `false` to disable this, and cause your completions
  241. to all be included, in the order they were given. When there are
  242. other sources, unfiltered completions appear at the top of the
  243. list of completions. `validFor` must not be given when `filter`
  244. is `false`, because it only works when filtering.
  245. */
  246. filter?: boolean;
  247. /**
  248. When [`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) is set to
  249. `false`, this may be provided to compute the ranges on the label
  250. that match the input. Should return an array of numbers where
  251. each pair of adjacent numbers provide the start and end of a
  252. range.
  253. */
  254. getMatch?: (completion: Completion) => readonly number[];
  255. /**
  256. Synchronously update the completion result after typing or
  257. deletion. If given, this should not do any expensive work, since
  258. it will be called during editor state updates. The function
  259. should make sure (similar to
  260. [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor)) that the
  261. completion still applies in the new state.
  262. */
  263. update?: (current: CompletionResult, from: number, to: number, context: CompletionContext) => CompletionResult | null;
  264. }
  265. /**
  266. This annotation is added to transactions that are produced by
  267. picking a completion.
  268. */
  269. declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
  270. /**
  271. Helper function that returns a transaction spec which inserts a
  272. completion's text in the main selection range, and any other
  273. selection range that has the same text in front of it.
  274. */
  275. declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
  276. /**
  277. Convert a snippet template to a function that can
  278. [apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
  279. using syntax like this:
  280. "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
  281. Each `${}` placeholder (you may also use `#{}`) indicates a field
  282. that the user can fill in. Its name, if any, will be the default
  283. content for the field.
  284. When the snippet is activated by calling the returned function,
  285. the code is inserted at the given position. Newlines in the
  286. template are indented by the indentation of the start line, plus
  287. one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
  288. the newline.
  289. On activation, (all instances of) the first field are selected.
  290. The user can move between fields with Tab and Shift-Tab as long as
  291. the fields are active. Moving to the last field or moving the
  292. cursor out of the current field deactivates the fields.
  293. The order of fields defaults to textual order, but you can add
  294. numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
  295. a custom order.
  296. To include a literal `${` or `#{` in your template, put a
  297. backslash after the dollar or hash and before the brace (`$\\{`).
  298. This will be removed and the sequence will not be interpreted as a
  299. placeholder.
  300. */
  301. declare function snippet(template: string): (editor: {
  302. state: EditorState;
  303. dispatch: (tr: Transaction) => void;
  304. }, _completion: Completion, from: number, to: number) => void;
  305. /**
  306. A command that clears the active snippet, if any.
  307. */
  308. declare const clearSnippet: StateCommand;
  309. /**
  310. Move to the next snippet field, if available.
  311. */
  312. declare const nextSnippetField: StateCommand;
  313. /**
  314. Move to the previous snippet field, if available.
  315. */
  316. declare const prevSnippetField: StateCommand;
  317. /**
  318. A facet that can be used to configure the key bindings used by
  319. snippets. The default binds Tab to
  320. [`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
  321. [`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
  322. to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
  323. */
  324. declare const snippetKeymap: Facet<readonly KeyBinding[], readonly KeyBinding[]>;
  325. /**
  326. Create a completion from a snippet. Returns an object with the
  327. properties from `completion`, plus an `apply` function that
  328. applies the snippet.
  329. */
  330. declare function snippetCompletion(template: string, completion: Completion): Completion;
  331. /**
  332. Returns a command that moves the completion selection forward or
  333. backward by the given amount.
  334. */
  335. declare function moveCompletionSelection(forward: boolean, by?: "option" | "page"): Command;
  336. /**
  337. Accept the current completion.
  338. */
  339. declare const acceptCompletion: Command;
  340. /**
  341. Explicitly start autocompletion.
  342. */
  343. declare const startCompletion: Command;
  344. /**
  345. Close the currently active completion.
  346. */
  347. declare const closeCompletion: Command;
  348. /**
  349. A completion source that will scan the document for words (using a
  350. [character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and
  351. return those as completions.
  352. */
  353. declare const completeAnyWord: CompletionSource;
  354. /**
  355. Configures bracket closing behavior for a syntax (via
  356. [language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt)) using the `"closeBrackets"`
  357. identifier.
  358. */
  359. interface CloseBracketConfig {
  360. /**
  361. The opening brackets to close. Defaults to `["(", "[", "{", "'",
  362. '"']`. Brackets may be single characters or a triple of quotes
  363. (as in `"''''"`).
  364. */
  365. brackets?: string[];
  366. /**
  367. Characters in front of which newly opened brackets are
  368. automatically closed. Closing always happens in front of
  369. whitespace. Defaults to `")]}:;>"`.
  370. */
  371. before?: string;
  372. }
  373. /**
  374. Extension to enable bracket-closing behavior. When a closeable
  375. bracket is typed, its closing bracket is immediately inserted
  376. after the cursor. When closing a bracket directly in front of a
  377. closing bracket inserted by the extension, the cursor moves over
  378. that bracket.
  379. */
  380. declare function closeBrackets(): Extension;
  381. /**
  382. Command that implements deleting a pair of matching brackets when
  383. the cursor is between them.
  384. */
  385. declare const deleteBracketPair: StateCommand;
  386. /**
  387. Close-brackets related key bindings. Binds Backspace to
  388. [`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
  389. */
  390. declare const closeBracketsKeymap: readonly KeyBinding[];
  391. /**
  392. Implements the extension's behavior on text insertion. If the
  393. given string counts as a bracket in the language around the
  394. selection, and replacing the selection with it requires custom
  395. behavior (inserting a closing version or skipping past a
  396. previously-closed bracket), this function returns a transaction
  397. representing that custom behavior. (You only need this if you want
  398. to programmatically insert brackets—the
  399. [`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
  400. take care of running this for user input.)
  401. */
  402. declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
  403. /**
  404. Returns an extension that enables autocompletion.
  405. */
  406. declare function autocompletion(config?: CompletionConfig): Extension;
  407. /**
  408. Basic keybindings for autocompletion.
  409. - Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
  410. - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
  411. - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
  412. - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
  413. - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
  414. - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
  415. - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
  416. */
  417. declare const completionKeymap: readonly KeyBinding[];
  418. /**
  419. Get the current completion status. When completions are available,
  420. this will return `"active"`. When completions are pending (in the
  421. process of being queried), this returns `"pending"`. Otherwise, it
  422. returns `null`.
  423. */
  424. declare function completionStatus(state: EditorState): null | "active" | "pending";
  425. /**
  426. Returns the available completions as an array.
  427. */
  428. declare function currentCompletions(state: EditorState): readonly Completion[];
  429. /**
  430. Return the currently selected completion, if any.
  431. */
  432. declare function selectedCompletion(state: EditorState): Completion | null;
  433. /**
  434. Returns the currently selected position in the active completion
  435. list, or null if no completions are active.
  436. */
  437. declare function selectedCompletionIndex(state: EditorState): number | null;
  438. /**
  439. Create an effect that can be attached to a transaction to change
  440. the currently selected completion.
  441. */
  442. declare function setSelectedCompletion(index: number): StateEffect<unknown>;
  443. export { CloseBracketConfig, Completion, CompletionContext, CompletionResult, CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };