Diffdown is a real-time collaborative Markdown editor/previewer built on the AT Protocol
diffdown.com
1import * as _codemirror_state from '@codemirror/state';
2import { EditorState, ChangeDesc, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
3import { EditorView, Rect, KeyBinding, Command } from '@codemirror/view';
4import * as _lezer_common from '@lezer/common';
5
6/**
7Objects type used to represent individual completions.
8*/
9interface Completion {
10 /**
11 The label to show in the completion picker. This is what input
12 is matched against to determine whether a completion matches (and
13 how well it matches).
14 */
15 label: string;
16 /**
17 An optional override for the completion's visible label. When
18 using this, matched characters will only be highlighted if you
19 provide a [`getMatch`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.getMatch)
20 function.
21 */
22 displayLabel?: string;
23 /**
24 Overrides the text that is used to sort completions. Will
25 default to `label` if not given.
26 */
27 sortText?: string;
28 /**
29 An optional short piece of information to show (with a different
30 style) after the label.
31 */
32 detail?: string;
33 /**
34 Additional info to show when the completion is selected. Can be
35 a plain string or a function that'll render the DOM structure to
36 show when invoked.
37 */
38 info?: string | ((completion: Completion) => CompletionInfo | Promise<CompletionInfo>);
39 /**
40 How to apply the completion. The default is to replace it with
41 its [label](https://codemirror.net/6/docs/ref/#autocomplete.Completion.label). When this holds a
42 string, the completion range is replaced by that string. When it
43 is a function, that function is called to perform the
44 completion. If it fires a transaction, it is responsible for
45 adding the [`pickedCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.pickedCompletion)
46 annotation to it.
47 */
48 apply?: string | ((view: EditorView, completion: Completion, from: number, to: number) => void);
49 /**
50 The type of the completion. This is used to pick an icon to show
51 for the completion. Icons are styled with a CSS class created by
52 appending the type name to `"cm-completionIcon-"`. You can
53 define or restyle icons by defining these selectors. The base
54 library defines simple icons for `class`, `constant`, `enum`,
55 `function`, `interface`, `keyword`, `method`, `namespace`,
56 `property`, `text`, `type`, and `variable`.
57
58 Multiple types can be provided by separating them with spaces.
59 */
60 type?: string;
61 /**
62 When this option is selected, and one of these characters is
63 typed, insert the completion before typing the character.
64 */
65 commitCharacters?: readonly string[];
66 /**
67 When given, should be a number from -99 to 99 that adjusts how
68 this completion is ranked compared to other completions that
69 match the input as well as this one. A negative number moves it
70 down the list, a positive number moves it up.
71 */
72 boost?: number;
73 /**
74 Can be used to divide the completion list into sections.
75 Completions in a given section (matched by name) will be grouped
76 together, with a heading above them. Options without section
77 will appear above all sections. A string value is equivalent to
78 a `{name}` object.
79 */
80 section?: string | CompletionSection;
81}
82/**
83The type returned from
84[`Completion.info`](https://codemirror.net/6/docs/ref/#autocomplete.Completion.info). May be a DOM
85node, null to indicate there is no info, or an object with an
86optional `destroy` method that cleans up the node.
87*/
88type CompletionInfo = Node | null | {
89 dom: Node;
90 destroy?(): void;
91};
92/**
93Object used to describe a completion
94[section](https://codemirror.net/6/docs/ref/#autocomplete.Completion.section). It is recommended to
95create a shared object used by all the completions in a given
96section.
97*/
98interface CompletionSection {
99 /**
100 The name of the section. If no `render` method is present, this
101 will be displayed above the options.
102 */
103 name: string;
104 /**
105 An optional function that renders the section header. Since the
106 headers are shown inside a list, you should make sure the
107 resulting element has a `display: list-item` style.
108 */
109 header?: (section: CompletionSection) => HTMLElement;
110 /**
111 By default, sections are ordered alphabetically by name. To
112 specify an explicit order, `rank` can be used. Sections with a
113 lower rank will be shown above sections with a higher rank.
114
115 When set to `"dynamic"`, the section's position compared to
116 other dynamic sections depends on the matching score of the
117 best-matching option in the sections.
118 */
119 rank?: number | "dynamic";
120}
121/**
122An instance of this is passed to completion source functions.
123*/
124declare class CompletionContext {
125 /**
126 The editor state that the completion happens in.
127 */
128 readonly state: EditorState;
129 /**
130 The position at which the completion is happening.
131 */
132 readonly pos: number;
133 /**
134 Indicates whether completion was activated explicitly, or
135 implicitly by typing. The usual way to respond to this is to
136 only return completions when either there is part of a
137 completable entity before the cursor, or `explicit` is true.
138 */
139 readonly explicit: boolean;
140 /**
141 The editor view. May be undefined if the context was created
142 in a situation where there is no such view available, such as
143 in synchronous updates via
144 [`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
145 or when called by test code.
146 */
147 readonly view?: EditorView | undefined;
148 /**
149 Create a new completion context. (Mostly useful for testing
150 completion sources—in the editor, the extension will create
151 these for you.)
152 */
153 constructor(
154 /**
155 The editor state that the completion happens in.
156 */
157 state: EditorState,
158 /**
159 The position at which the completion is happening.
160 */
161 pos: number,
162 /**
163 Indicates whether completion was activated explicitly, or
164 implicitly by typing. The usual way to respond to this is to
165 only return completions when either there is part of a
166 completable entity before the cursor, or `explicit` is true.
167 */
168 explicit: boolean,
169 /**
170 The editor view. May be undefined if the context was created
171 in a situation where there is no such view available, such as
172 in synchronous updates via
173 [`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
174 or when called by test code.
175 */
176 view?: EditorView | undefined);
177 /**
178 Get the extent, content, and (if there is a token) type of the
179 token before `this.pos`.
180 */
181 tokenBefore(types: readonly string[]): {
182 from: number;
183 to: number;
184 text: string;
185 type: _lezer_common.NodeType;
186 } | null;
187 /**
188 Get the match of the given expression directly before the
189 cursor.
190 */
191 matchBefore(expr: RegExp): {
192 from: number;
193 to: number;
194 text: string;
195 } | null;
196 /**
197 Yields true when the query has been aborted. Can be useful in
198 asynchronous queries to avoid doing work that will be ignored.
199 */
200 get aborted(): boolean;
201 /**
202 Allows you to register abort handlers, which will be called when
203 the query is
204 [aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
205
206 By default, running queries will not be aborted for regular
207 typing or backspacing, on the assumption that they are likely to
208 return a result with a
209 [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
210 allows the result to be used after all. Passing `onDocChange:
211 true` will cause this query to be aborted for any document
212 change.
213 */
214 addEventListener(type: "abort", listener: () => void, options?: {
215 onDocChange: boolean;
216 }): void;
217}
218/**
219Given a a fixed array of options, return an autocompleter that
220completes them.
221*/
222declare function completeFromList(list: readonly (string | Completion)[]): CompletionSource;
223/**
224Wrap the given completion source so that it will only fire when the
225cursor is in a syntax node with one of the given names.
226*/
227declare function ifIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
228/**
229Wrap the given completion source so that it will not fire when the
230cursor is in a syntax node with one of the given names.
231*/
232declare function ifNotIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
233/**
234The function signature for a completion source. Such a function
235may return its [result](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult)
236synchronously or as a promise. Returning null indicates no
237completions are available.
238*/
239type CompletionSource = (context: CompletionContext) => CompletionResult | null | Promise<CompletionResult | null>;
240/**
241Interface for objects returned by completion sources.
242*/
243interface CompletionResult {
244 /**
245 The start of the range that is being completed.
246 */
247 from: number;
248 /**
249 The end of the range that is being completed. Defaults to the
250 main cursor position.
251 */
252 to?: number;
253 /**
254 The completions returned. These don't have to be compared with
255 the input by the source—the autocompletion system will do its
256 own matching (against the text between `from` and `to`) and
257 sorting.
258 */
259 options: readonly Completion[];
260 /**
261 When given, further typing or deletion that causes the part of
262 the document between ([mapped](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) `from`
263 and `to` to match this regular expression or predicate function
264 will not query the completion source again, but continue with
265 this list of options. This can help a lot with responsiveness,
266 since it allows the completion list to be updated synchronously.
267 */
268 validFor?: RegExp | ((text: string, from: number, to: number, state: EditorState) => boolean);
269 /**
270 By default, the library filters and scores completions. Set
271 `filter` to `false` to disable this, and cause your completions
272 to all be included, in the order they were given. When there are
273 other sources, unfiltered completions appear at the top of the
274 list of completions. `validFor` must not be given when `filter`
275 is `false`, because it only works when filtering.
276 */
277 filter?: boolean;
278 /**
279 When [`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) is set to
280 `false` or a completion has a
281 [`displayLabel`](https://codemirror.net/6/docs/ref/#autocomplete.Completion.displayLabel), this
282 may be provided to compute the ranges on the label that match
283 the input. Should return an array of numbers where each pair of
284 adjacent numbers provide the start and end of a range. The
285 second argument, the match found by the library, is only passed
286 when `filter` isn't `false`.
287 */
288 getMatch?: (completion: Completion, matched?: readonly number[]) => readonly number[];
289 /**
290 Synchronously update the completion result after typing or
291 deletion. If given, this should not do any expensive work, since
292 it will be called during editor state updates. The function
293 should make sure (similar to
294 [`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor)) that the
295 completion still applies in the new state.
296 */
297 update?: (current: CompletionResult, from: number, to: number, context: CompletionContext) => CompletionResult | null;
298 /**
299 When results contain position-dependent information in, for
300 example, `apply` methods, you can provide this method to update
301 the result for transactions that happen after the query. It is
302 not necessary to update `from` and `to`—those are tracked
303 automatically.
304 */
305 map?: (current: CompletionResult, changes: ChangeDesc) => CompletionResult | null;
306 /**
307 Set a default set of [commit
308 characters](https://codemirror.net/6/docs/ref/#autocomplete.Completion.commitCharacters) for all
309 options in this result.
310 */
311 commitCharacters?: readonly string[];
312}
313/**
314This annotation is added to transactions that are produced by
315picking a completion.
316*/
317declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
318/**
319Helper function that returns a transaction spec which inserts a
320completion's text in the main selection range, and any other
321selection range that has the same text in front of it.
322*/
323declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
324
325interface CompletionConfig {
326 /**
327 When enabled (defaults to true), autocompletion will start
328 whenever the user types something that can be completed.
329 */
330 activateOnTyping?: boolean;
331 /**
332 When given, if a completion that matches the predicate is
333 picked, reactivate completion again as if it was typed normally.
334 */
335 activateOnCompletion?: (completion: Completion) => boolean;
336 /**
337 The amount of time to wait for further typing before querying
338 completion sources via
339 [`activateOnTyping`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.activateOnTyping).
340 Defaults to 100, which should be fine unless your completion
341 source is very slow and/or doesn't use `validFor`.
342 */
343 activateOnTypingDelay?: number;
344 /**
345 By default, when completion opens, the first option is selected
346 and can be confirmed with
347 [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion). When this
348 is set to false, the completion widget starts with no completion
349 selected, and the user has to explicitly move to a completion
350 before you can confirm one.
351 */
352 selectOnOpen?: boolean;
353 /**
354 Override the completion sources used. By default, they will be
355 taken from the `"autocomplete"` [language
356 data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) (which should hold
357 [completion sources](https://codemirror.net/6/docs/ref/#autocomplete.CompletionSource) or arrays
358 of [completions](https://codemirror.net/6/docs/ref/#autocomplete.Completion)).
359 */
360 override?: readonly CompletionSource[] | null;
361 /**
362 Determines whether the completion tooltip is closed when the
363 editor loses focus. Defaults to true.
364 */
365 closeOnBlur?: boolean;
366 /**
367 The maximum number of options to render to the DOM.
368 */
369 maxRenderedOptions?: number;
370 /**
371 Set this to false to disable the [default completion
372 keymap](https://codemirror.net/6/docs/ref/#autocomplete.completionKeymap). (This requires you to
373 add bindings to control completion yourself. The bindings should
374 probably have a higher precedence than other bindings for the
375 same keys.)
376 */
377 defaultKeymap?: boolean;
378 /**
379 By default, completions are shown below the cursor when there is
380 space. Setting this to true will make the extension put the
381 completions above the cursor when possible.
382 */
383 aboveCursor?: boolean;
384 /**
385 When given, this may return an additional CSS class to add to
386 the completion dialog element.
387 */
388 tooltipClass?: (state: EditorState) => string;
389 /**
390 This can be used to add additional CSS classes to completion
391 options.
392 */
393 optionClass?: (completion: Completion) => string;
394 /**
395 By default, the library will render icons based on the
396 completion's [type](https://codemirror.net/6/docs/ref/#autocomplete.Completion.type) in front of
397 each option. Set this to false to turn that off.
398 */
399 icons?: boolean;
400 /**
401 This option can be used to inject additional content into
402 options. The `render` function will be called for each visible
403 completion, and should produce a DOM node to show. `position`
404 determines where in the DOM the result appears, relative to
405 other added widgets and the standard content. The default icons
406 have position 20, the label position 50, and the detail position
407 80.
408 */
409 addToOptions?: {
410 render: (completion: Completion, state: EditorState, view: EditorView) => Node | null;
411 position: number;
412 }[];
413 /**
414 By default, [info](https://codemirror.net/6/docs/ref/#autocomplete.Completion.info) tooltips are
415 placed to the side of the selected completion. This option can
416 be used to override that. It will be given rectangles for the
417 list of completions, the selected option, the info element, and
418 the availble [tooltip
419 space](https://codemirror.net/6/docs/ref/#view.tooltips^config.tooltipSpace), and should return
420 style and/or class strings for the info element.
421 */
422 positionInfo?: (view: EditorView, list: Rect, option: Rect, info: Rect, space: Rect) => {
423 style?: string;
424 class?: string;
425 };
426 /**
427 The comparison function to use when sorting completions with the same
428 match score. Defaults to using
429 [`localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare).
430 */
431 compareCompletions?: (a: Completion, b: Completion) => number;
432 /**
433 When set to true (the default is false), turn off fuzzy matching
434 of completions and only show those that start with the text the
435 user typed. Only takes effect for results where
436 [`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) isn't false.
437 */
438 filterStrict?: boolean;
439 /**
440 By default, commands relating to an open completion only take
441 effect 75 milliseconds after the completion opened, so that key
442 presses made before the user is aware of the tooltip don't go to
443 the tooltip. This option can be used to configure that delay.
444 */
445 interactionDelay?: number;
446 /**
447 When there are multiple asynchronous completion sources, this
448 controls how long the extension waits for a slow source before
449 displaying results from faster sources. Defaults to 100
450 milliseconds.
451 */
452 updateSyncTime?: number;
453}
454
455/**
456Convert a snippet template to a function that can
457[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
458using syntax like this:
459
460 "for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
461
462Each `${}` placeholder (you may also use `#{}`) indicates a field
463that the user can fill in. Its name, if any, will be the default
464content for the field.
465
466When the snippet is activated by calling the returned function,
467the code is inserted at the given position. Newlines in the
468template are indented by the indentation of the start line, plus
469one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
470the newline.
471
472On activation, (all instances of) the first field are selected.
473The user can move between fields with Tab and Shift-Tab as long as
474the fields are active. Moving to the last field or moving the
475cursor out of the current field deactivates the fields.
476
477The order of fields defaults to textual order, but you can add
478numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
479a custom order.
480
481To include a literal `{` or `}` in your template, put a backslash
482in front of it. This will be removed and the brace will not be
483interpreted as indicating a placeholder.
484*/
485declare function snippet(template: string): (editor: {
486 state: EditorState;
487 dispatch: (tr: Transaction) => void;
488}, completion: Completion | null, from: number, to: number) => void;
489/**
490A command that clears the active snippet, if any.
491*/
492declare const clearSnippet: StateCommand;
493/**
494Move to the next snippet field, if available.
495*/
496declare const nextSnippetField: StateCommand;
497/**
498Move to the previous snippet field, if available.
499*/
500declare const prevSnippetField: StateCommand;
501/**
502Check if there is an active snippet with a next field for
503`nextSnippetField` to move to.
504*/
505declare function hasNextSnippetField(state: EditorState): boolean;
506/**
507Returns true if there is an active snippet and a previous field
508for `prevSnippetField` to move to.
509*/
510declare function hasPrevSnippetField(state: EditorState): boolean;
511/**
512A facet that can be used to configure the key bindings used by
513snippets. The default binds Tab to
514[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
515[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
516to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
517*/
518declare const snippetKeymap: Facet<readonly KeyBinding[], readonly KeyBinding[]>;
519/**
520Create a completion from a snippet. Returns an object with the
521properties from `completion`, plus an `apply` function that
522applies the snippet.
523*/
524declare function snippetCompletion(template: string, completion: Completion): Completion;
525
526/**
527Returns a command that moves the completion selection forward or
528backward by the given amount.
529*/
530declare function moveCompletionSelection(forward: boolean, by?: "option" | "page"): Command;
531/**
532Accept the current completion.
533*/
534declare const acceptCompletion: Command;
535/**
536Explicitly start autocompletion.
537*/
538declare const startCompletion: Command;
539/**
540Close the currently active completion.
541*/
542declare const closeCompletion: Command;
543
544/**
545A completion source that will scan the document for words (using a
546[character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and
547return those as completions.
548*/
549declare const completeAnyWord: CompletionSource;
550
551/**
552Configures bracket closing behavior for a syntax (via
553[language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt)) using the `"closeBrackets"`
554identifier.
555*/
556interface CloseBracketConfig {
557 /**
558 The opening brackets to close. Defaults to `["(", "[", "{", "'",
559 '"']`. Brackets may be single characters or a triple of quotes
560 (as in `"'''"`).
561 */
562 brackets?: string[];
563 /**
564 Characters in front of which newly opened brackets are
565 automatically closed. Closing always happens in front of
566 whitespace. Defaults to `")]}:;>"`.
567 */
568 before?: string;
569 /**
570 When determining whether a given node may be a string, recognize
571 these prefixes before the opening quote.
572 */
573 stringPrefixes?: string[];
574}
575/**
576Extension to enable bracket-closing behavior. When a closeable
577bracket is typed, its closing bracket is immediately inserted
578after the cursor. When closing a bracket directly in front of a
579closing bracket inserted by the extension, the cursor moves over
580that bracket.
581*/
582declare function closeBrackets(): Extension;
583/**
584Command that implements deleting a pair of matching brackets when
585the cursor is between them.
586*/
587declare const deleteBracketPair: StateCommand;
588/**
589Close-brackets related key bindings. Binds Backspace to
590[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
591*/
592declare const closeBracketsKeymap: readonly KeyBinding[];
593/**
594Implements the extension's behavior on text insertion. If the
595given string counts as a bracket in the language around the
596selection, and replacing the selection with it requires custom
597behavior (inserting a closing version or skipping past a
598previously-closed bracket), this function returns a transaction
599representing that custom behavior. (You only need this if you want
600to programmatically insert brackets—the
601[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
602take care of running this for user input.)
603*/
604declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
605
606/**
607Returns an extension that enables autocompletion.
608*/
609declare function autocompletion(config?: CompletionConfig): Extension;
610/**
611Basic keybindings for autocompletion.
612
613 - Ctrl-Space (and Alt-\` or Alt-i on macOS): [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
614 - Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
615 - ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
616 - ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
617 - PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
618 - PageUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false, "page")`
619 - Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
620*/
621declare const completionKeymap: readonly KeyBinding[];
622/**
623Get the current completion status. When completions are available,
624this will return `"active"`. When completions are pending (in the
625process of being queried), this returns `"pending"`. Otherwise, it
626returns `null`.
627*/
628declare function completionStatus(state: EditorState): null | "active" | "pending";
629/**
630Returns the available completions as an array.
631*/
632declare function currentCompletions(state: EditorState): readonly Completion[];
633/**
634Return the currently selected completion, if any.
635*/
636declare function selectedCompletion(state: EditorState): Completion | null;
637/**
638Returns the currently selected position in the active completion
639list, or null if no completions are active.
640*/
641declare function selectedCompletionIndex(state: EditorState): number | null;
642/**
643Create an effect that can be attached to a transaction to change
644the currently selected completion.
645*/
646declare function setSelectedCompletion(index: number): StateEffect<unknown>;
647
648export { type CloseBracketConfig, type Completion, CompletionContext, type CompletionInfo, type CompletionResult, type CompletionSection, type CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };