Module Text

The ModuleText object provides access to the original source code of the script.

You can print this object to the terminal, or you can extract a substring of the source code within specified ranges.

let module = ScriptModule::new(
    Package::meta(),
    "let x = 10;\nlet y = 20;\nlet z = 30;",
);

// Assigns a user-facing name to the script module. 
module.rename("Example Module");

let handle = TriggerHandle::new();
let read_guard = module.read(&handle, 1).unwrap();

let module_text = read_guard.text();

// Fetches the second line of the source text.
let second_line = module_text.substring(Position::new(2, 1)..Position::new(3, 1));
assert_eq!(second_line, "let y = 20;\n");

println!("{module_text}");

Displaying the ModuleText object prints the following snippet:

   ╭──╢ module [‹doctest›.‹Example Module›] ╟──────────────────────────────────╮
 1 │ let x = 10;                                                               │
 2 │ let y = 20;                                                               │
 3 │ let z = 30;                                                               │
   ╰───────────────────────────────────────────────────────────────────────────╯

The output snippet's look and feel can be configured via the ModuleText::snippet function. Using this interface, you can set the snippet's header, footer, and annotate specific fragments of the source code.

let mut snippet = module_text.snippet();

snippet.set_caption("Snippet Caption");
snippet.set_summary("Summary line 1.\nSummary line 2.");
snippet.annotate(
    Position::new(2, 5)..Position::new(2, 6),
    AnnotationPriority::Default,
    "Annotation of the variable.",
);

println!("{snippet}");

Prints:

   ╭──╢ Snippet Caption [‹doctest›.‹Example Module›] ╟─────────────────────────╮
 1 │ let x = 10;                                                               │
 2 │ let y = 20;                                                               │
   │     ╰╴ Annotation of the variable.                                        │
 3 │ let z = 30;                                                               │
   ├───────────────────────────────────────────────────────────────────────────┤
   │ Summary line 1.                                                           │
   │ Summary line 2.                                                           │
   ╰───────────────────────────────────────────────────────────────────────────╯