Files
SillyTavern/public/scripts/autocomplete/EnhancedMacroAutoCompleteOption.js
T
WolfsblvtandCohee e9bedadc0b Macros 2.0 (v0.4) - Add scoped macros (last arg can be scoped), {{if}} macro and macro flags (baseline implementation) (#4913)
* Macros: make category optional, default to UNCATEGORIZED

* Tests: Update macro tests to match new error handling behavior

- Change MacroRegistry tests from expecting thrown errors to capturing console.error logs
- Update MacroLexer tests to expect plaintext fallback instead of lexer errors for invalid tokens
- Fix MacroEngine test to use `char` macro instead of `newline` for arity validation
- Update MacroParser test with corrected expected error message for invalid identifiers
- Remove "[Error]" prefixes from test descriptions where lexer no longer errors

* Macros: Implement macro execution flags system

- Add MacroFlags module with flag parsing and validation (!, ?, ~, /, >, ., $, #)
- Update lexer to tokenize flags as separate tokens before macro identifier
- Modify parser to capture flags in CST under 'flags' label
- Update CST walker to parse flag tokens into MacroFlags object
- Pass parsed flags to macro handlers via MacroCall and MacroContext
- Update autocomplete parser to handle flags before identifier
- Add comprehensive tests for flag parsing,

* Macros: Fix autocomplete positioning for macros with flags and whitespace

- Add identifierStart to parseMacroContext to track where identifier begins in macro text
- Update autocomplete to use identifierStart for correct range calculation
- Simplify indexMacros regex to use global flag instead of manual loop
- Use parseMacroContext in indexMacros to extract identifier (handles flags/whitespace)
- Fix autocomplete range starting at wrong position when flags or whitespace present

* Macros: Add autocomplete support for macro execution flags

- Add MacroFlagAutoCompleteOption class for rendering flag options in autocomplete
- Extend parseMacroContext to track currentFlag (flag cursor is on) and isInFlagsArea
- Track flagEndPositions to determine which flag cursor is currently typing
- Update #buildEnhancedMacroOptions to show flag options when cursor is in flags area
- Show current flag first if cursor just typed it, then show remaining available flags
- Add renderItem and renderDetails methods to MacroFlag

* Macros: Implement scoped macro syntax with opening and closing tags

- Add scoped macro processing to MacroCstWalker to find and merge opening/closing pairs
- Parse closing block flag (/) to identify closing macros and match with opening tags
- Extract content between opening and closing tags as the last unnamed argument
- Add `isScoped` property to MacroCall and MacroContext to track scoped invocations
- Implement `#processScopedMacros` to find outermost matching pairs and handle nesting

* Macros: Add autocomplete warnings, scoped content info, and closing tag suggestions

- Add arity warning banners in autocomplete details for invalid argument counts
- Show warning when using space-separated args on multi-arg or no-arg macros
- Add scoped content info banner when cursor is inside unclosed scoped macro
- Implement MacroClosingTagAutoCompleteOption to suggest closing tags for scoped macros
- Add sortPriority property to AutoCompleteOption for controlling sort order

* SlashCommands: Disable unimplemented flags and closing flag when no unclosed scopes in autocomplete

- Set closing block flag as non-selectable when no unclosed scopes exist
- Set unimplemented flags as non-selectable with empty valueProvider
- Lower sort priority (12) for non-selectable flags vs selectable flags (10)

* Autocomplete: Show scoped content info and auto-close no-arg macros

- Show scoped content info when cursor is at closing }} of unclosed scoped macro
- Auto-complete no-arg macros with closing }} using valueProvider
- Trigger autocomplete on select (isSelect) to refresh after choosing an option
- Simplify MacroFlagAutoCompleteOption to use base makeItem for consistent styling
- Change closing tag icon from '{/}' to '{/' for better visual consistency

* Macros: Add scoped trim macro to trim content inside opening/closing tags

- Add scoped usage for {{trim}}content{{/trim}} to trim whitespace from content
- Keep non-scoped {{trim}} behavior (post-processing marker) for backward compatibility
- Add optional unnamed 'content' argument for scoped usage
- Update description to explain both scoped and non-scoped behavior
- Handler checks isScoped flag to determine which behavior to use

* Autocomplete: Fix closing tag parsing to prevent `/` being treated as flag

- Add special case in parseMacroContext to detect closing tags (`/` + identifier char)
- Stop flag parsing when `/` is followed by identifier character (closing tag syntax)
- Simplify MacroClosingTagAutoCompleteOption valueProvider to return full closing tag
- Remove input-based logic since autocomplete replaces entire identifier

