Skip to content

Instantly share code, notes, and snippets.

@jameswilliamknight
Created December 29, 2024 05:11
Show Gist options
  • Save jameswilliamknight/2501f4eb9a0e2630be3e835e7f5ab5ac to your computer and use it in GitHub Desktop.
Save jameswilliamknight/2501f4eb9a0e2630be3e835e7f5ab5ac to your computer and use it in GitHub Desktop.
/**
* Type definitions for the Templater Obsidian plugin
*
* NOTICE: This file was generated with the assistance of an AI language model (Cursor AI).
* While efforts have been made to ensure accuracy and completeness, please verify critical
* type definitions against the actual plugin implementation.
*
* Generated by: Cursor AI
* Model: anthropic/claude-3-sonnet-20241022
* Date: December 2024
*/
import {
App,
EditorPosition,
EditorTransaction,
TFile,
TFolder,
} from "obsidian";
/** Modules available in the Templater plugin. Each module provides a specific set of functionality
* that can be accessed in templates using the tp.module_name syntax.
* Common workflow: Users access these modules in their templates like:
* - tp.file for file operations (e.g., tp.file.rename)
* - tp.date for date manipulation (e.g., tp.date.now)
* - tp.system for system operations (e.g., tp.system.clipboard)
* Intent: Provides a modular, namespaced API for template operations */
export type ModuleName =
| "app"
| "config"
| "date"
| "file"
| "frontmatter"
| "hooks"
| "obsidian"
| "system"
| "user"
| "web";
/** Links a specific folder to a template that should be used when creating notes in that folder.
* Common workflow: Users set up folder templates in settings to automatically apply specific templates
* when creating notes in designated folders (e.g., /meetings folder uses meeting-template.md).
* Intent: Enables folder-specific templating without manual template selection */
export interface FolderTemplate {
folder: string;
template: string;
}
/** Defines a pattern-based template that will be applied to files whose names match the regex.
* Common workflow: Users set up patterns like "daily.*" to automatically apply templates to files
* matching that pattern (e.g., daily-standup notes automatically use the standup template).
* Intent: Enables automatic template application based on file naming patterns */
export interface FileTemplate {
regex: string;
template: string;
}
/** Configuration options that control Templater's behavior and features.
* Common workflow: Users configure these settings through the plugin settings UI to:
* - Set up template directories and automatic triggers
* - Configure system command access and security settings
* - Define startup templates and hotkeys
* Intent: Provides user-configurable behavior while maintaining security boundaries */
export interface TemplaterSettings {
/** Maximum time in milliseconds before a system command is terminated.
* Used to prevent hanging on long-running commands */
command_timeout: number;
templates_folder: string;
/** Pairs of [source template, destination path] for automatic template application.
* Used for setting up automatic file creation with templates */
templates_pairs: Array<[string, string]>;
trigger_on_file_creation: boolean;
auto_jump_to_cursor: boolean;
/** When enabled, allows execution of system commands via tp.system.exec and tp.system.shell.
* Common workflow: Users enable this to interact with external tools or scripts */
enable_system_commands: boolean;
shell_path: string;
/** Directory containing user-defined JavaScript modules that can be imported in templates.
* Common workflow: Users create custom .js files here to extend templater's functionality */
user_scripts_folder: string;
enable_folder_templates: boolean;
folder_templates: Array<FolderTemplate>;
enable_file_templates: boolean;
file_templates: Array<FileTemplate>;
/** Controls syntax highlighting in the template editor.
* Helps users identify template syntax within their files */
syntax_highlighting: boolean;
/** Separate control for mobile devices where performance might be a concern.
* Common workflow: Users might disable this on mobile for better performance */
syntax_highlighting_mobile: boolean;
/** Templates that can be triggered via hotkeys.
* Common workflow: Users bind frequently used templates to keyboard shortcuts */
enabled_templates_hotkeys: Array<string>;
/** Templates that are automatically executed when Obsidian starts.
* Common workflow: Used for daily notes or dashboard updates */
startup_templates: Array<string>;
}
/** Describes a parameter that can be passed to a template function.
* Common workflow: Used in the template function documentation system to show available parameters.
* Intent: Provides IntelliSense-like documentation for template functions */
export interface TpArgumentDocumentation {
name: string;
description: string;
}
/** Documents a function that can be called from within a template.
* Common workflow: Used by the suggestion system to:
* - Show available functions while typing
* - Display function documentation in the UI
* - Provide examples of usage
* Intent: Enables self-documenting template functions */
export interface TpFunctionDocumentation {
name: string;
/** Used for fuzzy matching in the function suggester.
* Common workflow: Users can type partial matches to find functions */
queryKey: string;
/** The function's signature as it would appear in code.
* Shows parameters and return type */
definition: string;
description: string;
/** Code snippet showing how to use the function.
* Provides real-world usage examples */
example: string;
args?: Record<string, TpArgumentDocumentation>;
}
/** Documents a module and its available functions.
* Common workflow: Used by the documentation system to:
* - Group related functions together
* - Provide module-level documentation
* - Enable module-specific search
* Intent: Organizes template functions into logical groups */
export interface TpModuleDocumentation {
name: string;
/** Used for fuzzy matching in the module suggester.
* Common workflow: Users can search for modules by partial name */
queryKey: string;
description: string;
functions: Record<string, TpFunctionDocumentation>;
}
export type TpSuggestDocumentation =
| TpModuleDocumentation
| TpFunctionDocumentation;
/** Configuration for the template expression parser.
* These settings control how template expressions are recognized and processed within files.
* Common workflow: Used internally to:
* - Parse template syntax in files
* - Handle variable substitution
* - Process dynamic content
* Intent: Provides flexible template syntax while maintaining parsing accuracy */
export interface ParserConfig {
/** Marks the beginning of a template expression (default: "<%").
* Common workflow: Users wrap their template code in these tags */
startTag: string;
/** Marks the end of a template expression (default: "%>") */
endTag: string;
/** Used internally to mark positions in the template during processing.
* Helps maintain template structure during multi-pass processing */
marker: string;
/** Characters that are valid within variable names.
* Controls what can be used in template variable names */
validNameChars: string;
/** Characters that can appear at the start of a variable name.
* Enforces valid variable naming */
validNameStartChars: string;
/** Characters that can appear within a variable name but not at the start.
* Allows for more flexible variable names while maintaining validity */
validNameContinueChars: string;
/** Special characters used for internal template processing.
* Used to handle special template features */
markers: string;
}
/** Provides access to the editor's content and manipulation capabilities.
* Common workflow: Used to:
* - Read and modify file content
* - Apply template changes
* - Handle user edits
* Intent: Abstracts editor operations for consistent content manipulation */
export interface EditorInterface {
getValue(): string;
setValue(value: string): void;
/** Apply a series of changes to the editor content.
* Common workflow: Used for complex content modifications */
transaction(transaction: EditorTransaction): void;
}
/** Handles cursor positioning and movement within templates.
* Used primarily for the <% tp.file.cursor() %> command functionality.
* Common workflow: Users place cursor markers in templates to:
* - Define tab stops
* - Set focus points after template insertion
* - Create interactive template workflows
* Intent: Enables template-driven cursor positioning */
export interface CursorJumperInterface {
jump_to_next_cursor_location(): Promise<void>;
/** Converts a character index in the content to an editor position object.
* Used for precise cursor placement */
get_editor_position_from_index(
content: string,
index: number
): EditorPosition;
set_cursor_location(positions: EditorPosition[]): void;
}
/** Provides autocompletion and suggestions for template expressions.
* Common workflow: As users type template expressions:
* - Shows available functions and modules
* - Displays documentation
* - Provides autocomplete
* Intent: Improves template authoring experience */
export interface EditorSuggestInterface {
suggestions: TpSuggestDocumentation[];
/** Returns relevant suggestions based on the current editing context.
* Filters suggestions based on what the user has typed */
getSuggestions(context: EditorSuggestContext): TpSuggestDocumentation[];
/** Creates the HTML element that displays a suggestion.
* Handles the visual presentation of suggestions */
renderSuggestion(suggestion: TpSuggestDocumentation, el: HTMLElement): void;
}
/** Context provided to the suggestion system to determine relevant completions.
* Common workflow: Used to:
* - Filter suggestions based on current input
* - Provide context-aware completions
* Intent: Enables context-aware template suggestions */
export interface EditorSuggestContext {
/** The partial text that triggered the suggestion */
query: string;
file: TFile;
editor: EditorInterface;
}
/** Determines how a template should be opened/inserted.
* Common workflow: Controls whether templates:
* - Insert at cursor position
* - Create new notes
* Intent: Provides different modes of template application */
export enum OpenMode {
InsertTemplate,
CreateNoteTemplate,
}
/** Manages Templater's event subscriptions and responses.
* Common workflow: Handles:
* - File creation events
* - Setting changes
* - Template processing events
* Intent: Coordinates plugin responses to system events */
export interface EventHandlerInterface {
setup(): void;
/** Updates CodeMirror mode when syntax highlighting settings change */
update_syntax_highlighting(): void;
/** Updates file creation hooks when trigger settings change */
update_trigger_file_on_creation(): void;
/** Updates the file context menu with template options */
update_file_menu(): void;
}
/** Provides fuzzy search functionality for template selection.
* Common workflow: Users can:
* - Search templates by name
* - Quick-insert templates
* - Create new notes from templates
* Intent: Enables quick template access and application */
export interface FuzzySuggesterInterface {
/** Returns all available template files */
getItems(): TFile[];
/** Formats how a template appears in the suggestion list */
getItemText(item: TFile): string;
/** Handles template selection from the suggestion list */
onChooseItem(item: TFile): void;
start(): void;
insert_template(): void;
create_new_note_from_template(folder?: TFolder): void;
}
/** Manages command registration and hotkey functionality.
* Common workflow: Handles:
* - Template hotkey registration
* - Command palette integration
* - Template quick actions
* Intent: Provides quick access to template functionality */
export interface CommandHandler {
setup(): void;
register_templates_hotkeys(): void;
/** Updates hotkey bindings when templates change */
add_template_hotkey(
old_template: string | null,
new_template: string
): void;
remove_template_hotkey(template: string | null): void;
}
/** Custom error class that supports additional console output for debugging.
* Common workflow: Used to:
* - Provide user-friendly error messages
* - Log detailed debug information
* Intent: Improves error handling and debugging */
export class TemplaterError extends Error {
constructor(msg: string, public console_msg?: string);
}
/** Collection of utility functions used throughout the plugin.
* Common workflow: Used for:
* - File and path manipulation
* - Regular expression handling
* - Array operations
* Intent: Provides common functionality to other plugin components */
export interface UtilityFunctions {
delay(ms: number): Promise<void>;
escape_RegExp(str: string): string;
/** Creates regex for matching standard template commands */
generate_command_regex(): RegExp;
/** Creates regex for matching dynamic template commands */
generate_dynamic_command_regex(): RegExp;
resolve_tfolder(app: App, folder_str: string): TFolder;
resolve_tfile(app: App, file_str: string): TFile;
get_tfiles_from_folder(app: App, folder_str: string): Array<TFile>;
/** Moves an array element while maintaining relative order of other elements */
arraymove<T>(arr: T[], fromIndex: number, toIndex: number): void;
get_active_file(app: App): TFile | null;
get_folder_path_from_file_path(path: string): string;
/** Type guard for identifying plain objects */
is_object(obj: unknown): obj is Record<string, unknown>;
/** Extracts parameter names from a function's toString() output */
get_fn_params(func: (...args: unknown[]) => unknown): string[];
}
/** Wraps functions with standardized error handling.
* Common workflow: Used to:
* - Catch and format errors
* - Provide consistent error messages
* - Handle async errors
* Intent: Standardizes error handling across the plugin */
export interface ErrorWrapper {
errorWrapper<T>(fn: () => Promise<T>, msg: string): Promise<T>;
errorWrapperSync<T>(fn: () => T, msg: string): T;
}
/** Defines how a template should be processed.
* Common workflow: Controls template behavior for:
* - New note creation
* - Content insertion
* - File overwriting
* Intent: Provides different modes of template application */
export enum RunMode {
CreateNewFromTemplate,
AppendActiveFile,
OverwriteFile,
OverwriteActiveFile,
/** Used for processing dynamic templates within files.
* Handles templates that update their content automatically */
DynamicProcessor,
StartupTemplate,
}
/** Configuration object passed during template processing.
* Common workflow: Used to:
* - Track template processing state
* - Maintain context during processing
* - Control template behavior
* Intent: Maintains template processing context */
export interface RunningConfig {
template_file: TFile | undefined;
target_file: TFile;
run_mode: RunMode;
/** The file that was active when template processing started.
* Used to restore context after processing */
active_file?: TFile | null;
}
/** Core functionality for template processing and management.
* Common workflow: Handles:
* - Template parsing and execution
* - Function object generation
* - Template file operations
* Intent: Provides core template processing capabilities */
export interface TemplaterCore {
parser: {
init(): Promise<void>;
/** Processes template expressions within the content.
* Converts template syntax into final output */
parse_commands(
template_content: string,
functions_object: Record<string, unknown>
): Promise<string>;
};
/** Generates the tp object that's available within templates.
* Creates the API surface for template operations */
functions_generator: {
init(): Promise<void>;
generate_object(
config: RunningConfig,
mode: FunctionsMode
): Promise<Record<string, unknown>>;
teardown(): Promise<void>;
};
/** The current tp object being used for template processing.
* Provides the API surface for the current template */
current_functions_object: Record<string, unknown>;
/** Tracks files that are currently being processed.
* Prevents recursive template processing */
files_with_pending_templates: Set<string>;
create_running_config(
template_file: TFile | undefined,
target_file: TFile,
run_mode: RunMode
): RunningConfig;
read_and_parse_template(config: RunningConfig): Promise<string>;
parse_template(
config: RunningConfig,
template_content: string
): Promise<string>;
create_new_note_from_template(
template: TFile | string,
folder?: TFolder | string,
filename?: string,
open_new_note?: boolean
): Promise<TFile | undefined>;
append_template_to_active_file(template_file: TFile): Promise<void>;
}
/** Controls which functions are available during template processing.
* Common workflow: Used to:
* - Control available template functions
* - Manage security boundaries
* Intent: Provides function access control */
export enum FunctionsMode {
/** Includes both user-defined and internal functions.
* Used for normal template processing */
USER_INTERNAL = "user_internal",
/** Only includes internal functions.
* Used for system templates */
INTERNAL = "internal",
}
/** Main plugin class that coordinates all Templater functionality.
* Common workflow: Handles:
* - Plugin initialization
* - Feature coordination
* - Resource management
* Intent: Provides the main plugin interface */
export interface TemplaterPlugin {
settings: TemplaterSettings;
templater: TemplaterCore;
event_handler: EventHandlerInterface;
command_handler: CommandHandler;
fuzzy_suggester: FuzzySuggesterInterface;
editor_handler: EditorInterface;
onload(): Promise<void>;
onunload(): void;
save_settings(): Promise<void>;
load_settings(): Promise<void>;
}
// Obsidian module augmentations
declare module "obsidian" {
interface App {
dom: {
appContainerEl: HTMLElement;
};
}
interface Vault {
getConfig: (key: string) => string;
exists: (path: string) => Promise<boolean>;
getAvailablePath: (path: string, extension: string) => string;
getAbstractFileByPathInsensitive: (path: string) => string;
}
interface DataAdapter {
basePath: string;
fs: {
uri: string;
};
}
interface Workspace {
on(
name: "templater:all-templates-executed",
callback: () => unknown
): EventRef;
}
interface EventRef {
e: Events;
}
interface MarkdownSubView {
applyFoldInfo(foldInfo: FoldInfo): void;
getFoldInfo(): FoldInfo | null;
}
interface FoldInfo {
folds: FoldRange[];
lines: number;
}
interface FoldRange {
from: number;
to: number;
}
}
/** Interface for generating objects */
export interface IGenerateObject {
/** Generate an object based on running configuration */
generate_object(config: RunningConfig): Promise<Record<string, unknown>>;
}
/** Interface for suggestion owners */
export interface ISuggestOwner<T> {
/** Render a suggestion in the UI */
renderSuggestion(item: T, el: HTMLElement): void;
/** Handle suggestion selection */
selectSuggestion(item: T, event: MouseEvent | KeyboardEvent): void;
}
/** Interface for text input suggestions */
export interface TextInputSuggestInterface<T> extends ISuggestOwner<T> {
/** Get suggestions based on input */
getSuggestions(inputStr: string): T[];
/** Render a suggestion in the UI */
renderSuggestion(item: T, el: HTMLElement): void;
/** Handle suggestion selection */
selectSuggestion(item: T): void;
/** Open the suggestion UI */
open(container: HTMLElement, inputEl: HTMLElement): void;
/** Close the suggestion UI */
close(): void;
/** Handle input changes */
onInputChanged(): void;
}
/** Interface for logging functions */
export interface LoggingFunctions {
/** Log an update message */
log_update(msg: string): void;
/** Log an error message */
log_error(e: Error | TemplaterError): void;
}
/** Interface for internal modules */
export interface InternalModuleInterface extends IGenerateObject {
/** Module name */
name: ModuleName;
/** Get the module name */
getName(): ModuleName;
/** Create static templates */
create_static_templates(): Promise<void>;
/** Create dynamic templates */
create_dynamic_templates(): Promise<void>;
/** Clean up resources */
teardown(): Promise<void>;
/** Initialize the module */
init(): Promise<void>;
/** Generate an object based on configuration */
generate_object(
new_config: RunningConfig
): Promise<Record<string, unknown>>;
}
/** The main interface for interacting with Templater from user scripts.
* Common workflow: Used in user scripts to:
* - Access Obsidian's API
* - Manipulate files and notes
* - Execute template functions
* Intent: Provides a safe, typed interface for template scripting */
export interface TemplaterInternals {
app: App & {
vault: Vault & {
adapter: {
read(path: string): Promise<string>;
};
};
};
user: {
getCurrentNote(tp: TemplaterInternals): Promise<TFile>;
getDailyNotePath(tp: TemplaterInternals, date: Date): Promise<string>;
[key: string]: (tp: TemplaterInternals, ...args: any[]) => Promise<any>;
};
}
// Make TypeScript recognize tp.user.scriptName calls
declare global {
interface Window {
tp: TemplaterInternals;
}
}
export type { TemplaterInternals };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment