Struct Snippet

Source
pub struct Snippet {
    pub name: String,
    pub prefix: String,
    pub body: Vec<String>,
    pub description: Option<String>,
    pub scope: Option<String>,
    pub is_file_template: Option<bool>,
    pub priority: Option<u32>,
}
Expand description

§The Snippet

🧩 Represents a VS Code snippet with all its properties and functionality. This structure allows you to create and manage code snippets for VS Code with rich customization options.

§Overview

  • 🎯 Create snippets with prefix triggers and body content
  • 🔧 Optional description and scope settings
  • ⚡ Priority management for suggestion list
  • 📦 Special templates to simplify development

§Usage

// Simple snippet creation
let snippet = Snippet::new("fn main", vec![
    "fn main() {",
    "    println!(\"Hello, World!\");",
    "}"
]);
 
// Using builder pattern
let snippet = Snippet::builder()
    .set_prefix("fn test")
    .set_body(vec![
        "#[test]",
        "fn test_$1() {",
        "    $0",
        "}"
    ])
    .set_description("Test function template")
    .set_scope("rust")
    .build()
    .unwrap();

§Using Templates

// Text snippet
let text = Snippet::text("hello", "println!(\"Hello, world!\");")
    .set_description("Prints 'Hello, world!'")
    .build()
    .unwrap();
 
// TODO comment
let todo = Snippet::todo_comment("todo", "TODO", Some("//"))
    .build()
    .unwrap();
 
// Function alias
let println = Snippet::fn_alias("pr", "println!")
    .build()
    .unwrap();

§Rust-specific Templates

// Requires feature = ["rust"]
 
// Rust macro alias
let macro_snippet = Snippet::rust_macro_alias("fmt", "format", None)
    .set_description("format! macro")
    .build()
    .unwrap();
 
// Rust attribute alias
let derive = Snippet::rust_attr("der", "derive", vec!["Debug", "Clone"])
    .set_description("Common derive attributes")
    .build()
    .unwrap();

§JSON Conversion

let snippet = Snippet::new("fn", vec!["function() {", "    $0", "}"]);
let json = snippet.to_json().unwrap();
println!("{}", json);

§Panics

The builder’s build() method will panic if:

  • prefix is empty
  • name is empty
  • body is empty

§Notes

§The syntax of VS Code snippets:
  • 📌 Use $0 to specify the final cursor position
  • 📌 Use $1, $2, etc. for tabstops
  • 📌 Use ${1:default text} for placeholders with default values
  • 📌 Use ${1|one,two,three|} for dropdown choices
§See Also

Fields§

§name: String

Unique identifier for the snippet (not serialized)

§prefix: String

The trigger text for the snippet

§body: Vec<String>

The actual content of the snippet

§description: Option<String>

Optional description of what the snippet does

§scope: Option<String>

Optional language scope (e.g., “rust”)

§is_file_template: Option<bool>

Optional flag for file templates

§priority: Option<u32>

Optional priority in suggestion list

Implementations§

Source§

impl Snippet

Source

pub fn new<S: Into<String>>( prefix: S, body: impl IntoIterator<Item = S>, ) -> Self

Creates a new snippet with required fields

Source

pub fn builder() -> SnippetBuilder

Creates a new SnippetBuilder instance

Source

pub fn to_json(&self) -> Result<String>

Converts the snippet to json string

Source§

impl Snippet

The standart snippet templates

Source

pub fn text<S: Into<String>>(prefix: S, text: S) -> SnippetBuilder

Creates a simple text snippet

Source

pub fn todo_comment<S: Into<String>>( prefix: S, comment_name: &str, comment_type: Option<&str>, ) -> SnippetBuilder

Creates various comment templates (TODO, NOTE, etc.)

Source

pub fn fn_alias<S: Into<String>>(prefix: S, fn_name: &str) -> SnippetBuilder

Creates a function alias template

Trait Implementations§

Source§

impl Clone for Snippet

Source§

fn clone(&self) -> Snippet

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Snippet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<SnippetBuilder> for Snippet

Source§

fn from(value: SnippetBuilder) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for Snippet

Source§

fn eq(&self, other: &Snippet) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Snippet

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Snippet

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.