* Macros: Add {{if}} conditional macro with auto-resolution of macro names

- Add {{if condition}}content{{/if}} macro to conditionally show content
- Auto-resolve condition if it matches a registered macro name (0 required args)
- Support both scoped content ({{if x}}...{{/if}}) and explicit args ({{if::x::content}})
- Treat empty string, "false", "off", "0" as falsy conditions
- Inherit environment context when resolving macro names
- Update autocomplete warning to allow space-separated syntax

* Macros: Add centralized identifier validation with pattern enforcement

- Export MACRO_IDENTIFIER_PATTERN from MacroLexer for reuse across modules
- Add isIdentifierValid() helper function to validate macro names and aliases
- Enforce identifier pattern: must start with letter, followed by word chars or hyphens
- Update macro registration to validate both primary names and alias identifiers
- Improve error messages to explain identifier requirements
- Add comprehensive e2e tests for valid/invalid identifier patterns

* Macros: Add tests for scoped {{trim}} macro functionality

* SlashCommands: Fix macro indexing to properly handle nested macros with brace depth tracking

- Replace regex-based macro detection with manual brace depth tracking
- Track opening/closing brace pairs to correctly identify macro boundaries
- Ensure nested macros like {{reverse::Hey {{user}}}} are properly indexed
- Index both outer and inner macros by scanning content recursively
- Handle unclosed macros by defaulting to end of text

* Macros: Add {{else}} branch support to {{if}} conditional macro

- Add {{else}} macro as marker to split then/else branches in {{if}} blocks
- Use control character sequence (\u0000\u001FELSE\u001F\u0000) as internal marker
- Split scoped content on else marker and trim both branches independently
- Return then-branch if condition is truthy, else-branch if falsy
- Auto-suggest {{else}} in autocomplete when inside scoped {{if}} block
- Make {{else}} non-selectable in autocomplete when outside {{if}} scope

* Macros: Add negation support to {{if}} conditional macro with ! prefix

- Add ! prefix support to invert condition evaluation in {{if}} macro
- Parse original macro text to detect ! prefix before macro resolution
- Strip ! from condition after detecting inversion to avoid double-negation
- Invert isFalsy result when ! prefix is detected in original condition
- Prevent ! in resolved values from triggering inversion (only original syntax)

* Autocomplete: Add {{if}} condition autocomplete with zero-arg macro suggestions

- Add EnhancedMacroAutoCompleteOptions typedef for noBraces/paddingAfter/closeWithBraces options
- Support options object in EnhancedMacroAutoCompleteOption constructor alongside context
- Add noBraces mode to display macro names without {{ }} braces (for use as values)
- Add paddingAfter option to match opening whitespace style before closing }}

* Autocomplete: Match opening whitespace padding when auto-closing macros

* Fix `{{if}}` example usages

* Macros: Hide `comment` alias from autocomplete suggestions for `//` macro

* Macros: Simplify {{trim}} handler with destructured parameters and clearer content check

* Macros: Use MacroEngine.evaluate for zero-arg macro resolution in {{if}} condition handler

* Macros: Add auto-trim for scoped content with # flag to preserve whitespace

