snippets
This directory contains the central repository of voice-triggerable code snippets for the Talon community configuration. Rather than maintaining separate snippet libraries for every programming language, these files leverage a multi-language format. This design allows a single spoken phrase to contextually insert the syntactically correct code block, formatter, and wrapper behavior based on the file type currently being edited.
How the Snippet Engine Works
Each .snippet file is structured with a YAML-like header followed by one or more language-specific template sections separated by --- delimiters.
A snippet typically declares:
* name: The unique identifier for the snippet.
* phrase: The spoken voice command trigger (e.g., "for each" or "class").
* insertionScope: The structural context (like statement, class, or branch) indicating where the snippet is valid.
* Variable formatters: Custom rules targeting placeholders (e.g., $1.insertionFormatter: PUBLIC_CAMEL_CASE dynamically formats the user's spoken variable name).
* Wrapper configurations: Rules defining how existing selected text is encapsulated when the snippet is executed as a "wrap" command (using $0.wrapperPhrase and $0.wrapperScope).
* Placeholders: $1, $2, ... represent sequential tab stops, while $0 defines the final cursor position after completing the snippet.
Code Generation & Meta-Snippets
Meta-Snippet Authoring
- communitySnippets.snippet: A bootstrap snippet suite designed to help authors write new snippets. It includes voice shortcuts to generate headers, variable formatters, language declarations, default variables, and the structural blocks of the snippet format itself.
Control Flow & Loop Snippets
These snippets implement standard logical branching and iteration across dozens of target languages.
Conditional Branching
- ifStatement.snippet: Generates an
ifblock. It handles braced syntax for C/C++/Java/JS, colon syntax for Python,then/endblocks for Lua, anddo/endblocks for Elixir. - ifElseStatement.snippet & elseIfStatement.snippet: Handle secondary logic branching.
- elseStatement.snippet: Provides the final fallback condition block.
- ternary.snippet: Implements inline conditional assignments, mapping to
? :in C-family languages,$1 if $2 else $0in Python, andif $1 { $2 } else { $0 }in Rust.
Pattern Matching & Switches
- switchStatement.snippet: Maps the voice command "switch" to appropriate patterns like standard
switchblocks, Python's modernmatchstatement, or Rust'smatch. - caseStatement.snippet & defaultStatement.snippet: Define standard branching cases within match/switch scopes, supporting arrow syntaxes (e.g., Scala's
=>, Kotlin's->, and Rust's=>).
Iteration & Loops
- whileLoopStatement.snippet: Basic conditional loop structures.
- doWhileLoopStatement.snippet: Post-condition loops, automatically falling back to
repeat / untilin Lua orloop do / break ifin Ruby. - untilLoopStatement.snippet: Native
untilloop syntax for Ruby. - infiniteLoopStatement.snippet: Explicit infinite loops (e.g., Rust's
loop, Go'sfor, and Python'swhile True). - forLoopStatement.snippet: Standard loop iterations.
- forLoopReverseStatement.snippet: Reverse loops, outputting idiomatic structures like Python's
reversed(range())or Go's decrementing index loop. - forRangeStatement.snippet: Standard index-based ranges (e.g.,
0..$1in Rust,1:${2}in R, andrange($1)in Python). - forEachStatement.snippet & forEachMutableStatement.snippet: Element-wise collection traversal, automatically outputting read-only references like
const auto &in C++ or copy-by-value references depending on target language paradigms.
Loop Controls
- breakStatement.snippet, breakWithStatement.snippet, continue.snippet, & continueWith.snippet: Control loops, handling label-based breaks/continues for compatible languages, or translating
continuetonextin R orgoto continuein Lua.
Structural & Object-Oriented Declarations
These templates assist in declaring fundamental object-oriented, structural, and procedural code blocks.
- classDeclaration.snippet: Generates class definitions with target-specific formatters (forcing PascalCase/CamelCase) and structures.
- structDeclaration.snippet: Creates structured data footprints in Rust, C++, and Go.
- interfaceDeclaration.snippet: Generates typescript interfaces or Go interface types.
- functionDeclaration.snippet & methodDeclaration.snippet: Standardize subroutine creation. Automatically enforces snake_case for Python, Ruby, and PHP, and camelCase for JavaScript and C-family systems.
- constructorDeclaration.snippet: Generates object constructors (
__init__in Python, class-matched naming in C++, and explicitconstructorkeywords in JS/TS). - lambdaExpression.snippet: Generates anonymous inline functions (e.g.,
[]() {}in C++,() => {}in JS, andlambdain Python).
Dependency Management & Compilation
Snippets designed to pull in external resources, header files, or manage preprocessor operations.
- import.snippet: Resolves standard module inclusion (
import,require,use,library, orusing) across more than a dozen languages. - importFrom.snippet & importStar.snippet: Contextual sub-module destructuring imports.
- includeLocalStatement.snippet, includeSystemStatement.snippet, & includeHeaderStatement.snippet: Manage C/C++
#includedirectives. - Preprocessor Directives:
- preprocessorDefineStatement.snippet and preprocessorUndefineStatement.snippet handle C/C++ macros with uppercase/snake_case formatting.
- preprocessorIfStatement.snippet, preprocessorIfDefineStatement.snippet, preprocessorElseIfStatement.snippet, preprocessorEndIf.snippet, and preprocessorErrorStatement.snippet build conditional compilation blocks.
Exception Handling
- tryStatement.snippet: Scaffolds standard error-trapping blocks.
- catchStatement.snippet: Inserts language-specific catch clauses (e.g., standard
except Exception as ex:in Python, genericcatch (\Throwable \$exception)in PHP, orwarning/errorhandlers in R). - tryCatchStatement.snippet: Combines
tryandcatchblocks into a single action with boilerplate error parameters already typed out. - finallyStatement.snippet: Appends cleanup logic wrappers.
- throwException.snippet: Generates error instantiation and propagation statements, such as
raise ValueError(f"$0")orthrow std::runtime_error("$0").
Language-Specific Modules
Certain snippets cater entirely to the paradigms of specific ecosystems.
Python & Talon Customization
- python.snippet: Dedicated heavily to Python development with an emphasis on Talon API scripting. It defines boilerplate code for registering Talon Modules, Contexts, action classes, settings, lists, tags, and capture classes. It also implements standard Python structures like dict/set/list comprehensions and generator expressions.
Rust
- rust.snippet: Sets up structural configurations, testing modules (
#[cfg(test)]), trait definitions and implementation blocks (impl),if letdestructurings,let elseguard statements, andunsafeblocks.
JavaScript & React
- javascript.snippet: Standardizes local bindings (
constandletwith CamelCase automatic formatting), arrow functions, self-calling functions, and loops. - javascriptreact.snippet: Simplifies modern React hook development, generating React
useState(along with capitalized setter naming automation),useRef, anduseEffectarrays.
Web & Document Formats
- html.snippet: Helps construct table architectures, list infrastructures, and standard JSX/HTML attributes.
- xml.snippet: Creates matching open/close tags with formatted element tags.
- markdown.snippet: Provides rapid authoring shortcuts for Markdown links, images, bold/italic text styles, blockquotes, and checkbox lists.
Other Languages
- c.snippet: Focuses on typdef structural layouts and
#pragmacommands. - cpp.snippet: Implements C++ templates, member access specifiers (
public:,private:), automatic variable initialization, static casting, and robust header guard wrappers. - java.snippet: Introduces JVM
synchronizedblocks. - go.snippet: Scaffolds concurrency-based
selectstatements. - lua.snippet: Implements standard table traversal patterns (
pairsandipairs). - elixir.snippet: Outlines conditional
cond dopattern matches. - sql.snippet: Generates DDL schemas (
CREATE TABLE). - shellscript.snippet: Automatically places a strict shebang header (
#!/usr/bin/env bash set -euo pipefail) at the start of scripts. - talon.snippet: Rapidly registers custom Talon voice commands that invoke RPC utilities using the clipboard contents.
- typescript.snippet: Acts as a targeted context hook for TypeScript development.
Utility & Syntactic Helpers
These smaller snippets optimize everyday text manipulation.
- codeBlock.snippet: Inserts basic curly braces
{}or pythonic colons:depending on the scoping rules of the active language. - commentLine.snippet, commentBlock.snippet, & commentDocumentation.snippet: Standardize single-line (
//or#), multi-line (/* */or"""), and documentation-level (/** */or///) comments. - printStatement.snippet & formatString.snippet: Provide standardized output and string interpolation (e.g., Python f-strings, Javascript template literals, or
fmt.Printlnin Go). - functionCall.snippet: Places a call to a function with parenthetical parameters.
- newInstance.snippet: Instantiates new classes/structs (supporting
newprefixes, native Python constructor patterns, or Go's curly-brace instantiations). - item.snippet: Simplifies adding structured key-value pairs inside map or dictionary literals.
- returnStatement.snippet: Places return statements, managing the presence of semicolons based on the language.
- goToStatement.snippet: Emits standard jumping statements.
- withStatement.snippet: Implements pythonic context managers (
with) and SQL Common Table Expressions (WITH AS). - global.snippet: Instantiates standard Markdown code quote blocks.