### Example of stdio transport setup Source: https://myriad-dreamin.github.io/tinymist/rs/src/sync_ls/transport.rs.html?search=std%3A%3Avec A practical example demonstrating how to set up a standard input/output transport for LSP messages. This function can be used as a starting point for custom transport configurations. ```rust pub fn stdio_transport() -> (Sender, Receiver, IoThreads) { io_transport(MessageKind::Lsp, || stdin().lock(), || stdout().lock()) } ``` -------------------------------- ### HTTP Server Setup Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/task/user_action.rs.html Sets up a TCP listener and binds it to a specified address to start the HTTP server. It logs the server's listening address and prepares for graceful shutdown. ```rust let listener = tokio::net::TcpListener::bind(&static_file_addr) .await .unwrap(); let addr = listener.local_addr().unwrap(); log::info!("trace server listening on http://{addr}"); let (final_tx, final_rx) = oneshot::channel(); // the graceful watcher let graceful = hyper_util::server::graceful::GracefulShutdown::new(); ``` -------------------------------- ### Default Preview Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/struct.ServerState.html Starts a preview instance without arguments, useful when clients cannot pass arguments. This method also serves as an example for using the `preview` command. ```APIDOC ## default_preview ### Description Starts a preview instance but without arguments. This is used for the case where a client cannot pass arguments to the preview command. It is also an example of how to use the `preview` command. ### Behaviors * The preview server listens on a random port. * The colors are inverted according to the user’s system settings. * The preview follows an inferred focused file from the requests from the client. * The preview is opened in the default browser. ### Method `default_preview` ### Parameters - `_args` (Vec) - This argument is not used. ``` -------------------------------- ### SystemFileMeta Search Examples Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_vfs/system/struct.SystemFileMeta.html?search= Provides examples of how to perform searches within SystemFileMeta. These examples illustrate different query patterns. ```APIDOC ## SystemFileMeta Search ### Description This section provides examples of search queries that can be used to find file metadata within the system. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### BundlePath Search Examples Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/foundations/struct.BundlePath.html?search= Examples demonstrating how to search within BundlePath. These examples illustrate common search patterns. ```APIDOC ## BundlePath Search ### Description Provides examples of how to search within `BundlePath`. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### Providing Examples in Docstrings Source: https://myriad-dreamin.github.io/tinymist/feature/docs.html Shows how to use the #example function within a docstring to include a code example that will be rendered. ```tinymist #example(` ``` $ sum f(x) = 10 $ ``` `) ``` -------------------------------- ### Initialize and Run Previewer Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/preview.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up and runs the previewer by building it with LSP and compile handlers, binding streams, flushing compilation, and starting an HTTP server for the preview. This is the main entry point for the preview functionality. ```rust let previewer = previewer.build(lsp_tx, compile_handler.clone()); bind_streams(&mut previewer, websocket_rx); // Put a fence to ensure the previewer can receive the first compilation. // The fence must be put after the previewer is initialized. compile_handler.flush_compile(); // Replace the data plane port in the html to self let page_title = resolve_page_title( args.preview.page_title.as_deref(), args.compile.input.as_deref(), ); let frontend_html = frontend_html( TYPST_PREVIEW_HTML, args.preview.preview_mode, "/", &page_title, ); let srv = make_http_server(frontend_html, args.data_plane_host, websocket_tx).await; let addr = srv.addr; log::info!( target: crate::PREVIEW_COMPAT_LOG_TARGET, "PreviewTask({task_id}): preview server listening on: {addr}" ); let resp = StartPreviewResponse { static_server_port: Some(addr.port()), static_server_addr: Some(addr.to_string()), data_plane_port: Some(addr.port()), }; ``` -------------------------------- ### CLI Integration Example Source: https://myriad-dreamin.github.io/tinymist/feature/preview.html Demonstrates how to use the `typst-preview` command-line tool with arguments, which is equivalent to using the `tinymist preview` command. ```bash typst-preview /abs-path/to/main.typ --partial-rendering ``` ```bash tinymist preview /abs-path/to/main.typ --partial-rendering ``` -------------------------------- ### Get Current Instant Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/time/struct.Instant.html?search= Use `Instant::now()` to get the current time. This is the starting point for most time measurements. ```rust use std::time::Instant; let now = Instant::now(); ``` -------------------------------- ### Test Function Example Source: https://myriad-dreamin.github.io/tinymist/feature/cli.html An example of a Typst function that can be run as a test. Test functions typically start with `test-`. ```typst #let test-it() = [] ``` -------------------------------- ### Start Preview Server Source: https://myriad-dreamin.github.io/tinymist/feature/cli.html Starts a preview server for a Typst document. Specify the path to the main Typst file to begin the preview. ```bash tinymist preview path/to/main.typ ``` -------------------------------- ### HashSet Length Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/hash/type.FxHashSet.html Shows how to get the number of elements currently in a HashSet. ```rust use std::collections::HashSet; let mut v = HashSet::new(); assert_eq!(v.len(), 0); v.insert(1); assert_eq!(v.len(), 1); ``` -------------------------------- ### DebugL10n Blanket Implementation Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_project/lsp/struct.LspCompilerFeat.html Provides a method to get a debug string for the current language. ```rust fn debug_l10n(&self) -> Arg<'static> Returns a debug string for the current language. ``` -------------------------------- ### Trim Matches Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/diag/struct.EcoString.html?search=std%3A%3Avec Shows how to remove characters matching a pattern from both the start and end of a string. ```rust assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar"); ``` ```rust assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar"); ``` ```rust let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_matches(x), "foo1bar"); ``` ```rust assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); ``` -------------------------------- ### Preview Configuration Search Examples Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_preview/struct.PreviewConfig.html?search= Examples of how to search for preview configurations. These demonstrate searching by type, type conversions, and generic type transformations. ```APIDOC ## Search Examples ### Example 1: Searching for a standard library type ```rust std::vec ``` ### Example 2: Searching for a type conversion ```rust u32 -> bool ``` ### Example 3: Searching for a generic type transformation ```rust Option, (T -> U) -> Option ``` ``` -------------------------------- ### Trim Start Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/diag/struct.EcoString.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates removing leading whitespace from a string, considering Unicode characters. ```rust let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### start_project Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/project.rs.html?search= Starts a project with the given universe and options. This function initializes the project, sets up watchers, and returns a service to manage the project's lifecycle. ```APIDOC ## start_project ### Description Starts a project with the given universe and options. This function initializes the project, sets up watchers, and returns a service to manage the project's lifecycle. ### Function Signature `pub fn start_project(verse: LspUniverse, opts: Option, intr_handler: F) -> StartProjectResult` ### Parameters #### `verse` - Type: `LspUniverse` - Description: The universe for the project. #### `opts` - Type: `Option` - Description: Optional project options, including runtime handle, analysis, config, preview state, and export target. Defaults to `ProjectOpts::default()` if `None`. #### `intr_handler` - Type: `F` (where `F` is a closure) - Description: A handler function for interrupts during compilation. ### Returns - Type: `StartProjectResult` - Description: A struct containing the `WatchService` for running the project, an interrupt sender, and an editor request receiver. ### Associated Types - `ProjectOpts`: Struct containing options for starting a project. - `handle`: `Option` - The tokio runtime handle. - `analysis`: `Arc` - The shared analysis state. - `config`: `Config` - The shared configuration. - `preview`: `ProjectPreviewState` (conditional on `feature = "preview"`) - The shared preview state. - `export_target`: `ExportTarget` - The export target. - `StartProjectResult`: Struct containing the results of starting a project. - `service`: `WatchService` - A future service that runs the project. - `intr_tx`: `mpsc::UnboundedSender` - The interrupt sender. - `editor_rx`: `mpsc::UnboundedReceiver` - The editor request receiver. ``` -------------------------------- ### start_project Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/project.rs.html Starts a project with the given universe and options. It sets up the necessary components for compilation, file watching, and handling editor requests. ```APIDOC ## start_project ### Description Starts a project with the given universe and options. It sets up the necessary components for compilation, file watching, and handling editor requests. ### Function Signature ```rust pub fn start_project( verse: LspUniverse, opts: Option, intr_handler: F, ) -> StartProjectResult where F: FnMut( &mut LspProjectCompiler, Interrupt, fn(&mut LspProjectCompiler, Interrupt), ) ``` ### Parameters #### Function Parameters - **verse** (LspUniverse) - The language server universe to start the project with. - **opts** (Option) - Optional project options, including runtime handle, analysis, config, preview state, and export target. Defaults to `ProjectOpts::default()` if `None`. - **intr_handler** (F) - A closure that handles interrupts for the project compilation. ### Returns - **StartProjectResult** - A struct containing the `WatchService` for running the project, an interrupt sender, and an editor request receiver. ``` -------------------------------- ### Get Element Name Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/foundations/struct.Element.html?search= Returns the normal name of the element as a static string slice. For example, 'enum'. ```rust pub fn name(self) -> &'static str ``` -------------------------------- ### Start Preview Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/struct.ServerState.html Starts a preview instance with the provided arguments. ```APIDOC ## do_start_preview ### Description Starts a preview instance. ### Method `do_start_preview` ### Parameters - `args` (Vec) - Arguments for starting the preview instance. ``` -------------------------------- ### Trim Start Matches Examples Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/diag/struct.EcoString.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Removes prefixes from a string that match a given pattern, including numeric characters. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); ``` -------------------------------- ### Iterating Over Slice Elements Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/project/world/base/vfs/struct.Bytes.html?search=u32+-%3E+bool Use `iter` to get an iterator that yields references to all elements in the slice from start to end. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### SuperInit Initialize Method Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/lsp/init.rs.html?search= Handles the core LSP server initialization logic, setting up the server state, capabilities, and responding to the client. ```rust impl Initializer for SuperInit { type I = (); type S = ServerState; fn initialize(self, _params: ()) -> (ServerState, AnySchedulableResponse) { let SuperInit { client, exec_cmds, config, err, } = self; let const_config = config.const_config.clone(); // Bootstrap server let state = ServerState::main(client, config, err.is_none()); if let Some(err) = err { return (state, Err(err)); } let semantic_tokens_provider = (!const_config.tokens_dynamic_registration).then(|| { SemanticTokensServerCapabilities::SemanticTokensOptions(get_semantic_tokens_options()) }); let document_formatting_provider = (!const_config.doc_fmt_dynamic_registration).then_some(OneOf::Left(true)); let document_range_formatting_provider = (!const_config.doc_fmt_dynamic_registration).then_some(OneOf::Left(true)); let file_operations = const_config.notify_will_rename_files.then(|| { WorkspaceFileOperationsServerCapabilities { will_rename: Some(FileOperationRegistrationOptions { filters: vec![FileOperationFilter { scheme: Some("file".to_string()), pattern: FileOperationPattern { glob: "**/*.typ".to_string(), matches: Some(FileOperationPatternKind::File), options: None, }, }], }), ..WorkspaceFileOperationsServerCapabilities::default() } }); let res = InitializeResult { capabilities: ServerCapabilities { position_encoding: Some(const_config.position_encoding.into()), hover_provider: Some(HoverProviderCapability::Simple(true)), signature_help_provider: Some(SignatureHelpOptions { trigger_characters: Some(vec![ String::from("("), String::from(","), ]), ... }), ... }, ... }; (state, Ok(json!(res))) } } ``` -------------------------------- ### Get Element Title Case Name Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/foundations/struct.Element.html?search= Returns the title case name of the element, suitable for documentation. For example, 'Numbered List'. ```rust pub fn title(&self) -> &'static str ``` -------------------------------- ### Start Project Function Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/project.rs.html?search=std%3A%3Avec Initiates a new project with the given universe and options. It sets up necessary channels for communication and returns a service to watch for project changes. ```rust pub fn start_project( verse: LspUniverse, opts: Option, intr_handler: F, ) -> StartProjectResult where F: FnMut( &mut LspProjectCompiler, Interrupt, fn(&mut LspProjectCompiler, Interrupt), ), { let opts = opts.unwrap_or_default(); #[cfg(any(feature = "export", feature = "system"))] let handle = opts.handle.unwrap_or_else(tokio::runtime::Handle::current); let _ = opts.config; // type EditorSender = mpsc::UnboundedSender; let (editor_tx, editor_rx) = mpsc::unbounded_channel(); let (intr_tx, intr_rx) = tokio::sync::mpsc::unbounded_channel(); // todo: unify filesystem watcher let (dep_tx, dep_rx) = mpsc::unbounded_channel(); // todo: notify feature? #[cfg(feature = "system")] { let fs_intr_tx = intr_tx.clone(); handle.spawn(watch_deps(dep_rx, move |event| { fs_intr_tx.interrupt(LspInterrupt::Fs(event)); })); } #[cfg(not(feature = "system"))] { let _ = dep_rx; log::warn!("Project: system watcher is not enabled, file changes will not be watched"); } // Create the actor let compile_handle = Arc::new(CompileHandlerImpl { #[cfg(feature = "preview")] preview: opts.preview, is_standalone: true, #[cfg(feature = "export")] export: crate::task::ExportTask::new(handle, Some(editor_tx.clone()), opts.config.export()), editor_tx, client: Arc::new(intr_tx.clone()), analysis: opts.analysis, status_revision: Mutex::default(), notified_revision: Mutex::default(), }); let mut compiler = ProjectCompiler::new( verse, dep_tx, CompileServerOpts { handler: compile_handle, export_target: opts.export_target, syntax_only: opts.config.syntax_only, ignore_first_sync: true, }, ); compiler.primary.reason.by_entry_update = true; StartProjectResult { service: WatchService { compiler, intr_rx, intr_handler, }, intr_tx, editor_rx, } } ``` -------------------------------- ### do_start_preview Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/struct.ServerState.html?search= Starts a preview instance. ```APIDOC ## pub fn do_start_preview(&mut self, args: Vec) -> SchedulableResponse ### Description Starts a preview instance. ### Method Not specified (likely internal command) ### Endpoint Not applicable ### Parameters * **args** (Vec) - Description not specified. ``` -------------------------------- ### LsDriver::get_resources Source: https://myriad-dreamin.github.io/tinymist/rs/sync_ls/struct.LsDriver.html?search= Get static resources with help of tinymist service, for example, a static help pages for some typst function. ```APIDOC ## LsDriver::get_resources ### Description Get static resources with help of tinymist service, for example, a static help pages for some typst function. ### Method `get_resources(&mut self, req_id: RequestId, args: Vec) -> ScheduleResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response `ScheduleResult` #### Response Example None ``` -------------------------------- ### Configure Server Commands and Resources Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/server.rs.html?search=u32+-%3E+bool Sets up initial commands and resources for the LSP server. This is typically part of the server's setup phase. ```rust .with_command("tinymist.startServerProfiling", State::start_server_trace) .with_command("tinymist.stopServerProfiling", State::stop_server_trace); ``` ```rust let provider = provider .with_command("tinymist.doInitTemplate", State::init_template) .with_command("tinymist.doGetTemplateEntry", State::get_template_entry) .with_resource("/package/by-namespace", State::resource_package_by_ns) .with_resource("/dir/package", State::resource_package_dirs) .with_resource("/dir/package/local", State::resource_local_package_dir); ``` -------------------------------- ### Regex::find_at Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/foundations/struct.Regex.html Demonstrates `find_at` with a starting offset, showing how it affects the search for matches and their reported ranges, especially with anchors. ```Rust use regex::Regex; let re = Regex::new(r"\bchew\b").unwrap(); let hay = "eschew"; // We get a match here, but it's probably not intended. assert_eq!(re.find(&hay[2..]).map(|m| m.range()), Some(0..4)); // No match because the assertions take the context into account. assert_eq!(re.find_at(hay, 2), None); ``` -------------------------------- ### Initial Setup and Sync for Multiple Files Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist_project/watch.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This code block sets up a harness with multiple test files, populates them with initial content, and then synchronizes their dependencies. It's a prerequisite for subsequent event testing. ```rust let mut harness = NotifyActorHarness::new(); let empty = test_path("unstable-empty.typ"); let missing = test_path("unstable-missing.typ"); let errored = test_path("unstable-error.typ"); let recovery = test_path("unstable-recovery.typ"); for path in [&empty, &missing, &errored, &recovery] { harness.access.set_content(path, "stable"); } harness .apply(MatrixInput::SyncDependency(vec![ empty.clone(), missing.clone(), errored.clone(), recovery.clone(), ])) .await; harness.take_events(); harness.take_commands(); ``` -------------------------------- ### Regex::is_match_at Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/foundations/struct.Regex.html Illustrates `is_match_at` using a starting offset to evaluate regex patterns considering context, similar to `shortest_match_at`. ```Rust use regex::Regex; let re = Regex::new(r"\bchew\b").unwrap(); let hay = "eschew"; // We get a match here, but it's probably not intended. assert!(re.is_match(&hay[2..])); // No match because the assertions take the context into account. assert!(!re.is_match_at(hay, 2)); ``` -------------------------------- ### Start Preview Instance with CLI Arguments Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/preview.rs.html Parses CLI arguments and initiates a preview instance, returning a schedulable response. ```rust /// Starts a preview instance. pub fn start_preview( &mut self, cli_args: Vec, kind: PreviewKind, ) -> SchedulableResponse { // clap parse let cli_args = ["preview"] .into_iter() ``` -------------------------------- ### Create World Compute Graph from World Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist_world/compute.rs.html?search=u32+-%3E+bool Constructs a `WorldComputeGraph` directly from a `CompilerWorld`. This simplifies the setup when starting with a complete world instance. ```rust pub fn from_world(world: CompilerWorld) -> Arc { Self::new(CompileSnapshot::from_world(world)) } ``` -------------------------------- ### Start Default Preview Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/cmd.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts a preview instance with default arguments, useful when clients cannot pass arguments. It opens the preview in the default browser, listens on a random port, inverts colors, and follows the inferred focused file. This command is available when the 'preview' feature is enabled. ```APIDOC ## fn default_preview ### Description Starts a preview instance but without arguments. This is used for the case where a client cannot pass arguments to the preview command. It is also an example of how to use the `preview` command. Behaviors: - The preview server listens on a random port. - The colors are inverted according to the user's system settings. - The preview follows an inferred focused file from the requests from the client. - The preview is opened in the default browser. ### Parameters - `_args` (Vec): A vector of JSON values. This argument is not used in the function body but is part of the signature. ### Returns - `SchedulableResponse`: A response indicating the status of starting the preview server. ``` -------------------------------- ### Start a Tinymist Project Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/project.rs.html?search= Initiates a project with the given universe and options. Handles setup for file watching, compilation, and editor communication. ```rust pub fn start_project( verse: LspUniverse, opts: Option, intr_handler: F, ) -> StartProjectResult where F: FnMut( &mut LspProjectCompiler, Interrupt, fn(&mut LspProjectCompiler, Interrupt), ), { let opts = opts.unwrap_or_default(); #[cfg(any(feature = "export", feature = "system"))] let handle = opts.handle.unwrap_or_else(tokio::runtime::Handle::current); let _ = opts.config; // type EditorSender = mpsc::UnboundedSender; let (editor_tx, editor_rx) = mpsc::unbounded_channel(); let (intr_tx, intr_rx) = tokio::sync::mpsc::unbounded_channel(); // todo: unify filesystem watcher let (dep_tx, dep_rx) = mpsc::unbounded_channel(); // todo: notify feature? #[cfg(feature = "system")] { let fs_intr_tx = intr_tx.clone(); handle.spawn(watch_deps(dep_rx, move |event| { fs_intr_tx.interrupt(LspInterrupt::Fs(event)); })); } #[cfg(not(feature = "system"))] { let _ = dep_rx; log::warn!("Project: system watcher is not enabled, file changes will not be watched"); } // Create the actor let compile_handle = Arc::new(CompileHandlerImpl { #[cfg(feature = "preview")] preview: opts.preview, is_standalone: true, #[cfg(feature = "export")] export: crate::task::ExportTask::new(handle, Some(editor_tx.clone()), opts.config.export()), editor_tx, client: Arc::new(intr_tx.clone()), analysis: opts.analysis, status_revision: Mutex::default(), notified_revision: Mutex::default(), }); let mut compiler = ProjectCompiler::new( verse, dep_tx, CompileServerOpts { handler: compile_handle, export_target: opts.export_target, syntax_only: opts.config.syntax_only, ignore_first_sync: true, }, ); compiler.primary.reason.by_entry_update = true; StartProjectResult { service: WatchService { compiler, intr_rx, intr_handler, }, intr_tx, editor_rx, } } ``` -------------------------------- ### FieldClass Enum Definition Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_query/syntax/matcher/enum.FieldClass.html?search=std%3A%3Avec Defines the FieldClass enum with its variants: Field and DotSuffix. It also includes an example of how to get the node of the field class. ```APIDOC ## Enum FieldClass tinymist_query::syntax::matcher ### Description Classes of field syntax that can be operated on by IDE functionality. ### Variants #### Field(LinkedNode<'a>) A field node. ##### Example The `x` in the following code: ``` #a.x ``` #### DotSuffix(SourceSpanOffset) A dot suffix missing a field. ##### Example The `.` in the following code: ``` #a. ``` ### Implementations #### pub fn offset(&self, source: &Source) -> Option Gets the node of the field class. ``` -------------------------------- ### Start Project Function Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/project.rs.html Initiates a project with a given universe and options. It sets up necessary channels for communication and returns a service to watch for project changes and compile them. ```rust pub fn start_project( verse: LspUniverse, opts: Option, intr_handler: F, ) -> StartProjectResult where F: FnMut( &mut LspProjectCompiler, Interrupt, fn(&mut LspProjectCompiler, Interrupt), ), { let opts = opts.unwrap_or_default(); #[cfg(any(feature = "export", feature = "system"))] let handle = opts.handle.unwrap_or_else(tokio::runtime::Handle::current); let _ = opts.config; // type EditorSender = mpsc::UnboundedSender; let (editor_tx, editor_rx) = mpsc::unbounded_channel(); let (intr_tx, intr_rx) = tokio::sync::mpsc::unbounded_channel(); // todo: unify filesystem watcher let (dep_tx, dep_rx) = mpsc::unbounded_channel(); // todo: notify feature? #[cfg(feature = "system")] { let fs_intr_tx = intr_tx.clone(); handle.spawn(watch_deps(dep_rx, move |event| { fs_intr_tx.interrupt(LspInterrupt::Fs(event)); })); } #[cfg(not(feature = "system"))] { let _ = dep_rx; log::warn!("Project: system watcher is not enabled, file changes will not be watched"); } // Create the actor let compile_handle = Arc::new(CompileHandlerImpl { #[cfg(feature = "preview")] preview: opts.preview, is_standalone: true, #[cfg(feature = "export")] export: crate::task::ExportTask::new(handle, Some(editor_tx.clone()), opts.config.export()), editor_tx, client: Arc::new(intr_tx.clone()), analysis: opts.analysis, status_revision: Mutex::default(), notified_revision: Mutex::default(), }); let mut compiler = ProjectCompiler::new( verse, dep_tx, CompileServerOpts { handler: compile_handle, export_target: opts.export_target, syntax_only: opts.config.syntax_only, ignore_first_sync: true, }, ); compiler.primary.reason.by_entry_update = true; StartProjectResult { service: WatchService { compiler, intr_rx, intr_handler, }, intr_tx, editor_rx, } } ``` -------------------------------- ### Get Package Directories (System Feature) Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/cmd.rs.html Retrieves the paths of installed package directories when the 'system' feature is enabled. Requires a server snapshot. ```rust let snap = self.snapshot().map_err(internal_error)?; just_future(async move { let paths = snap.registry().paths(); let paths = paths.iter().map(|p| p.as_ref()).collect::>(); serde_json::to_value(paths).map_err(|e| internal_error(e.to_string())) }) ``` -------------------------------- ### Start Preview Instance Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/cmd.rs.html?search=std%3A%3Avec Starts a preview instance for the document. This command is conditional on the 'preview' feature being enabled. ```Rust pub fn do_start_preview( &mut self, mut args: Vec, ) -> SchedulableResponse { let cli_args = get_arg_or_default!(args[0] as Vec); ``` -------------------------------- ### Regex::captures_at Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/foundations/struct.Regex.html Explains `captures_at` using a starting offset, highlighting its impact on capturing groups when context, like anchors, is considered. ```Rust use regex::Regex; let re = Regex::new(r"\bchew\b").unwrap(); let hay = "eschew"; // We get a match here, but it's probably not intended. assert_eq!(&re.captures(&hay[2..]).unwrap()[0], "chew"); // No match because the assertions take the context into account. assert!(re.captures_at(hay, 2).is_none()); ``` -------------------------------- ### Start Project Function Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/project.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initiates a project with the given universe and options. It sets up necessary channels, handlers, and the compiler, returning a service to watch for changes and handle interrupts. ```rust /// Starts a project with the given universe. pub fn start_project( verse: LspUniverse, opts: Option, intr_handler: F, ) -> StartProjectResult where F: FnMut( &mut LspProjectCompiler, Interrupt, fn(&mut LspProjectCompiler, Interrupt), ), { let opts = opts.unwrap_or_default(); #[cfg(any(feature = "export", feature = "system"))] let handle = opts.handle.unwrap_or_else(tokio::runtime::Handle::current); let _ = opts.config; // type EditorSender = mpsc::UnboundedSender; let (editor_tx, editor_rx) = mpsc::unbounded_channel(); let (intr_tx, intr_rx) = tokio::sync::mpsc::unbounded_channel(); // todo: unify filesystem watcher let (dep_tx, dep_rx) = mpsc::unbounded_channel(); // todo: notify feature? #[cfg(feature = "system")] { let fs_intr_tx = intr_tx.clone(); handle.spawn(watch_deps(dep_rx, move |event| { fs_intr_tx.interrupt(LspInterrupt::Fs(event)); })); } #[cfg(not(feature = "system"))] { let _ = dep_rx; log::warn!("Project: system watcher is not enabled, file changes will not be watched"); } // Create the actor let compile_handle = Arc::new(CompileHandlerImpl { #[cfg(feature = "preview")] preview: opts.preview, is_standalone: true, #[cfg(feature = "export")] export: crate::task::ExportTask::new(handle, Some(editor_tx.clone()), opts.config.export()), editor_tx, client: Arc::new(intr_tx.clone()), analysis: opts.analysis, status_revision: Mutex::default(), notified_revision: Mutex::default(), }); let mut compiler = ProjectCompiler::new( verse, dep_tx, CompileServerOpts { handler: compile_handle, export_target: opts.export_target, syntax_only: opts.config.syntax_only, ignore_first_sync: true, }, ); compiler.primary.reason.by_entry_update = true; StartProjectResult { service: WatchService { compiler, intr_rx, intr_handler, }, intr_tx, editor_rx, } } ``` -------------------------------- ### ServerState Start Preview Method Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/preview.rs.html?search=u32+-%3E+bool Initiates the process of starting a preview instance with provided CLI arguments and preview kind. It prepares arguments for clap parsing. ```rust /// Starts a preview instance. pub fn start_preview( &mut self, cli_args: Vec, kind: PreviewKind, ) -> SchedulableResponse { // clap parse let cli_args = ["preview"] .into_iter() .chain(cli_args.iter().map(|e| e.as_str())); ``` -------------------------------- ### default_preview Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/struct.ServerState.html?search= Starts a preview instance without arguments, useful when clients cannot pass arguments. It also serves as an example for using the `preview` command. ```APIDOC ## pub fn default_preview(&mut self, _args: Vec) -> SchedulableResponse ### Description Starts a preview instance but without arguments. This is used for the case where a client cannot pass arguments to the preview command. It is also an example of how to use the `preview` command. Behaviors: * The preview server listens on a random port. * The colors are inverted according to the user’s system settings. * The preview follows an inferred focused file from the requests from the client. * The preview is opened in the default browser. ### Method Not specified (likely internal command) ### Endpoint Not applicable ### Parameters * **_args** (Vec) - Description not specified. ``` -------------------------------- ### Get Text Slice Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist_viewer/lib.rs.html?search=std%3A%3Avec Extracts a substring from the TextRun based on character start and end indices. Returns an empty string if the range is invalid. ```rust fn text_slice(&self, start: usize, end: usize) -> &str { let character_count = self.character_count(); let start = start.min(character_count); let end = end.min(character_count); if start >= end { return ""; } let start_byte = char_to_byte_index(&self.text, start); let end_byte = char_to_byte_index(&self.text, end); &self.text[start_byte..end_byte] } ``` -------------------------------- ### do_start_preview Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/struct.ServerState.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts a preview instance with specified arguments. ```APIDOC ## do_start_preview ### Description Starts a preview instance with specified arguments. ### Method Not specified (likely internal command) ### Parameters * `args` (Vec) - Arguments for starting the preview instance. ``` -------------------------------- ### Start Preview (Regular) Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/cmd.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Starts a regular preview instance. This command is available when the 'preview' feature is enabled. ```APIDOC ## fn browse_preview ### Description Starts a preview instance for browsing. This function is part of the preview management system. ### Parameters - `args` (Vec): A vector of JSON values, where the first element is expected to be a `Vec` representing CLI arguments. ### Returns - `SchedulableResponse`: A response indicating the status of starting the preview server. ``` -------------------------------- ### Rust TableBuilder::new() Example Source: https://myriad-dreamin.github.io/tinymist/rs/src/cmark_writer/ast/tables.rs.html?search=u32+-%3E+bool Initializes a new `TableBuilder` for constructing tables. Use this to start building a table with custom headers and rows. ```rust let mut builder = TableBuilder::new(); ``` -------------------------------- ### PreviewState::start Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/tool/preview/struct.PreviewState.html Starts a preview task using the provided arguments, builder, and project context. It returns a schedulable response indicating the status of the preview startup. ```APIDOC ## `PreviewState::start` ### Description Starts a preview on a given compiler. ### Signature `pub fn start(&self, args: PreviewCliArgs, previewer: PreviewBuilder, project_id: ProjectInsId, is_primary: bool, is_background: bool) -> SchedulableResponse` ### Parameters - `args`: PreviewCliArgs - Command-line arguments for the preview. - `previewer`: PreviewBuilder - The builder for creating the preview. - `project_id`: ProjectInsId - The ID of the project. - `is_primary`: bool - Whether this is the primary preview instance. - `is_background`: bool - Whether to run the preview in the background. ``` -------------------------------- ### Instant::now() and Instant::elapsed() Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/time/struct.Instant.html Demonstrates how to get the current instant, sleep for a duration, and then calculate the elapsed time using `elapsed()` and `as_secs()`. ```APIDOC ## Instant::now() and Instant::elapsed() ### Description This example shows how to capture the current time using `Instant::now()`, pause execution for a specified duration using `std::thread::sleep`, and then measure the time that has passed since the `Instant` was created using the `elapsed()` method. The elapsed duration is then converted to seconds using `as_secs()`. ### Usage ```rust use std::time::{Duration, Instant}; use std::thread::sleep; fn main() { let now = Instant::now(); // we sleep for 2 seconds sleep(Duration::new(2, 0)); // it prints '2' println!("{}", now.elapsed().as_secs()); } ``` ### Parameters This example does not directly involve parameters for `Instant::now()` or `Instant::elapsed()` as they are methods called on an `Instant` instance. ### Returns - `Instant::now()`: Returns a new `Instant` representing the current moment. - `Instant::elapsed()`: Returns a `Duration` representing the time elapsed since the `Instant` was created. - `Duration::as_secs()`: Returns the number of seconds in the `Duration` as a `u64`. ``` -------------------------------- ### Unsafe unwrap_err_unchecked Example (Err) Source: https://myriad-dreamin.github.io/tinymist/rs/cmark_writer/error/type.WriteResult.html?search=u32+-%3E+bool Shows how to use unwrap_err_unchecked to get the Err value without a check. This is unsafe and should only be used when the Result is guaranteed to be Err. ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Generating Package Documentation Files Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist_query/docs/package.rs.html This code snippet demonstrates the initialization of a file list for package documentation. It includes a common Typst file and constructs an entry point file that imports necessary modules and functions for creating a package index. ```rust let mut files = vec![]; files.push(PackageDocTypFile { path: PathBuf::from("common.typ"), content: include_str!("package-doc.typ").to_owned(), }); let mut entry = String::new(); let _ = writeln!( entry, "#import \"/typ/packages/tinymist-index/lib.typ": create_index" ); for path in &module_paths { let _ = writeln!( entry, "#import {}: {}", typst_string(&path.module_source_import), path.module_func ); for symbol in &path.symbol_paths { let _ = writeln!( entry, "#import {}: {}", typst_string(&symbol.source_import), symbol.func ); } if let Some(source_import) = &path.source_source_import { let _ = writeln!( entry, "#import {}: {}", typst_string(source_import), path.source_func ); } } let _ = writeln!( entry, "#let package-info = json(bytes(read(\"../{base}.json\")))" ); let _ = writeln!( entry, "#let package-index = create_index(read(\"../{base}.scip", encoding: none))" ); for path in &module_paths { let _ = writeln!(entry, "#{}(package-info, package-index)", path.module_func); for symbol in &path.symbol_paths { let _ = writeln!(entry, "#{}(package-info, package-index)", symbol.func); } } for path in &module_paths { if path.source_text.is_some() { let _ = writeln!(entry, "#{}(package-info, package-index)", path.source_func); } } files.push(PackageDocTypFile { path: PathBuf::from("index.typ"), content: entry, }); ``` -------------------------------- ### Unsafe unwrap_unchecked Example (Ok) Source: https://myriad-dreamin.github.io/tinymist/rs/cmark_writer/error/type.WriteResult.html?search=u32+-%3E+bool Shows how to use unwrap_unchecked to get the Ok value without a check. This is unsafe and should only be used when the Result is guaranteed to be Ok. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` -------------------------------- ### Setup Default Project Compiler Harness with Dependencies Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist_project/compiler.rs.html Initializes a project compiler harness with default files and performs an initial compilation. It then returns the harness and its initial dependencies, providing a clean state for further testing. ```rust fn clean_default_harness_with_deps() -> (ProjectCompilerHarness, Vec) { let files = default_files(); let mut harness = ProjectCompilerHarness::new(&files); let initial = harness.compile_primary(); assert_eq!(initial.error_cnt(), 0); let deps = harness.latest_sync_dependencies(); (harness, deps) } ``` -------------------------------- ### Get Package Directories (System Feature) Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/cmd.rs.html?search=std%3A%3Avec Retrieves the paths of installed packages. This feature requires the 'system' feature to be enabled and returns an asynchronous result. ```rust /// Get directory of packages #[cfg(feature = "system")] pub fn resource_package_dirs(&mut self, _arguments: Vec) -> AnySchedulableResponse { let snap = self.snapshot().map_err(internal_error)?; just_future(async move { let paths = snap.registry().paths(); let paths = paths.iter().map(|p| p.as_ref()).collect::>(); serde_json::to_value(paths).map_err(|e| internal_error(e.to_string())) }) } ``` -------------------------------- ### Create and Log HTTP Server for Preview Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/tool/preview.rs.html?search=u32+-%3E+bool Creates an HTTP server using the generated frontend HTML and specified data plane host, then logs the address it's listening on. ```rust let srv = make_http_server(frontend_html, args.data_plane_host, websocket_tx).await; let addr = srv.addr; log::info!( target: crate::PREVIEW_COMPAT_LOG_TARGET, "PreviewTask({task_id}): preview server listening on: {addr}" ); ``` -------------------------------- ### Regex::shortest_match_at Example Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/typst/foundations/struct.Regex.html Shows how `shortest_match_at` uses a starting offset to consider surrounding context, affecting matches that rely on anchors or word boundaries. ```Rust use regex::Regex; let re = Regex::new(r"\bchew\b").unwrap(); let hay = "eschew"; // We get a match here, but it's probably not intended. assert_eq!(re.shortest_match(&hay[2..]), Some(4)); // No match because the assertions take the context into account. assert_eq!(re.shortest_match_at(hay, 2), None); ``` -------------------------------- ### Configure LSP Preview Inputs Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist/config.rs.html?search=u32+-%3E+bool Sets up LSP inputs for preview functionality, including version and theme, serializing them into a JSON string. ```rust let mut dict = TypstDict::default(); #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct PreviewInputs { pub version: u32, pub theme: String, } dict.insert( "x-preview".into(), serde_json::to_string(&PreviewInputs { version: 1, theme: self.color_theme.clone().unwrap_or_default(), }) .unwrap() .into_value(), ); Arc::new(LazyHash::new(dict)) ``` -------------------------------- ### PreviewState::start Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist/tool/preview/struct.PreviewState.html?search=u32+-%3E+bool Starts a preview task on a given compiler with specified arguments and project context. ```APIDOC ## PreviewState::start ### Description Start a preview on a given compiler. ### Signature ```rust pub fn start( &self, args: PreviewCliArgs, previewer: PreviewBuilder, project_id: ProjectInsId, is_primary: bool, is_background: bool, ) -> SchedulableResponse ``` ``` -------------------------------- ### Get Monday-Based Week Number from UtcDateTime Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/time/struct.UtcDateTime.html Determines the week number where week 1 starts on Monday (0-53). Standard for many international contexts. ```rust assert_eq!(utc_datetime!(2019-01-01 0:00).monday_based_week(), 0); assert_eq!(utc_datetime!(2020-01-01 0:00).monday_based_week(), 0); assert_eq!(utc_datetime!(2020-12-31 0:00).monday_based_week(), 52); assert_eq!(utc_datetime!(2021-01-01 0:00).monday_based_week(), 0); ``` -------------------------------- ### Instrument Breakpoint for Simple Block Source: https://myriad-dreamin.github.io/tinymist/rs/src/tinymist_debug/debugger/instr.rs.html Instruments a simple code block with breakpoint logic for block start and end events. This is a basic instrumentation example. ```Rust let source = Source::detached("#let a = 1;"); let (new, _meta) = instrument_breakpoints(source).unwrap(); insta::assert_snapshot!(new.text(), @"#let a = 1;"); ``` -------------------------------- ### Get Sunday-Based Week Number from UtcDateTime Source: https://myriad-dreamin.github.io/tinymist/rs/tinymist_std/time/struct.UtcDateTime.html Calculates the week number where week 1 starts on Sunday (0-53). Useful for regions or systems using this convention. ```rust assert_eq!(utc_datetime!(2019-01-01 0:00).sunday_based_week(), 0); assert_eq!(utc_datetime!(2020-01-01 0:00).sunday_based_week(), 0); assert_eq!(utc_datetime!(2020-12-31 0:00).sunday_based_week(), 52); assert_eq!(utc_datetime!(2021-01-01 0:00).sunday_based_week(), 0); ```