- Auto-trim scoped content by default in MacroCstWalker before passing to handlers
- Add preserveWhitespace flag (# symbol) to prevent auto-trimming when needed
- Rename legacyHash flag to preserveWhitespace across engine and definitions
- Update {{trim}} handler to rely on engine auto-trim for scoped content
- Update {{if}} handler to respect # flag when trimming branches around {{else}} marker

* Macros: Clarify macro name validation error message to use "alphanumeric characters" instead of "word chars"

* Add 'setspriteoverride' optional 'name' argument

* Refactor ElevenLabs TTS API key handling (#4906)

* Refactor ElevenLabs TTS API key handling #4483

* Remove unused connection button and related event handler from ElevenLabs TTS provider

* Add ElevenLabs STT endpoint

* Add caching system prompt feature for OpenRouter Gemini (#4903)

* feat: add caching system prompt for OpenRouter Gemini

* fix: resolve reviews

* Update GitHub links to llama.cpp

* Add model selection support for llama.cpp router mode (#4910)

* Add model selection support for llama.cpp router mode

- Add llamacpp_model setting to textgen-settings.js
- Implement loadLlamaCppModels() function to fetch and populate models
- Add onLlamaCppModelSelect() handler for model selection
- Update status check to load llama.cpp models when connecting
- Update getTextGenModel() to return selected llama.cpp model
- Add model dropdown to HTML UI in llama.cpp section
- Initialize event handlers and Select2 for better UX
- Add llamacpp_model to preset manager for save/load support
- Add llamacpp_model to slash commands support

This implements model selection for llama.cpp router mode, allowing
users to select from multiple models without restarting the server.
Follows the same pattern as Ollama, Tabby, and vLLM implementations.

* Correct spelling

* Fix clear selection position

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>

* Add glm-4.7 model option and context mapping for Z.AI

* Add select2 style for NanoGPT list
Closes #4911

* Disable macro engine init traces

* Update type annotations for instruct presets and context presets

* Fix test for new error text

* Add MacroStoryString tests

* Add trimContent utility for consistent indentation dedenting in scoped macros

- Add trimScopedContent method to MacroEngine that trims and dedents scoped content based on first non-empty line indentation
- Pass trimContent utility through evaluation context to all macro handlers
- Update {{if}} macro to use trimContent instead of direct trim() call
- Update auto-trim logic in MacroCstWalker to use trimContent for consistent dedenting
- Add trimContent to MacroExecutionContext type definitions

* Add ELSE_MARKER export and cleanup leftover markers in macro processing

* Update trimContent parameter to use options object pattern in JSDoc

* Add processor registration system to MacroEngine with priority-based execution

- Add MacroProcessor callback and RegisteredProcessor typedef for pre/post processors
- Add addPreProcessor/removePreProcessor and addPostProcessor/removePostProcessor methods with priority-based sorting
- Refactor core legacy syntax handling into registered processors with reserved priorities (0-50)
- Move legacy time syntax, marker replacements, brace unescaping, trim macro, and ELSE_MARKER cleanup to registered processors

* Split core processor registration into separate pre and post processor methods

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-12-28 21:36:13 +02:00

730 lines
28 KiB
JavaScript

/**
* Enhanced macro autocomplete option for the new MacroRegistry-based system.
* Reuses rendering logic from MacroBrowser for consistency and DRY.
*/
import { AutoCompleteOption } from './AutoCompleteOption.js';
import {
formatMacroSignature,
createSourceIndicator,
createAliasIndicator,
renderMacroDetails,
} from '../macros/MacroBrowser.js';
import { enumIcons } from '../slash-commands/SlashCommandCommonEnumsProvider.js';
import { ValidFlagSymbols } from '../macros/engine/MacroFlags.js';
/** @typedef {import('../macros/engine/MacroRegistry.js').MacroDefinition} MacroDefinition */
/**
* Macro context passed from the parser to provide cursor position info.
* @typedef {Object} MacroAutoCompleteContext
* @property {string} fullText - The full macro text being typed (without {{ }}).
* @property {number} cursorOffset - Cursor position within the macro text.
* @property {string} paddingBefore - Padding before the macro identifier/flags.
* @property {string} identifier - The macro identifier (name).
* @property {number} identifierStart - Start position of the identifier within the macro text.
* @property {string[]} flags - Array of flag symbols typed (e.g., ['!', '?']).
* @property {string|null} currentFlag - The flag symbol cursor is currently on (last typed flag), or null.
* @property {boolean} isInFlagsArea - Whether cursor is in the flags area (before identifier starts).
* @property {string[]} args - Array of arguments typed so far.
* @property {number} currentArgIndex - Index of the argument being typed (-1 if on identifier).
* @property {boolean} isTypingSeparator - Whether cursor is on a partial separator (single ':').
* @property {boolean} hasSpaceAfterIdentifier - Whether there's a space after the identifier (for space-separated args).
* @property {boolean} hasSpaceArgContent - Whether there's actual content after the space (not just whitespace).
* @property {number} separatorCount - Number of '::' separators found.
* @property {boolean} [isInScopedContent] - Whether cursor is in scoped content (after }} but before closing tag).
* @property {string} [scopedMacroName] - Name of the scoped macro if in scoped content.
*/
/**
* @typedef {Object} EnhancedMacroAutoCompleteOptions
* @property {boolean} [noBraces=false] - If true, display without {{ }} braces (for use as values, e.g., in {{if}} conditions).
* @property {string} [paddingAfter=''] - Whitespace to add before closing }} (for matching opening whitespace style).
* @property {boolean} [closeWithBraces=false] - If true, the completion will add }} to close the macro.
*/
export class EnhancedMacroAutoCompleteOption extends AutoCompleteOption {
/** @type {MacroDefinition} */
#macro;
/** @type {MacroAutoCompleteContext|null} */
#context = null;
/** @type {boolean} */
#noBraces = false;
/** @type {string} */
#paddingAfter = '';
/**
* @param {MacroDefinition} macro - The macro definition from MacroRegistry.
* @param {MacroAutoCompleteContext|EnhancedMacroAutoCompleteOptions|null} [contextOrOptions] - Context for argument hints, or options object.
*/
constructor(macro, contextOrOptions = null) {
// Use the macro name as the autocomplete key
super(macro.name, enumIcons.macro);
this.#macro = macro;
// Detect if second argument is context or options
// Context has 'identifier' property, options may have 'noBraces'
if (contextOrOptions && typeof contextOrOptions === 'object') {
if ('noBraces' in contextOrOptions || 'paddingAfter' in contextOrOptions || 'closeWithBraces' in contextOrOptions) {
// It's an options object
const options = /** @type {EnhancedMacroAutoCompleteOptions} */ (contextOrOptions);
this.#noBraces = options.noBraces ?? false;
this.#paddingAfter = options.paddingAfter ?? '';
// If noBraces mode with closeWithBraces, complete with name + padding + }}
if (options.closeWithBraces) {
this.valueProvider = () => `${macro.name}${this.#paddingAfter}}}`;
this.makeSelectable = true;
}
} else {
// It's a context object
this.#context = /** @type {MacroAutoCompleteContext} */ (contextOrOptions);
}
}
// nameOffset = 2 to skip the {{ prefix in the display (formatMacroSignature includes braces)
// When noBraces is true, nameOffset = 0 since we don't show braces
this.nameOffset = this.#noBraces ? 0 : 2;
// For macros that take no arguments, auto-complete with closing }} (unless already set by options)
if (!this.valueProvider) {
const takesNoArgs = macro.minArgs === 0 && macro.maxArgs === 0 && macro.list === null;
if (takesNoArgs) {
this.valueProvider = () => `${macro.name}${this.#paddingAfter}}}`;
this.makeSelectable = true; // Required when using valueProvider
}
}
}
/** @returns {MacroDefinition} */
get macro() {
return this.#macro;
}
/**
* Renders the list item for the autocomplete dropdown.
* Tight display: [icon] [signature] [description] [alias icon?] [source icon]
* @returns {HTMLElement}
*/
renderItem() {
const li = document.createElement('li');
li.classList.add('item', 'macro-ac-item');
li.setAttribute('data-name', this.name);
li.setAttribute('data-option-type', 'macro');
// Type icon
const type = document.createElement('span');
type.classList.add('type', 'monospace');
type.textContent = '{}';
li.append(type);
// Specs container (for fuzzy highlight compatibility)
const specs = document.createElement('span');
specs.classList.add('specs');
// Name with character spans for fuzzy highlighting
const nameEl = document.createElement('span');
nameEl.classList.add('name', 'monospace');
// Build signature with individual character spans
// When noBraces is true, show just the macro name without {{ }}
const sigText = this.#noBraces ? this.#macro.name : formatMacroSignature(this.#macro);
for (const char of sigText) {
const span = document.createElement('span');
span.textContent = char;
nameEl.append(span);
}
specs.append(nameEl);
li.append(specs);
// Stopgap (spacer for flex layout)
const stopgap = document.createElement('span');
stopgap.classList.add('stopgap');
li.append(stopgap);
// Help text (description)
const help = document.createElement('span');
help.classList.add('help');
const content = document.createElement('span');
content.classList.add('helpContent');
content.textContent = this.#macro.description || '';
help.append(content);
li.append(help);
// Alias indicator icon (if this is an alias)
const aliasIcon = createAliasIndicator(this.#macro);
if (aliasIcon) {
aliasIcon.classList.add('macro-ac-indicator');
li.append(aliasIcon);
}
// Source indicator icon
const sourceIcon = createSourceIndicator(this.#macro);
sourceIcon.classList.add('macro-ac-indicator');
li.append(sourceIcon);
return li;
}
/**
* Renders the details panel content.
* Reuses renderMacroDetails from MacroBrowser with autocomplete-specific options.
* @returns {DocumentFragment}
*/
renderDetails() {
const frag = document.createDocumentFragment();
// Check for arity warnings
const warning = this.#getArityWarning();
if (warning) {
const warningEl = this.#renderWarning(warning);
frag.append(warningEl);
}
// Show scoped content info banner if we're in scoped content
if (this.#context?.isInScopedContent) {
const scopedInfo = this.#renderScopedContentInfo();
if (scopedInfo) frag.append(scopedInfo);
}
// Determine current argument index for highlighting
const currentArgIndex = this.#context?.currentArgIndex ?? -1;
// Render argument hint banner if we're typing an argument (and no warning)
if (!warning && currentArgIndex >= 0) {
const hint = this.#renderArgumentHint();
if (hint) frag.append(hint);
}
// Reuse MacroBrowser's renderMacroDetails with options
// Don't highlight args if there's a warning
const details = renderMacroDetails(this.#macro, { currentArgIndex: warning ? -1 : currentArgIndex });
// Add class for autocomplete-specific styling overrides
details.classList.add('macro-ac-details');
frag.append(details);
return frag;
}
/**
* Checks for arity-related warnings based on the current context.
* @returns {string|null} Warning message, or null if no warning.
*/
#getArityWarning() {
if (!this.#context) return null;
const argCount = this.#context.args.length;
const maxArgs = this.#macro.maxArgs;
//const minArgs = this.#macro.minArgs;
const hasList = this.#macro.list !== null;
// Check for too many arguments (only if no list args)
if (!hasList && argCount > maxArgs) {
return `Too many arguments: this macro accepts ${maxArgs === 0 ? 'no arguments' : `up to ${maxArgs} argument${maxArgs === 1 ? '' : 's'}`}, but ${argCount} provided.`;
}
// Check for space-separated arg on macro that doesn't support it
// Space-separated syntax provides 1 arg; with scoped content you can provide a 2nd arg
// So it's valid for macros with maxArgs <= 2 (or with list args)
if (this.#context.hasSpaceArgContent) {
if (maxArgs === 0) {
return 'This macro does not accept any arguments. Remove the space or use a different macro.';
}
if (!hasList && maxArgs > 2) {
return `Space-separated syntax only works for macros with up to 2 arguments. Use :: separators instead: {{${this.#macro.name}::arg1::arg2}}`;
}
}
// Check if trying to add args to a no-arg macro via ::
if (this.#context.separatorCount > 0 && maxArgs === 0) {
return 'This macro does not accept any arguments.';
}
return null;
}
/**
* Renders a warning banner.
* @param {string} message - The warning message.
* @returns {HTMLElement}
*/
#renderWarning(message) {
const warning = document.createElement('div');
warning.classList.add('macro-ac-warning');
const icon = document.createElement('i');
icon.classList.add('fa-solid', 'fa-triangle-exclamation');
warning.append(icon);
const text = document.createElement('span');
text.textContent = message;
warning.append(text);
return warning;
}
/**
* Renders the scoped content info banner.
* Shows when cursor is inside scoped content of an unclosed macro.
* @returns {HTMLElement|null}
*/
#renderScopedContentInfo() {
if (!this.#context?.isInScopedContent) return null;
const info = document.createElement('div');
info.classList.add('macro-ac-scoped-info');
const icon = document.createElement('i');
icon.classList.add('fa-solid', 'fa-layer-group');
info.append(icon);
const text = document.createElement('span');
text.innerHTML = `Typing <strong>scoped content</strong> for <code>{{${this.#context.scopedMacroName}}}</code>. Close with <code>{{/${this.#context.scopedMacroName}}}</code>`;
info.append(text);
return info;
}
/**
* Renders the current argument hint banner.
* @returns {HTMLElement|null}
*/
#renderArgumentHint() {
if (!this.#context || this.#context.currentArgIndex < 0) return null;
const argIndex = this.#context.currentArgIndex;
const isListArg = argIndex >= this.#macro.maxArgs;
// If we're beyond unnamed args and there's no list, no hint
if (isListArg && !this.#macro.list) return null;
const hint = document.createElement('div');
hint.classList.add('macro-ac-arg-hint');
const icon = document.createElement('i');
icon.classList.add('fa-solid', 'fa-arrow-right');
hint.append(icon);
if (isListArg) {
// List argument hint
const listIndex = argIndex - this.#macro.maxArgs + 1;
const text = document.createElement('span');
text.innerHTML = `<strong>List item ${listIndex}</strong>`;
hint.append(text);
} else {
// Unnamed argument hint (required or optional)
const argDef = this.#macro.unnamedArgDefs[argIndex];
let optionalLabel = '';
if (argDef?.optional) {
optionalLabel = argDef.defaultValue !== undefined
? ` <em>(optional, default: ${argDef.defaultValue === '' ? '<empty string>' : argDef.defaultValue})</em>`
: ' <em>(optional)</em>';
}
const text = document.createElement('span');
text.innerHTML = `<strong>${argDef?.name || `Argument ${argIndex + 1}`}</strong>${optionalLabel}`;
if (argDef?.type) {
const typeSpan = document.createElement('code');
typeSpan.classList.add('macro-ac-hint-type');
if (Array.isArray(argDef.type)) {
typeSpan.textContent = argDef.type.join(' | ');
typeSpan.title = `Accepts: ${argDef.type.join(', ')}`;
} else {
typeSpan.textContent = argDef.type;
}
text.append(' ', typeSpan);
}
hint.append(text);
if (argDef?.description) {
const descSpan = document.createElement('span');
descSpan.classList.add('macro-ac-hint-desc');
descSpan.textContent = ` — ${argDef.description}`;
hint.append(descSpan);
}
if (argDef?.sampleValue) {
const sampleSpan = document.createElement('span');
sampleSpan.classList.add('macro-ac-hint-sample');
sampleSpan.textContent = ` (e.g. ${argDef.sampleValue})`;
hint.append(sampleSpan);
}
}
return hint;
}
}
/**
* Autocomplete option for macro execution flags.
* Shows flag symbol, name, and description.
* Uses default AutoCompleteOption rendering for consistent styling.
*/
export class MacroFlagAutoCompleteOption extends AutoCompleteOption {
/** @type {import('../macros/engine/MacroFlags.js').MacroFlagDefinition} */
#flagDef;
/**
* @param {import('../macros/engine/MacroFlags.js').MacroFlagDefinition} flagDef - The flag definition.
*/
constructor(flagDef) {
// Use the flag symbol as the name, with a flag icon
// Display name includes both symbol and name for clarity
super(flagDef.type, '🚩');
this.#flagDef = flagDef;
}
/** @returns {import('../macros/engine/MacroFlags.js').MacroFlagDefinition} */
get flagDefinition() {
return this.#flagDef;
}
/**
* Renders the autocomplete list item for this flag.
* Uses the same structure as other autocomplete options for consistent styling.
* @returns {HTMLElement}
*/
renderItem() {
// Use base class makeItem for consistent styling
const li = this.makeItem(
`${this.#flagDef.type} ${this.#flagDef.name}`, // Display: "? Optional"
'🚩',
true, // noSlash
[], // namedArguments
[], // unnamedArguments
'void', // returnType
this.#flagDef.description + (this.#flagDef.implemented ? '' : ' (planned)'), // helpString
);
li.setAttribute('data-name', this.name);
li.setAttribute('data-option-type', 'flag');
return li;
}
/**
* Renders the details panel for this flag.
* @returns {DocumentFragment}
*/
renderDetails() {
const frag = document.createDocumentFragment();
const details = document.createElement('div');
details.classList.add('macro-flag-details');
// Header with flag symbol and name
const header = document.createElement('h3');
header.classList.add('macro-flag-details-header');
header.innerHTML = `<code>${this.#flagDef.type}</code> ${this.#flagDef.name} Flag`;
details.append(header);
// Description
const desc = document.createElement('p');
desc.classList.add('macro-flag-details-desc');
desc.textContent = this.#flagDef.description;
details.append(desc);
// Status
const status = document.createElement('p');
status.classList.add('macro-flag-details-status');
status.innerHTML = `<strong>Status:</strong> ${this.#flagDef.implemented ? 'Implemented' : 'Planned for future release'}`;
details.append(status);
// Parser effect note
if (this.#flagDef.affectsParser) {
const parserNote = document.createElement('p');
parserNote.classList.add('macro-flag-details-note');
parserNote.innerHTML = '<em>This flag affects how the macro is parsed.</em>';
details.append(parserNote);
}
frag.append(details);
return frag;
}
}
/**
* Autocomplete option for closing a scoped macro.
* Suggests {{/macroName}} to close an unclosed scoped macro.
*/
export class MacroClosingTagAutoCompleteOption extends AutoCompleteOption {
/** @type {string} */
#macroName;
/**
* @param {string} macroName - The name of the macro to close.
*/
constructor(macroName) {
// The closing tag is what we're suggesting - use /macroName as the name for matching
const closingTag = `/${macroName}`;
super(closingTag, '{/');
this.#macroName = macroName;
// Custom valueProvider to return the correct replacement text
// Autocomplete REPLACES the typed identifier entirely, so return the full closing tag
this.valueProvider = () => {
// Return full closing tag content (without {{ since that's before the identifier)
return `/${macroName}}}`;
};
// Make selectable so TAB completion works (valueProvider alone makes it non-selectable)
this.makeSelectable = true;
// Highest priority - closing tags should always appear at the very top
this.sortPriority = 1;
}
/** @returns {string} */
get macroName() {
return this.#macroName;
}
/**
* Renders the autocomplete list item for this closing tag.
* Uses the same structure as other macro options for consistent styling.
* @returns {HTMLElement}
*/
renderItem() {
const li = document.createElement('li');
li.classList.add('item', 'macro-ac-item');
// Type icon (same column as other macros)
const type = document.createElement('span');
type.classList.add('type', 'monospace');
type.textContent = this.typeIcon;
li.append(type);
// Specs container (for fuzzy highlight compatibility)
const specs = document.createElement('span');
specs.classList.add('specs');
// Name element with character spans
const nameEl = document.createElement('span');
nameEl.classList.add('name', 'monospace');
// Display full closing tag like other macros show full syntax
const displayName = `{{/${this.#macroName}}}`;
for (const char of displayName) {
const span = document.createElement('span');
span.textContent = char;
nameEl.append(span);
}
specs.append(nameEl);
li.append(specs);
// Stopgap (spacer for flex layout)
const stopgap = document.createElement('span');
stopgap.classList.add('stopgap');
li.append(stopgap);
// Help text (description)
const help = document.createElement('span');
help.classList.add('help');
const content = document.createElement('span');
content.classList.add('helpContent');
content.textContent = `Close the {{${this.#macroName}}} scoped macro.`;
help.append(content);
li.append(help);
return li;
}
/**
* Renders the details panel for this closing tag.
* @returns {DocumentFragment}
*/
renderDetails() {
const frag = document.createDocumentFragment();
const details = document.createElement('div');
details.classList.add('macro-closing-tag-details');
// Header
const header = document.createElement('h3');
header.innerHTML = `Close <code>{{${this.#macroName}}}</code>`;
details.append(header);
// Description
const desc = document.createElement('p');
desc.textContent = `Inserts the closing tag {{/${this.#macroName}}} to complete the scoped macro. The content between the opening and closing tags will be passed as the last argument.`;
details.append(desc);
frag.append(details);
return frag;
}
}
/**
* Parses the macro text to determine current argument context.
* Handles leading whitespace and flags before the identifier.
*
* @param {string} macroText - The text inside {{ }}, e.g., "roll::1d20" or "!user" or " description ".
* @param {number} cursorOffset - Cursor position within macroText.
* @returns {MacroAutoCompleteContext}
*/
export function parseMacroContext(macroText, cursorOffset) {
let i = 0;
// Skip leading whitespace
while (i < macroText.length && /\s/.test(macroText[i])) {
i++;
}
// Extract flags (special symbols before the identifier)
// Track position after each flag to determine which flag cursor is on
// Special case: `/` followed by identifier chars is a closing tag, not a flag
const flags = [];
const flagEndPositions = []; // Position right after each flag (before any whitespace)
while (i < macroText.length) {
const char = macroText[i];
// Check if this looks like a closing tag: `/` followed by an identifier character
if (char === '/' && i + 1 < macroText.length && /[a-zA-Z_]/.test(macroText[i + 1])) {
// This is a closing tag identifier, not a flag - stop parsing flags
break;
}
if (ValidFlagSymbols.has(char)) {
flags.push(char);
i++;
flagEndPositions.push(i); // Position right after this flag
// Skip whitespace between flags
while (i < macroText.length && /\s/.test(macroText[i])) {
i++;
}
} else {
break;
}
}
// Determine which flag cursor is currently on (if any)
// The "current" flag is the last one typed when cursor is still in the flags area
// This ensures the last typed flag shows at the top of the autocomplete list
let currentFlag = null;
if (flags.length > 0) {
// If cursor is at or after the last flag position but before identifier starts,
// the last flag is the "current" one (just typed)
const lastFlagEnd = flagEndPositions[flagEndPositions.length - 1];
if (cursorOffset >= lastFlagEnd - 1) {
currentFlag = flags[flags.length - 1];
}
}
// Now parse the identifier and arguments starting from position i
const remainingText = macroText.slice(i);
const parts = [];
/** @type {{ start: number, end: number }[]} */
const separatorPositions = []; // Track positions of :: separators
let currentPart = '';
let partStart = i;
let j = 0;
while (j < remainingText.length) {
if (remainingText[j] === ':' && remainingText[j + 1] === ':') {
parts.push({ text: currentPart, start: partStart, end: i + j });
separatorPositions.push({ start: i + j, end: i + j + 2 });
currentPart = '';
j += 2;
partStart = i + j;
} else {
currentPart += remainingText[j];
j++;
}
}
// Push the last part
parts.push({ text: currentPart, start: partStart, end: macroText.length });
// Determine if cursor is in the flags area (at or before identifier starts)
const identifierStartPos = parts[0]?.start ?? i;
const isInFlagsArea = cursorOffset <= identifierStartPos;
// Check if cursor is on a partial separator (single ':' that might become '::')
const isTypingSeparator = remainingText.length > 0 &&
cursorOffset > identifierStartPos &&
macroText[cursorOffset - 1] === ':' &&
macroText[cursorOffset] !== ':' &&
(cursorOffset < 2 || macroText[cursorOffset - 2] !== ':');
// Parse identifier and space-separated argument from the first part
// "getvar myvar" -> identifier="getvar", spaceArg="myvar"
// "setvar " -> identifier="setvar", spaceArg="" (just whitespace, no content yet)
const firstPartText = parts[0]?.text || '';
const trimmedFirstPart = firstPartText.trimStart();
const firstSpaceInIdentifier = trimmedFirstPart.search(/\s/);
let identifierOnly;
let spaceArgText = '';
//let spaceArgStart = -1;
let hasSpaceAfterIdentifier = false;
if (firstSpaceInIdentifier > 0 && separatorPositions.length === 0) {
// There's whitespace inside the first part - split identifier from space-arg
identifierOnly = trimmedFirstPart.slice(0, firstSpaceInIdentifier);
const afterIdentifier = trimmedFirstPart.slice(firstSpaceInIdentifier);
// Check if there's actual content after the whitespace (not just spaces or ::)
const contentAfterSpace = afterIdentifier.trimStart();
hasSpaceAfterIdentifier = afterIdentifier.length > 0; // Has at least a space
if (contentAfterSpace.length > 0 && !contentAfterSpace.startsWith(':')) {
// There's actual argument content after the space
spaceArgText = contentAfterSpace;
//spaceArgStart = identifierStartPos + firstSpaceInIdentifier + (afterIdentifier.length - contentAfterSpace.length);
}
} else {
identifierOnly = trimmedFirstPart.trimEnd();
}
// Calculate identifier end position (for space-after-identifier detection)
const identifierEndPos = identifierStartPos + (firstPartText.length - firstPartText.trimStart().length) + identifierOnly.length;
// Determine which part the cursor is in
let currentArgIndex = -1;
// Only consider being in an argument if we've passed a separator
if (separatorPositions.length > 0) {
// Find which argument we're in based on separator positions
for (let sepIdx = 0; sepIdx < separatorPositions.length; sepIdx++) {
const sep = separatorPositions[sepIdx];
if (cursorOffset >= sep.end) {
// We're past this separator, so we're in at least this argument
currentArgIndex = sepIdx;
}
}
} else if (spaceArgText.length > 0 || (hasSpaceAfterIdentifier && cursorOffset > identifierEndPos)) {
// Space-separated arg: either has content, or cursor is past identifier+space
currentArgIndex = 0;
}
// If typing a separator, we're still on identifier/previous arg, not the next one
if (isTypingSeparator) {
currentArgIndex = -1;
}
const leftPadding = macroText.match(/^\s+/)?.[0] ?? '';
// Clean identifier: strip trailing colons (for partial :: typing)
let cleanIdentifier = identifierOnly.replace(/:+$/, '');
// Build args array - include space-separated arg if present
// Trim args like the macro engine does
let args = parts.slice(1).map(p => p.text.trim());
if (spaceArgText.length > 0) {
args = [spaceArgText, ...args];
}
return {
fullText: macroText,
cursorOffset,
paddingBefore: leftPadding,
identifier: cleanIdentifier,
identifierStart: identifierStartPos,
isInFlagsArea,
flags,
currentFlag,
args,
currentArgIndex,
isTypingSeparator,
hasSpaceAfterIdentifier,
hasSpaceArgContent: spaceArgText.length > 0,
separatorCount: separatorPositions.length,
};
}