This commit is contained in:
2026-03-07 15:20:48 +01:00
parent 72faf32011
commit 5aa01f4dec
3 changed files with 22 additions and 41 deletions

View File

@@ -1,4 +1,5 @@
import { CompletionContext, CompletionResult } from '@codemirror/autocomplete'
import type { EditorState } from '@codemirror/state'
const NUNJUCKS_KEYWORDS = [
'if', 'endif', 'elif', 'else', 'for', 'endfor', 'in', 'and', 'or', 'not',
@@ -12,10 +13,15 @@ const NUNJUCKS_FILTERS = [
'trim', 'escape', 'safe', 'striptags', 'capitalize', 'reverse', 'batch', 'slice',
]
/** Get line text (CodeMirror 6: doc.line(n) is 1-based) */
function getLineText(state: EditorState, lineNo0Based: number): string {
return state.doc.line(lineNo0Based + 1).text
}
/** Detect if position is inside {{ or {% from the start of the line */
function insideNunjucks(doc: { getLine: (n: number) => string }, lineNo: number, pos: number): boolean {
const line = doc.getLine(lineNo)
const before = line.slice(0, pos)
function insideNunjucks(state: EditorState, lineNo0Based: number, posInLine: number): boolean {
const line = getLineText(state, lineNo0Based)
const before = line.slice(0, posInLine)
const openVar = before.lastIndexOf('{{')
const openTag = before.lastIndexOf('{%')
const closeVar = before.lastIndexOf('}}')
@@ -26,11 +32,11 @@ function insideNunjucks(doc: { getLine: (n: number) => string }, lineNo: number,
}
/** Get the word fragment before the cursor for matching */
function wordBefore(doc: { getLine: (n: number) => string }, lineNo: number, pos: number): string {
const line = doc.getLine(lineNo)
let start = pos
function wordBefore(state: EditorState, lineNo0Based: number, posInLine: number): string {
const line = getLineText(state, lineNo0Based)
let start = posInLine
while (start > 0 && /[\w.-]/.test(line[start - 1])) start -= 1
return line.slice(start, pos)
return line.slice(start, posInLine)
}
export function nunjucksCompletionSource(
@@ -41,9 +47,9 @@ export function nunjucksCompletionSource(
return (context: CompletionContext) => {
const { state, pos } = context
const line = state.doc.lineAt(pos)
if (!insideNunjucks(state.doc, line.number - 1, pos - line.from)) return null
if (!insideNunjucks(state, line.number - 1, pos - line.from)) return null
const word = wordBefore(state.doc, line.number - 1, pos - line.from)
const word = wordBefore(state, line.number - 1, pos - line.from)
const from = pos - word.length
const options: { label: string; type?: string; info?: string }[] = []