Skip to content

Commit

Permalink
Add hasNext/PrevSnippetField getters
Browse files Browse the repository at this point in the history
FEATURE: The new `hasNextSnippetField` and `hasPrevSnippetField` functions
can be used to figure out if the snippet-field-motion commands apply to a
given state.

See https://discuss.codemirror.net/t/snippet-autocompletion-fields-count/6447
  • Loading branch information
marijnh committed May 10, 2023
1 parent 10de70e commit e5403a6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,12 @@

@nextSnippetField

@hasNextSnippetField

@prevSnippetField

@hasPrevSnippetField

@clearSnippet

@snippetKeymap
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {CompletionConfig, completionConfig} from "./config"
import {completionPlugin, moveCompletionSelection, acceptCompletion, startCompletion, closeCompletion} from "./view"
import {baseTheme} from "./theme"

export {snippet, snippetCompletion, nextSnippetField, prevSnippetField, clearSnippet, snippetKeymap} from "./snippet"
export {snippet, snippetCompletion, nextSnippetField, prevSnippetField,
hasNextSnippetField, hasPrevSnippetField, clearSnippet, snippetKeymap} from "./snippet"
export {Completion, CompletionSection, CompletionContext, CompletionSource, CompletionResult, pickedCompletion,
completeFromList, ifIn, ifNotIn, insertCompletionText} from "./completion"
export {startCompletion, closeCompletion, acceptCompletion, moveCompletionSelection} from "./view"
Expand Down
14 changes: 14 additions & 0 deletions src/snippet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,20 @@ export const nextSnippetField = moveField(1)
/// Move to the previous snippet field, if available.
export const prevSnippetField = moveField(-1)

/// Check if there is an active snippet with a next field for
/// `nextSnippetField` to move to.
export function hasNextSnippetField(state: EditorState) {
let active = state.field(snippetState, false)
return !!(active && active.ranges.some(r => r.field == active!.active + 1))
}

/// Returns true if there is an active snippet and a previous field
/// for `prevSnippetField` to move to.
export function hasPrevSnippetField(state: EditorState) {
let active = state.field(snippetState, false)
return !!(active && active.active > 0)
}

const defaultSnippetKeymap = [
{key: "Tab", run: nextSnippetField, shift: prevSnippetField},
{key: "Escape", run: clearSnippet}
Expand Down

0 comments on commit e5403a6

Please sign in to comment.