From b036fd97ab2c1cdc003b50eea7850279a1a7601f Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 21 Jul 2025 15:13:34 +0200 Subject: [PATCH] Reformat with 2024 edition --- crates/typst-cli/build.rs | 4 +- crates/typst-cli/src/compile.rs | 8 +- crates/typst-cli/src/download.rs | 2 +- crates/typst-cli/src/init.rs | 2 +- crates/typst-cli/src/main.rs | 4 +- crates/typst-cli/src/query.rs | 6 +- crates/typst-cli/src/server.rs | 2 +- crates/typst-cli/src/timings.rs | 4 +- crates/typst-cli/src/update.rs | 2 +- crates/typst-cli/src/watch.rs | 4 +- crates/typst-cli/src/world.rs | 16 +- crates/typst-eval/src/access.rs | 11 +- crates/typst-eval/src/binding.rs | 2 +- crates/typst-eval/src/call.rs | 10 +- crates/typst-eval/src/code.rs | 33 ++- crates/typst-eval/src/flow.rs | 6 +- crates/typst-eval/src/import.rs | 35 ++-- crates/typst-eval/src/lib.rs | 8 +- crates/typst-eval/src/markup.rs | 2 +- crates/typst-eval/src/ops.rs | 15 +- crates/typst-eval/src/rules.rs | 23 +- crates/typst-eval/src/vm.rs | 4 +- crates/typst-html/src/convert.rs | 4 +- crates/typst-html/src/document.rs | 6 +- crates/typst-html/src/dom.rs | 4 +- crates/typst-html/src/encode.rs | 10 +- crates/typst-html/src/fragment.rs | 2 +- crates/typst-html/src/lib.rs | 8 +- crates/typst-html/src/link.rs | 4 +- crates/typst-html/src/rules.rs | 16 +- crates/typst-html/src/typed.rs | 6 +- crates/typst-ide/src/analyze.rs | 19 +- crates/typst-ide/src/complete.rs | 198 +++++++++--------- crates/typst-ide/src/definition.rs | 10 +- crates/typst-ide/src/jump.rs | 37 ++-- crates/typst-ide/src/lib.rs | 14 +- crates/typst-ide/src/matchers.rs | 31 +-- crates/typst-ide/src/tests.rs | 2 +- crates/typst-ide/src/tooltip.rs | 69 +++--- crates/typst-ide/src/utils.rs | 8 +- crates/typst-kit/src/package.rs | 4 +- crates/typst-layout/src/flow/block.rs | 7 +- crates/typst-layout/src/flow/collect.rs | 15 +- crates/typst-layout/src/flow/compose.rs | 8 +- crates/typst-layout/src/flow/mod.rs | 8 +- crates/typst-layout/src/grid/layouter.rs | 108 +++++----- crates/typst-layout/src/grid/lines.rs | 50 ++--- crates/typst-layout/src/grid/mod.rs | 4 +- crates/typst-layout/src/grid/repeated.rs | 20 +- crates/typst-layout/src/grid/rowspans.rs | 29 +-- crates/typst-layout/src/inline/collect.rs | 15 +- crates/typst-layout/src/inline/line.rs | 53 ++--- crates/typst-layout/src/inline/linebreak.rs | 21 +- crates/typst-layout/src/inline/mod.rs | 20 +- crates/typst-layout/src/inline/shaping.rs | 16 +- crates/typst-layout/src/lists.rs | 23 +- crates/typst-layout/src/math/accent.rs | 4 +- crates/typst-layout/src/math/attach.rs | 4 +- crates/typst-layout/src/math/frac.rs | 4 +- crates/typst-layout/src/math/fragment.rs | 19 +- crates/typst-layout/src/math/lr.rs | 18 +- crates/typst-layout/src/math/mat.rs | 6 +- crates/typst-layout/src/math/mod.rs | 18 +- crates/typst-layout/src/math/root.rs | 2 +- crates/typst-layout/src/math/run.rs | 25 ++- crates/typst-layout/src/math/shared.rs | 2 +- crates/typst-layout/src/math/stretch.rs | 4 +- crates/typst-layout/src/math/text.rs | 8 +- crates/typst-layout/src/math/underover.rs | 4 +- crates/typst-layout/src/pages/mod.rs | 6 +- crates/typst-layout/src/pages/run.rs | 4 +- crates/typst-layout/src/repeat.rs | 2 +- crates/typst-layout/src/rules.rs | 14 +- crates/typst-layout/src/shapes.rs | 2 +- crates/typst-layout/src/stack.rs | 2 +- crates/typst-layout/src/transforms.rs | 2 +- crates/typst-library/src/diag.rs | 16 +- crates/typst-library/src/engine.rs | 16 +- crates/typst-library/src/foundations/args.rs | 6 +- crates/typst-library/src/foundations/array.rs | 8 +- crates/typst-library/src/foundations/auto.rs | 4 +- crates/typst-library/src/foundations/bool.rs | 2 +- crates/typst-library/src/foundations/bytes.rs | 6 +- crates/typst-library/src/foundations/calc.rs | 4 +- crates/typst-library/src/foundations/cast.rs | 14 +- .../src/foundations/content/element.rs | 6 +- .../src/foundations/content/field.rs | 2 +- .../src/foundations/content/mod.rs | 13 +- .../src/foundations/content/raw.rs | 2 +- .../typst-library/src/foundations/context.rs | 4 +- .../typst-library/src/foundations/datetime.rs | 10 +- .../typst-library/src/foundations/decimal.rs | 10 +- crates/typst-library/src/foundations/dict.rs | 4 +- .../typst-library/src/foundations/duration.rs | 4 +- .../typst-library/src/foundations/fields.rs | 2 +- crates/typst-library/src/foundations/float.rs | 6 +- crates/typst-library/src/foundations/func.rs | 12 +- crates/typst-library/src/foundations/int.rs | 6 +- crates/typst-library/src/foundations/label.rs | 4 +- crates/typst-library/src/foundations/mod.rs | 2 +- .../typst-library/src/foundations/module.rs | 6 +- crates/typst-library/src/foundations/none.rs | 2 +- crates/typst-library/src/foundations/ops.rs | 4 +- .../typst-library/src/foundations/plugin.rs | 6 +- crates/typst-library/src/foundations/repr.rs | 4 +- crates/typst-library/src/foundations/scope.rs | 6 +- .../typst-library/src/foundations/selector.rs | 8 +- crates/typst-library/src/foundations/str.rs | 12 +- .../typst-library/src/foundations/styles.rs | 12 +- .../typst-library/src/foundations/symbol.rs | 10 +- .../typst-library/src/foundations/target.rs | 2 +- crates/typst-library/src/foundations/ty.rs | 6 +- crates/typst-library/src/foundations/value.rs | 12 +- .../typst-library/src/foundations/version.rs | 6 +- .../src/introspection/counter.rs | 14 +- .../typst-library/src/introspection/here.rs | 2 +- .../src/introspection/introspector.rs | 2 +- .../typst-library/src/introspection/locate.rs | 2 +- .../src/introspection/location.rs | 2 +- .../src/introspection/metadata.rs | 2 +- .../typst-library/src/introspection/query.rs | 2 +- .../typst-library/src/introspection/state.rs | 10 +- crates/typst-library/src/introspection/tag.rs | 4 +- crates/typst-library/src/layout/abs.rs | 2 +- crates/typst-library/src/layout/align.rs | 8 +- crates/typst-library/src/layout/angle.rs | 2 +- crates/typst-library/src/layout/axes.rs | 6 +- crates/typst-library/src/layout/columns.rs | 2 +- crates/typst-library/src/layout/container.rs | 6 +- crates/typst-library/src/layout/corners.rs | 7 +- crates/typst-library/src/layout/dir.rs | 2 +- crates/typst-library/src/layout/em.rs | 20 +- crates/typst-library/src/layout/fr.rs | 2 +- crates/typst-library/src/layout/frame.rs | 2 +- crates/typst-library/src/layout/grid/mod.rs | 8 +- .../typst-library/src/layout/grid/resolve.rs | 36 ++-- crates/typst-library/src/layout/hide.rs | 2 +- crates/typst-library/src/layout/layout.rs | 2 +- crates/typst-library/src/layout/length.rs | 6 +- crates/typst-library/src/layout/measure.rs | 2 +- crates/typst-library/src/layout/pad.rs | 2 +- crates/typst-library/src/layout/page.rs | 8 +- crates/typst-library/src/layout/place.rs | 2 +- crates/typst-library/src/layout/ratio.rs | 8 +- crates/typst-library/src/layout/rel.rs | 4 +- crates/typst-library/src/layout/repeat.rs | 2 +- crates/typst-library/src/layout/sides.rs | 13 +- crates/typst-library/src/layout/spacing.rs | 2 +- crates/typst-library/src/layout/stack.rs | 2 +- crates/typst-library/src/layout/transform.rs | 2 +- crates/typst-library/src/loading/cbor.rs | 2 +- crates/typst-library/src/loading/csv.rs | 4 +- crates/typst-library/src/loading/json.rs | 2 +- crates/typst-library/src/loading/mod.rs | 4 +- crates/typst-library/src/loading/read.rs | 2 +- crates/typst-library/src/loading/toml.rs | 2 +- crates/typst-library/src/loading/xml.rs | 4 +- crates/typst-library/src/loading/yaml.rs | 2 +- crates/typst-library/src/math/accent.rs | 4 +- crates/typst-library/src/math/attach.rs | 2 +- crates/typst-library/src/math/cancel.rs | 2 +- crates/typst-library/src/math/equation.rs | 2 +- crates/typst-library/src/math/frac.rs | 2 +- crates/typst-library/src/math/lr.rs | 2 +- crates/typst-library/src/math/matrix.rs | 10 +- crates/typst-library/src/math/mod.rs | 2 +- crates/typst-library/src/math/op.rs | 4 +- crates/typst-library/src/math/root.rs | 2 +- crates/typst-library/src/math/style.rs | 2 +- crates/typst-library/src/math/underover.rs | 2 +- .../typst-library/src/model/bibliography.rs | 29 +-- crates/typst-library/src/model/cite.rs | 4 +- crates/typst-library/src/model/document.rs | 6 +- crates/typst-library/src/model/emph.rs | 2 +- crates/typst-library/src/model/enum.rs | 2 +- crates/typst-library/src/model/figure.rs | 6 +- crates/typst-library/src/model/footnote.rs | 6 +- crates/typst-library/src/model/heading.rs | 2 +- crates/typst-library/src/model/link.rs | 6 +- crates/typst-library/src/model/list.rs | 6 +- crates/typst-library/src/model/numbering.rs | 6 +- crates/typst-library/src/model/outline.rs | 7 +- crates/typst-library/src/model/par.rs | 6 +- crates/typst-library/src/model/quote.rs | 4 +- crates/typst-library/src/model/reference.rs | 15 +- crates/typst-library/src/model/strong.rs | 2 +- crates/typst-library/src/model/table.rs | 4 +- crates/typst-library/src/model/terms.rs | 2 +- crates/typst-library/src/pdf/embed.rs | 6 +- crates/typst-library/src/routines.rs | 2 +- crates/typst-library/src/text/case.rs | 2 +- crates/typst-library/src/text/deco.rs | 2 +- crates/typst-library/src/text/font/book.rs | 22 +- crates/typst-library/src/text/font/variant.rs | 2 +- crates/typst-library/src/text/item.rs | 2 +- crates/typst-library/src/text/lang.rs | 4 +- crates/typst-library/src/text/linebreak.rs | 2 +- crates/typst-library/src/text/lorem.rs | 2 +- crates/typst-library/src/text/mod.rs | 12 +- crates/typst-library/src/text/raw.rs | 15 +- crates/typst-library/src/text/shift.rs | 2 +- crates/typst-library/src/text/smallcaps.rs | 2 +- crates/typst-library/src/text/smartquote.rs | 18 +- crates/typst-library/src/text/space.rs | 2 +- crates/typst-library/src/visualize/color.rs | 25 +-- crates/typst-library/src/visualize/curve.rs | 6 +- .../typst-library/src/visualize/gradient.rs | 10 +- .../typst-library/src/visualize/image/mod.rs | 8 +- .../src/visualize/image/raster.rs | 8 +- .../typst-library/src/visualize/image/svg.rs | 4 +- crates/typst-library/src/visualize/paint.rs | 2 +- crates/typst-library/src/visualize/path.rs | 2 +- crates/typst-library/src/visualize/polygon.rs | 2 +- crates/typst-library/src/visualize/shape.rs | 2 +- crates/typst-library/src/visualize/stroke.rs | 4 +- crates/typst-library/src/visualize/tiling.rs | 14 +- crates/typst-macros/src/elem.rs | 4 +- crates/typst-macros/src/func.rs | 2 +- crates/typst-macros/src/scope.rs | 13 +- crates/typst-macros/src/time.rs | 4 +- crates/typst-macros/src/ty.rs | 4 +- crates/typst-macros/src/util.rs | 17 +- crates/typst-pdf/src/convert.rs | 8 +- crates/typst-pdf/src/embed.rs | 4 +- crates/typst-pdf/src/image.rs | 2 +- crates/typst-pdf/src/lib.rs | 2 +- crates/typst-pdf/src/outline.rs | 8 +- crates/typst-pdf/src/paint.rs | 2 +- crates/typst-pdf/src/shape.rs | 8 +- crates/typst-pdf/src/text.rs | 4 +- crates/typst-realize/src/lib.rs | 18 +- crates/typst-render/src/lib.rs | 62 +++--- crates/typst-render/src/shape.rs | 2 +- crates/typst-render/src/text.rs | 43 ++-- crates/typst-svg/src/image.rs | 4 +- crates/typst-svg/src/lib.rs | 9 +- crates/typst-svg/src/paint.rs | 2 +- crates/typst-syntax/src/ast.rs | 2 +- crates/typst-syntax/src/file.rs | 2 +- crates/typst-syntax/src/highlight.rs | 32 ++- crates/typst-syntax/src/lexer.rs | 21 +- crates/typst-syntax/src/lib.rs | 2 +- crates/typst-syntax/src/node.rs | 21 +- crates/typst-syntax/src/package.rs | 12 +- crates/typst-syntax/src/parser.rs | 43 ++-- crates/typst-syntax/src/reparser.rs | 17 +- crates/typst-syntax/src/source.rs | 2 +- crates/typst-syntax/src/span.rs | 6 +- crates/typst-utils/src/fat.rs | 38 ++-- crates/typst-utils/src/pico.rs | 6 +- crates/typst/src/lib.rs | 6 +- docs/src/html.rs | 20 +- docs/src/lib.rs | 6 +- docs/src/link.rs | 13 +- docs/src/main.rs | 2 +- tests/fuzz/src/compile.rs | 7 +- tests/src/collect.rs | 10 +- tests/src/custom.rs | 2 +- tests/src/run.rs | 18 +- tests/src/world.rs | 6 +- 260 files changed, 1245 insertions(+), 1289 deletions(-) diff --git a/crates/typst-cli/build.rs b/crates/typst-cli/build.rs index bd6a563db..23bc2d183 100644 --- a/crates/typst-cli/build.rs +++ b/crates/typst-cli/build.rs @@ -1,10 +1,10 @@ use std::env; -use std::fs::{create_dir_all, File}; +use std::fs::{File, create_dir_all}; use std::path::Path; use std::process::Command; use clap::{CommandFactory, ValueEnum}; -use clap_complete::{generate_to, Shell}; +use clap_complete::{Shell, generate_to}; use clap_mangen::Man; #[path = "src/args.rs"] diff --git a/crates/typst-cli/src/compile.rs b/crates/typst-cli/src/compile.rs index 0db67b454..30cf1473e 100644 --- a/crates/typst-cli/src/compile.rs +++ b/crates/typst-cli/src/compile.rs @@ -10,13 +10,13 @@ use ecow::eco_format; use parking_lot::RwLock; use pathdiff::diff_paths; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; +use typst::WorldExt; use typst::diag::{ - bail, At, Severity, SourceDiagnostic, SourceResult, StrResult, Warned, + At, Severity, SourceDiagnostic, SourceResult, StrResult, Warned, bail, }; use typst::foundations::{Datetime, Smart}; use typst::layout::{Frame, Page, PageRanges, PagedDocument}; use typst::syntax::{FileId, Lines, Span}; -use typst::WorldExt; use typst_html::HtmlDocument; use typst_pdf::{PdfOptions, PdfStandards, Timestamp}; @@ -513,7 +513,9 @@ fn write_make_deps( }) .collect::, _>>() else { - bail!("failed to create make dependencies file because output path was not valid unicode") + bail!( + "failed to create make dependencies file because output path was not valid unicode" + ) }; if output_paths.is_empty() { bail!("failed to create make dependencies file because output was stdout") diff --git a/crates/typst-cli/src/download.rs b/crates/typst-cli/src/download.rs index ca1e539d4..28317ff72 100644 --- a/crates/typst-cli/src/download.rs +++ b/crates/typst-cli/src/download.rs @@ -8,8 +8,8 @@ use codespan_reporting::term::termcolor::WriteColor; use typst::utils::format_duration; use typst_kit::download::{DownloadState, Downloader, Progress}; -use crate::terminal::{self, TermOut}; use crate::ARGS; +use crate::terminal::{self, TermOut}; /// Prints download progress by writing `downloading {0}` followed by repeatedly /// updating the last terminal line. diff --git a/crates/typst-cli/src/init.rs b/crates/typst-cli/src/init.rs index 9a77fb470..845a564f4 100644 --- a/crates/typst-cli/src/init.rs +++ b/crates/typst-cli/src/init.rs @@ -4,7 +4,7 @@ use std::path::Path; use codespan_reporting::term::termcolor::{Color, ColorSpec, WriteColor}; use ecow::eco_format; use fs_extra::dir::CopyOptions; -use typst::diag::{bail, FileError, StrResult}; +use typst::diag::{FileError, StrResult, bail}; use typst::syntax::package::{ PackageManifest, PackageSpec, TemplateInfo, VersionlessPackageSpec, }; diff --git a/crates/typst-cli/src/main.rs b/crates/typst-cli/src/main.rs index 6a3b337d8..4774dd43b 100644 --- a/crates/typst-cli/src/main.rs +++ b/crates/typst-cli/src/main.rs @@ -21,8 +21,8 @@ use std::io::{self, Write}; use std::process::ExitCode; use std::sync::LazyLock; -use clap::error::ErrorKind; use clap::Parser; +use clap::error::ErrorKind; use codespan_reporting::term; use codespan_reporting::term::termcolor::WriteColor; use typst::diag::HintedStrResult; @@ -102,7 +102,7 @@ fn print_error(msg: &str) -> io::Result<()> { #[cfg(not(feature = "self-update"))] mod update { - use typst::diag::{bail, StrResult}; + use typst::diag::{StrResult, bail}; use crate::args::UpdateCommand; diff --git a/crates/typst-cli/src/query.rs b/crates/typst-cli/src/query.rs index b1a446203..30688b3b6 100644 --- a/crates/typst-cli/src/query.rs +++ b/crates/typst-cli/src/query.rs @@ -1,12 +1,12 @@ use comemo::Track; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use serde::Serialize; -use typst::diag::{bail, HintedStrResult, StrResult, Warned}; +use typst::World; +use typst::diag::{HintedStrResult, StrResult, Warned, bail}; use typst::engine::Sink; use typst::foundations::{Content, IntoValue, LocatableSelector, Scope}; use typst::layout::PagedDocument; use typst::syntax::{Span, SyntaxMode}; -use typst::World; use typst_eval::eval_string; use crate::args::{QueryCommand, SerializationFormat}; diff --git a/crates/typst-cli/src/server.rs b/crates/typst-cli/src/server.rs index 11c564e8d..0dde19f7f 100644 --- a/crates/typst-cli/src/server.rs +++ b/crates/typst-cli/src/server.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use ecow::eco_format; use parking_lot::{Condvar, Mutex, MutexGuard}; use tiny_http::{Header, Request, Response, StatusCode}; -use typst::diag::{bail, StrResult}; +use typst::diag::{StrResult, bail}; use crate::args::{Input, ServerArgs}; diff --git a/crates/typst-cli/src/timings.rs b/crates/typst-cli/src/timings.rs index 3d10bbc67..89b9523bf 100644 --- a/crates/typst-cli/src/timings.rs +++ b/crates/typst-cli/src/timings.rs @@ -2,9 +2,9 @@ use std::fs::File; use std::io::BufWriter; use std::path::{Path, PathBuf}; -use typst::diag::{bail, StrResult}; -use typst::syntax::Span; use typst::World; +use typst::diag::{StrResult, bail}; +use typst::syntax::Span; use crate::args::{CliArguments, Command}; use crate::world::SystemWorld; diff --git a/crates/typst-cli/src/update.rs b/crates/typst-cli/src/update.rs index ec8ca71e8..ec074c6c4 100644 --- a/crates/typst-cli/src/update.rs +++ b/crates/typst-cli/src/update.rs @@ -6,7 +6,7 @@ use ecow::eco_format; use semver::Version; use serde::Deserialize; use tempfile::NamedTempFile; -use typst::diag::{bail, StrResult}; +use typst::diag::{StrResult, bail}; use typst_kit::download::Downloader; use xz2::bufread::XzDecoder; use zip::ZipArchive; diff --git a/crates/typst-cli/src/watch.rs b/crates/typst-cli/src/watch.rs index 630d340b2..765f86808 100644 --- a/crates/typst-cli/src/watch.rs +++ b/crates/typst-cli/src/watch.rs @@ -10,12 +10,12 @@ use codespan_reporting::term::{self, termcolor}; use ecow::eco_format; use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher as _}; use same_file::is_same_file; -use typst::diag::{bail, warning, StrResult}; +use typst::diag::{StrResult, bail, warning}; use typst::syntax::Span; use typst::utils::format_duration; use crate::args::{Input, Output, WatchCommand}; -use crate::compile::{compile_once, print_diagnostics, CompileConfig}; +use crate::compile::{CompileConfig, compile_once, print_diagnostics}; use crate::timings::Timer; use crate::world::{SystemWorld, WorldCreationError}; use crate::{print_error, terminal}; diff --git a/crates/typst-cli/src/world.rs b/crates/typst-cli/src/world.rs index 900199354..42083ef20 100644 --- a/crates/typst-cli/src/world.rs +++ b/crates/typst-cli/src/world.rs @@ -5,7 +5,7 @@ use std::sync::{LazyLock, OnceLock}; use std::{fmt, fs, io, mem}; use chrono::{DateTime, Datelike, FixedOffset, Local, Utc}; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use parking_lot::Mutex; use typst::diag::{FileError, FileResult}; use typst::foundations::{Bytes, Datetime, Dict, IntoValue}; @@ -362,9 +362,10 @@ impl SlotCell { ) -> FileResult { // If we accessed the file already in this compilation, retrieve it. if mem::replace(&mut self.accessed, true) - && let Some(data) = &self.data { - return data.clone(); - } + && let Some(data) = &self.data + { + return data.clone(); + } // Read and hash the file. let result = timed!("loading file", load()); @@ -372,9 +373,10 @@ impl SlotCell { // If the file contents didn't change, yield the old processed data. if mem::replace(&mut self.fingerprint, fingerprint) == fingerprint - && let Some(data) = &self.data { - return data.clone(); - } + && let Some(data) = &self.data + { + return data.clone(); + } let prev = self.data.take().and_then(Result::ok); let value = result.and_then(|data| f(data, prev)); diff --git a/crates/typst-eval/src/access.rs b/crates/typst-eval/src/access.rs index ddcc8b98b..c82b9339a 100644 --- a/crates/typst-eval/src/access.rs +++ b/crates/typst-eval/src/access.rs @@ -1,9 +1,9 @@ use ecow::eco_format; -use typst_library::diag::{bail, At, Hint, SourceResult, Trace, Tracepoint}; +use typst_library::diag::{At, Hint, SourceResult, Trace, Tracepoint, bail}; use typst_library::foundations::{Dict, Value}; use typst_syntax::ast::{self, AstNode}; -use crate::{call_method_access, is_accessor_method, Eval, Vm}; +use crate::{Eval, Vm, call_method_access, is_accessor_method}; /// Access an expression mutably. pub(crate) trait Access { @@ -30,9 +30,10 @@ impl Access for ast::Ident<'_> { fn access<'a>(self, vm: &'a mut Vm) -> SourceResult<&'a mut Value> { let span = self.span(); if vm.inspected == Some(span) - && let Ok(binding) = vm.scopes.get(&self) { - vm.trace(binding.read().clone()); - } + && let Ok(binding) = vm.scopes.get(&self) + { + vm.trace(binding.read().clone()); + } vm.scopes .get_mut(&self) .and_then(|b| b.write().map_err(Into::into)) diff --git a/crates/typst-eval/src/binding.rs b/crates/typst-eval/src/binding.rs index f3802f079..9a53ac069 100644 --- a/crates/typst-eval/src/binding.rs +++ b/crates/typst-eval/src/binding.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; use ecow::eco_format; -use typst_library::diag::{bail, error, At, SourceDiagnostic, SourceResult}; +use typst_library::diag::{At, SourceDiagnostic, SourceResult, bail, error}; use typst_library::foundations::{Array, Dict, Value}; use typst_syntax::ast::{self, AstNode}; diff --git a/crates/typst-eval/src/call.rs b/crates/typst-eval/src/call.rs index eaeabbab3..c4087f6bb 100644 --- a/crates/typst-eval/src/call.rs +++ b/crates/typst-eval/src/call.rs @@ -1,8 +1,9 @@ use comemo::{Tracked, TrackedMut}; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; +use typst_library::World; use typst_library::diag::{ - bail, error, At, HintedStrResult, HintedString, SourceDiagnostic, SourceResult, - Trace, Tracepoint, + At, HintedStrResult, HintedString, SourceDiagnostic, SourceResult, Trace, Tracepoint, + bail, error, }; use typst_library::engine::{Engine, Sink, Traced}; use typst_library::foundations::{ @@ -12,12 +13,11 @@ use typst_library::foundations::{ use typst_library::introspection::Introspector; use typst_library::math::LrElem; use typst_library::routines::Routines; -use typst_library::World; use typst_syntax::ast::{self, AstNode, Ident}; use typst_syntax::{Span, Spanned, SyntaxNode}; use typst_utils::LazyHash; -use crate::{call_method_mut, is_mutating_method, Access, Eval, FlowEvent, Route, Vm}; +use crate::{Access, Eval, FlowEvent, Route, Vm, call_method_mut, is_mutating_method}; impl Eval for ast::FuncCall<'_> { type Output = Value; diff --git a/crates/typst-eval/src/code.rs b/crates/typst-eval/src/code.rs index 1930ebc48..d3e0c937f 100644 --- a/crates/typst-eval/src/code.rs +++ b/crates/typst-eval/src/code.rs @@ -1,9 +1,9 @@ -use ecow::{eco_vec, EcoVec}; -use typst_library::diag::{bail, error, warning, At, SourceResult}; +use ecow::{EcoVec, eco_vec}; +use typst_library::diag::{At, SourceResult, bail, error, warning}; use typst_library::engine::Engine; use typst_library::foundations::{ - ops, Array, Capturer, Closure, Content, ContextElem, Dict, Func, NativeElement, - Selector, Str, Value, + Array, Capturer, Closure, Content, ContextElem, Dict, Func, NativeElement, Selector, + Str, Value, ops, }; use typst_library::introspection::{Counter, State}; use typst_syntax::ast::{self, AstNode}; @@ -324,19 +324,18 @@ impl Eval for ast::FieldAccess<'_> { }; // Check whether this is a get rule field access. - if let Value::Func(func) = &value && - let Some(element) = func.element() && - let Some(id) = element.field_id(&field) && - let styles = vm.context.styles().at(field.span()) && - let Ok(value) = element.field_from_styles( - id, - styles.as_ref().map(|&s| s).unwrap_or_default(), - ) { - // Only validate the context once we know that this is indeed - // a field from the style chain. - let _ = styles?; - return Ok(value); - } + if let Value::Func(func) = &value + && let Some(element) = func.element() + && let Some(id) = element.field_id(&field) + && let styles = vm.context.styles().at(field.span()) + && let Ok(value) = element + .field_from_styles(id, styles.as_ref().map(|&s| s).unwrap_or_default()) + { + // Only validate the context once we know that this is indeed + // a field from the style chain. + let _ = styles?; + return Ok(value); + } Err(err) } diff --git a/crates/typst-eval/src/flow.rs b/crates/typst-eval/src/flow.rs index b5ba487f5..dcc2073bd 100644 --- a/crates/typst-eval/src/flow.rs +++ b/crates/typst-eval/src/flow.rs @@ -1,10 +1,10 @@ -use typst_library::diag::{bail, error, At, SourceDiagnostic, SourceResult}; -use typst_library::foundations::{ops, IntoValue, Value}; +use typst_library::diag::{At, SourceDiagnostic, SourceResult, bail, error}; +use typst_library::foundations::{IntoValue, Value, ops}; use typst_syntax::ast::{self, AstNode}; use typst_syntax::{Span, SyntaxKind, SyntaxNode}; use unicode_segmentation::UnicodeSegmentation; -use crate::{destructure, Eval, Vm}; +use crate::{Eval, Vm, destructure}; /// The maximum number of loop iterations. const MAX_ITERATIONS: usize = 10_000; diff --git a/crates/typst-eval/src/import.rs b/crates/typst-eval/src/import.rs index 138d7ccfe..1e091a9cf 100644 --- a/crates/typst-eval/src/import.rs +++ b/crates/typst-eval/src/import.rs @@ -1,16 +1,16 @@ use comemo::TrackedMut; -use ecow::{eco_format, eco_vec, EcoString}; +use ecow::{EcoString, eco_format, eco_vec}; +use typst_library::World; use typst_library::diag::{ - bail, error, warning, At, FileError, SourceResult, Trace, Tracepoint, + At, FileError, SourceResult, Trace, Tracepoint, bail, error, warning, }; use typst_library::engine::Engine; use typst_library::foundations::{Binding, Content, Module, Value}; -use typst_library::World; use typst_syntax::ast::{self, AstNode, BareImportError}; use typst_syntax::package::{PackageManifest, PackageSpec}; use typst_syntax::{FileId, Span, VirtualPath}; -use crate::{eval, Eval, Vm}; +use crate::{Eval, Vm, eval}; impl Eval for ast::ModuleImport<'_> { type Output = Value; @@ -47,13 +47,14 @@ impl Eval for ast::ModuleImport<'_> { let new_name = self.new_name(); if let Some(new_name) = new_name { if let ast::Expr::Ident(ident) = self.source() - && ident.as_str() == new_name.as_str() { - // Warn on `import x as x` - vm.engine.sink.warn(warning!( - new_name.span(), - "unnecessary import rename to same name", - )); - } + && ident.as_str() == new_name.as_str() + { + // Warn on `import x as x` + vm.engine.sink.warn(warning!( + new_name.span(), + "unnecessary import rename to same name", + )); + } // Define renamed module on the scope. vm.define(new_name, source.clone()); @@ -144,12 +145,12 @@ impl Eval for ast::ModuleImport<'_> { if let ast::ImportItem::Renamed(renamed_item) = &item && renamed_item.original_name().as_str() == renamed_item.new_name().as_str() - { - vm.engine.sink.warn(warning!( - renamed_item.new_name().span(), - "unnecessary import rename to same name", - )); - } + { + vm.engine.sink.warn(warning!( + renamed_item.new_name().span(), + "unnecessary import rename to same name", + )); + } vm.bind(item.bound_name(), binding.clone()); } diff --git a/crates/typst-eval/src/lib.rs b/crates/typst-eval/src/lib.rs index e4bbe4f0f..965b37c96 100644 --- a/crates/typst-eval/src/lib.rs +++ b/crates/typst-eval/src/lib.rs @@ -14,7 +14,7 @@ mod methods; mod rules; mod vm; -pub use self::call::{eval_closure, CapturesVisitor}; +pub use self::call::{CapturesVisitor, eval_closure}; pub use self::flow::FlowEvent; pub use self::import::import; pub use self::vm::Vm; @@ -24,14 +24,14 @@ use self::binding::*; use self::methods::*; use comemo::{Track, Tracked, TrackedMut}; -use typst_library::diag::{bail, SourceResult}; +use typst_library::World; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{Context, Module, NativeElement, Scope, Scopes, Value}; use typst_library::introspection::Introspector; use typst_library::math::EquationElem; use typst_library::routines::Routines; -use typst_library::World; -use typst_syntax::{ast, parse, parse_code, parse_math, Source, Span, SyntaxMode}; +use typst_syntax::{Source, Span, SyntaxMode, ast, parse, parse_code, parse_math}; /// Evaluate a source file and return the resulting module. #[comemo::memoize] diff --git a/crates/typst-eval/src/markup.rs b/crates/typst-eval/src/markup.rs index baa548459..772494b61 100644 --- a/crates/typst-eval/src/markup.rs +++ b/crates/typst-eval/src/markup.rs @@ -1,4 +1,4 @@ -use typst_library::diag::{warning, At, SourceResult}; +use typst_library::diag::{At, SourceResult, warning}; use typst_library::foundations::{ Content, Label, NativeElement, Repr, Smart, Symbol, Unlabellable, Value, }; diff --git a/crates/typst-eval/src/ops.rs b/crates/typst-eval/src/ops.rs index 9a8eb5239..af129411c 100644 --- a/crates/typst-eval/src/ops.rs +++ b/crates/typst-eval/src/ops.rs @@ -1,8 +1,8 @@ use typst_library::diag::{At, HintedStrResult, SourceResult}; -use typst_library::foundations::{ops, IntoValue, Value}; +use typst_library::foundations::{IntoValue, Value, ops}; use typst_syntax::ast::{self, AstNode}; -use crate::{access_dict, Access, Eval, Vm}; +use crate::{Access, Eval, Vm, access_dict}; impl Eval for ast::Unary<'_> { type Output = Value; @@ -77,11 +77,12 @@ fn apply_assignment( // An assignment to a dictionary field is different from a normal access // since it can create the field instead of just modifying it. if binary.op() == ast::BinOp::Assign - && let ast::Expr::FieldAccess(access) = lhs { - let dict = access_dict(vm, access)?; - dict.insert(access.field().get().clone().into(), rhs); - return Ok(Value::None); - } + && let ast::Expr::FieldAccess(access) = lhs + { + let dict = access_dict(vm, access)?; + dict.insert(access.field().get().clone().into(), rhs); + return Ok(Value::None); + } let location = binary.lhs().access(vm)?; let lhs = std::mem::take(&mut *location); diff --git a/crates/typst-eval/src/rules.rs b/crates/typst-eval/src/rules.rs index bf4a80780..011478a1e 100644 --- a/crates/typst-eval/src/rules.rs +++ b/crates/typst-eval/src/rules.rs @@ -1,4 +1,4 @@ -use typst_library::diag::{warning, At, SourceResult}; +use typst_library::diag::{At, SourceResult, warning}; use typst_library::foundations::{ Element, Func, Recipe, Selector, ShowableSelector, Styles, Transformation, }; @@ -13,9 +13,10 @@ impl Eval for ast::SetRule<'_> { fn eval(self, vm: &mut Vm) -> SourceResult { if let Some(condition) = self.condition() - && !condition.eval(vm)?.cast::().at(condition.span())? { - return Ok(Styles::new()); - } + && !condition.eval(vm)?.cast::().at(condition.span())? + { + return Ok(Styles::new()); + } let target = self.target(); let target = target @@ -57,16 +58,16 @@ impl Eval for ast::ShowRule<'_> { /// Migration hint for `show par: set block(spacing: ..)`. fn check_show_par_set_block(vm: &mut Vm, recipe: &Recipe) { - if let Some(Selector::Elem(elem, _)) = recipe.selector() && - *elem == Element::of::() && - let Transformation::Style(styles) = recipe.transform() && - (styles.has(BlockElem::above) || styles.has(BlockElem::below)) - { - vm.engine.sink.warn(warning!( + if let Some(Selector::Elem(elem, _)) = recipe.selector() + && *elem == Element::of::() + && let Transformation::Style(styles) = recipe.transform() + && (styles.has(BlockElem::above) || styles.has(BlockElem::below)) + { + vm.engine.sink.warn(warning!( recipe.span(), "`show par: set block(spacing: ..)` has no effect anymore"; hint: "write `set par(spacing: ..)` instead"; hint: "this is specific to paragraphs as they are not considered blocks anymore" )) - } + } } diff --git a/crates/typst-eval/src/vm.rs b/crates/typst-eval/src/vm.rs index 52cfb4b5b..2c62c8b40 100644 --- a/crates/typst-eval/src/vm.rs +++ b/crates/typst-eval/src/vm.rs @@ -1,10 +1,10 @@ use comemo::Tracked; +use typst_library::World; use typst_library::diag::warning; use typst_library::engine::Engine; use typst_library::foundations::{Binding, Context, IntoValue, Scopes, Value}; -use typst_library::World; -use typst_syntax::ast::{self, AstNode}; use typst_syntax::Span; +use typst_syntax::ast::{self, AstNode}; use crate::FlowEvent; diff --git a/crates/typst-html/src/convert.rs b/crates/typst-html/src/convert.rs index 817b0f025..09d89313c 100644 --- a/crates/typst-html/src/convert.rs +++ b/crates/typst-html/src/convert.rs @@ -1,4 +1,4 @@ -use typst_library::diag::{warning, SourceResult}; +use typst_library::diag::{SourceResult, warning}; use typst_library::engine::Engine; use typst_library::foundations::{Content, StyleChain, Target, TargetElem}; use typst_library::introspection::{SplitLocator, TagElem}; @@ -8,7 +8,7 @@ use typst_library::routines::Pair; use typst_library::text::{LinebreakElem, SmartQuoteElem, SpaceElem, TextElem}; use crate::fragment::html_fragment; -use crate::{attr, tag, FrameElem, HtmlElem, HtmlElement, HtmlFrame, HtmlNode}; +use crate::{FrameElem, HtmlElem, HtmlElement, HtmlFrame, HtmlNode, attr, tag}; /// Converts realized content into HTML nodes. pub fn convert_to_nodes<'a>( diff --git a/crates/typst-html/src/document.rs b/crates/typst-html/src/document.rs index c581df05f..ca84d3354 100644 --- a/crates/typst-html/src/document.rs +++ b/crates/typst-html/src/document.rs @@ -2,7 +2,8 @@ use std::collections::HashSet; use std::num::NonZeroUsize; use comemo::{Tracked, TrackedMut}; -use typst_library::diag::{bail, SourceResult}; +use typst_library::World; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{Content, StyleChain}; use typst_library::introspection::{ @@ -11,11 +12,10 @@ use typst_library::introspection::{ use typst_library::layout::{Point, Position, Transform}; use typst_library::model::DocumentInfo; use typst_library::routines::{Arenas, RealizationKind, Routines}; -use typst_library::World; use typst_syntax::Span; use typst_utils::NonZeroExt; -use crate::{attr, tag, HtmlDocument, HtmlElement, HtmlNode}; +use crate::{HtmlDocument, HtmlElement, HtmlNode, attr, tag}; /// Produce an HTML document from content. /// diff --git a/crates/typst-html/src/dom.rs b/crates/typst-html/src/dom.rs index e7f5fcbcd..2c9a2e640 100644 --- a/crates/typst-html/src/dom.rs +++ b/crates/typst-html/src/dom.rs @@ -1,8 +1,8 @@ use std::fmt::{self, Debug, Display, Formatter}; use ecow::{EcoString, EcoVec}; -use typst_library::diag::{bail, HintedStrResult, StrResult}; -use typst_library::foundations::{cast, Dict, Repr, Str, StyleChain}; +use typst_library::diag::{HintedStrResult, StrResult, bail}; +use typst_library::foundations::{Dict, Repr, Str, StyleChain, cast}; use typst_library::introspection::{Introspector, Tag}; use typst_library::layout::{Abs, Frame, Point}; use typst_library::model::DocumentInfo; diff --git a/crates/typst-html/src/encode.rs b/crates/typst-html/src/encode.rs index 02c3f16de..2d21109c1 100644 --- a/crates/typst-html/src/encode.rs +++ b/crates/typst-html/src/encode.rs @@ -1,12 +1,12 @@ use std::fmt::Write; -use typst_library::diag::{bail, At, SourceResult, StrResult}; +use typst_library::diag::{At, SourceResult, StrResult, bail}; use typst_library::foundations::Repr; use typst_library::introspection::Introspector; use typst_syntax::Span; use crate::{ - attr, charsets, tag, HtmlDocument, HtmlElement, HtmlFrame, HtmlNode, HtmlTag, + HtmlDocument, HtmlElement, HtmlFrame, HtmlNode, HtmlTag, attr, charsets, tag, }; /// Encodes an HTML document into a string. @@ -262,11 +262,7 @@ impl RawMode { { // Template literals can be multi-line, so indent may change // the semantics of the JavaScript. - if text.contains('`') { - Self::Wrap - } else { - Self::Indent - } + if text.contains('`') { Self::Wrap } else { Self::Indent } } tag::style => Self::Indent, _ => Self::Keep, diff --git a/crates/typst-html/src/fragment.rs b/crates/typst-html/src/fragment.rs index 78ae7dee0..66a59b678 100644 --- a/crates/typst-html/src/fragment.rs +++ b/crates/typst-html/src/fragment.rs @@ -4,8 +4,8 @@ use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{Content, StyleChain}; use typst_library::introspection::{Introspector, Locator, LocatorLink}; -use typst_library::routines::{Arenas, FragmentKind, RealizationKind, Routines}; use typst_library::World; +use typst_library::routines::{Arenas, FragmentKind, RealizationKind, Routines}; use crate::HtmlNode; diff --git a/crates/typst-html/src/lib.rs b/crates/typst-html/src/lib.rs index 42b3c5d6f..373da607f 100644 --- a/crates/typst-html/src/lib.rs +++ b/crates/typst-html/src/lib.rs @@ -19,8 +19,8 @@ pub use self::encode::html; pub use self::rules::register; use ecow::EcoString; -use typst_library::foundations::{Content, Module, Scope}; use typst_library::Category; +use typst_library::foundations::{Content, Module, Scope}; use typst_macros::elem; /// Creates the module with all HTML definitions. @@ -86,11 +86,7 @@ impl HtmlElem { attr: HtmlAttr, value: Option>, ) -> Self { - if let Some(value) = value { - self.with_attr(attr, value) - } else { - self - } + if let Some(value) = value { self.with_attr(attr, value) } else { self } } /// Adds CSS styles to an element. diff --git a/crates/typst-html/src/link.rs b/crates/typst-html/src/link.rs index 0fcbe906a..ad70f06fe 100644 --- a/crates/typst-html/src/link.rs +++ b/crates/typst-html/src/link.rs @@ -1,14 +1,14 @@ use std::collections::{HashMap, HashSet, VecDeque}; use comemo::Track; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_library::foundations::{Label, NativeElement}; use typst_library::introspection::{Introspector, Location, Tag}; use typst_library::layout::{Frame, FrameItem, Point}; use typst_library::model::{Destination, LinkElem}; use typst_utils::PicoStr; -use crate::{attr, tag, HtmlElement, HtmlNode}; +use crate::{HtmlElement, HtmlNode, attr, tag}; /// Searches for links within a frame. /// diff --git a/crates/typst-html/src/rules.rs b/crates/typst-html/src/rules.rs index 14885bd36..c358a181e 100644 --- a/crates/typst-html/src/rules.rs +++ b/crates/typst-html/src/rules.rs @@ -1,12 +1,12 @@ use std::num::NonZeroUsize; -use ecow::{eco_format, EcoVec}; -use typst_library::diag::{warning, At}; +use ecow::{EcoVec, eco_format}; +use typst_library::diag::{At, warning}; use typst_library::foundations::{ Content, NativeElement, NativeRuleMap, ShowFn, Smart, StyleChain, Target, }; use typst_library::introspection::{Counter, Locator}; -use typst_library::layout::resolve::{table_to_cellgrid, Cell, CellGrid, Entry}; +use typst_library::layout::resolve::{Cell, CellGrid, Entry, table_to_cellgrid}; use typst_library::layout::{OuterVAlignment, Sizing}; use typst_library::model::{ Attribution, CiteElem, CiteGroup, Destination, EmphElem, EnumElem, FigureCaption, @@ -19,7 +19,7 @@ use typst_library::text::{ }; use typst_library::visualize::ImageElem; -use crate::{attr, css, tag, FrameElem, HtmlAttrs, HtmlElem, HtmlTag}; +use crate::{FrameElem, HtmlAttrs, HtmlElem, HtmlTag, attr, css, tag}; /// Registers show rules for the [HTML target](Target::Html). pub fn register(rules: &mut NativeRuleMap) { @@ -240,10 +240,10 @@ const QUOTE_RULE: ShowFn = |elem, _, styles| { let mut blockquote = HtmlElem::new(tag::blockquote).with_body(Some(realized)); if let Some(Attribution::Content(attribution)) = attribution && let Some(link) = attribution.to_packed::() - && let LinkTarget::Dest(Destination::Url(url)) = &link.dest { - blockquote = - blockquote.with_attr(attr::cite, url.clone().into_inner()); - } + && let LinkTarget::Dest(Destination::Url(url)) = &link.dest + { + blockquote = blockquote.with_attr(attr::cite, url.clone().into_inner()); + } realized = blockquote.pack().spanned(span); diff --git a/crates/typst-html/src/typed.rs b/crates/typst-html/src/typed.rs index 190ff4f16..56f090e91 100644 --- a/crates/typst-html/src/typed.rs +++ b/crates/typst-html/src/typed.rs @@ -9,9 +9,9 @@ use std::sync::LazyLock; use bumpalo::Bump; use comemo::Tracked; -use ecow::{eco_format, eco_vec, EcoString}; +use ecow::{EcoString, eco_format, eco_vec}; use typst_assets::html as data; -use typst_library::diag::{bail, At, Hint, HintedStrResult, SourceResult}; +use typst_library::diag::{At, Hint, HintedStrResult, SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{ Args, Array, AutoValue, CastInfo, Content, Context, Datetime, Dict, Duration, @@ -22,7 +22,7 @@ use typst_library::layout::{Axes, Axis, Dir, Length}; use typst_library::visualize::Color; use typst_macros::cast; -use crate::{css, tag, HtmlAttr, HtmlAttrs, HtmlElem, HtmlTag}; +use crate::{HtmlAttr, HtmlAttrs, HtmlElem, HtmlTag, css, tag}; /// Hook up all typed HTML definitions. pub(super) fn define(html: &mut Scope) { diff --git a/crates/typst-ide/src/analyze.rs b/crates/typst-ide/src/analyze.rs index e7fd8af8e..6f80c85d4 100644 --- a/crates/typst-ide/src/analyze.rs +++ b/crates/typst-ide/src/analyze.rs @@ -1,11 +1,11 @@ use std::collections::HashSet; use comemo::Track; -use ecow::{eco_vec, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_vec}; use typst::foundations::{Label, Styles, Value}; use typst::layout::PagedDocument; use typst::model::{BibliographyElem, FigureElem}; -use typst::syntax::{ast, LinkedNode, SyntaxKind}; +use typst::syntax::{LinkedNode, SyntaxKind, ast}; use crate::IdeWorld; @@ -28,14 +28,17 @@ pub fn analyze_expr( ast::Expr::Str(v) => Value::Str(v.get().into()), _ => { if node.kind() == SyntaxKind::Contextual - && let Some(child) = node.children().next_back() { - return analyze_expr(world, &child); - } + && let Some(child) = node.children().next_back() + { + return analyze_expr(world, &child); + } if let Some(parent) = node.parent() - && parent.kind() == SyntaxKind::FieldAccess && node.index() > 0 { - return analyze_expr(world, parent); - } + && parent.kind() == SyntaxKind::FieldAccess + && node.index() > 0 + { + return analyze_expr(world, parent); + } return typst::trace::(world.upcast(), node.span()); } diff --git a/crates/typst-ide/src/complete.rs b/crates/typst-ide/src/complete.rs index a974eb313..87b592ec0 100644 --- a/crates/typst-ide/src/complete.rs +++ b/crates/typst-ide/src/complete.rs @@ -2,17 +2,17 @@ use std::cmp::Reverse; use std::collections::{BTreeMap, HashSet}; use std::ffi::OsStr; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use serde::{Deserialize, Serialize}; use typst::foundations::{ - fields_on, repr, AutoValue, CastInfo, Func, Label, NoneValue, ParamInfo, Repr, - StyleChain, Styles, Type, Value, + AutoValue, CastInfo, Func, Label, NoneValue, ParamInfo, Repr, StyleChain, Styles, + Type, Value, fields_on, repr, }; use typst::layout::{Alignment, Dir, PagedDocument}; use typst::syntax::ast::AstNode; use typst::syntax::{ - ast, is_id_continue, is_id_start, is_ident, FileId, LinkedNode, Side, Source, - SyntaxKind, + FileId, LinkedNode, Side, Source, SyntaxKind, ast, is_id_continue, is_id_start, + is_ident, }; use typst::text::{FontFlags, RawElem}; use typst::visualize::Color; @@ -21,7 +21,7 @@ use unscanny::Scanner; use crate::utils::{ check_value_recursively, globals, plain_docs_sentence, summarize_font_family, }; -use crate::{analyze_expr, analyze_import, analyze_labels, named_items, IdeWorld}; +use crate::{IdeWorld, analyze_expr, analyze_import, analyze_labels, named_items}; /// Autocomplete a cursor position in a source file. /// @@ -144,23 +144,23 @@ fn complete_markup(ctx: &mut CompletionContext) -> bool { } // Behind a half-completed binding: "#let x = |". - if let Some(prev) = ctx.leaf.prev_leaf() + if let Some(prev) = ctx.leaf.prev_leaf() && prev.kind() == SyntaxKind::Eq && prev.parent_kind() == Some(SyntaxKind::LetBinding) - { - ctx.from = ctx.cursor; - code_completions(ctx, false); - return true; - } + { + ctx.from = ctx.cursor; + code_completions(ctx, false); + return true; + } // Behind a half-completed context block: "#context |". - if let Some(prev) = ctx.leaf.prev_leaf() + if let Some(prev) = ctx.leaf.prev_leaf() && prev.kind() == SyntaxKind::Context - { - ctx.from = ctx.cursor; - code_completions(ctx, false); - return true; - } + { + ctx.from = ctx.cursor; + code_completions(ctx, false); + return true; + } // Directly after a raw block. let mut s = Scanner::new(ctx.text); @@ -368,34 +368,35 @@ fn complete_field_accesses(ctx: &mut CompletionContext) -> bool { ); // Behind an expression plus dot: "emoji.|". - if (ctx.leaf.kind() == SyntaxKind::Dot - || (matches!(ctx.leaf.kind(), SyntaxKind::Text | SyntaxKind::MathText) - && ctx.leaf.text() == ".")) + if (ctx.leaf.kind() == SyntaxKind::Dot + || (matches!(ctx.leaf.kind(), SyntaxKind::Text | SyntaxKind::MathText) + && ctx.leaf.text() == ".")) && ctx.leaf.range().end == ctx.cursor && let Some(prev) = ctx.leaf.prev_sibling() && (!in_markup || prev.range().end == ctx.leaf.range().start) && prev.is::() - && (prev.parent_kind() != Some(SyntaxKind::Markup) || - prev.prev_sibling_kind() == Some(SyntaxKind::Hash)) + && (prev.parent_kind() != Some(SyntaxKind::Markup) + || prev.prev_sibling_kind() == Some(SyntaxKind::Hash)) && let Some((value, styles)) = analyze_expr(ctx.world, &prev).into_iter().next() - { - ctx.from = ctx.cursor; - field_access_completions(ctx, &value, &styles); - return true; - } + { + ctx.from = ctx.cursor; + field_access_completions(ctx, &value, &styles); + return true; + } // Behind a started field access: "emoji.fa|". - if ctx.leaf.kind() == SyntaxKind::Ident + if ctx.leaf.kind() == SyntaxKind::Ident && let Some(prev) = ctx.leaf.prev_sibling() && prev.kind() == SyntaxKind::Dot && let Some(prev_prev) = prev.prev_sibling() && prev_prev.is::() - && let Some((value, styles)) = analyze_expr(ctx.world, &prev_prev).into_iter().next() - { - ctx.from = ctx.leaf.offset(); - field_access_completions(ctx, &value, &styles); - return true; - } + && let Some((value, styles)) = + analyze_expr(ctx.world, &prev_prev).into_iter().next() + { + ctx.from = ctx.leaf.offset(); + field_access_completions(ctx, &value, &styles); + return true; + } false } @@ -498,36 +499,37 @@ fn complete_open_labels(ctx: &mut CompletionContext) -> bool { fn complete_imports(ctx: &mut CompletionContext) -> bool { // In an import path for a file or package: // "#import "|", - if let Some(SyntaxKind::ModuleImport | SyntaxKind::ModuleInclude) = ctx.leaf.parent_kind() + if let Some(SyntaxKind::ModuleImport | SyntaxKind::ModuleInclude) = + ctx.leaf.parent_kind() && let Some(ast::Expr::Str(str)) = ctx.leaf.cast() - { - let value = str.get(); - ctx.from = ctx.leaf.offset(); - if value.starts_with('@') { - let all_versions = value.contains(':'); - ctx.package_completions(all_versions); - } else { - ctx.file_completions_with_extensions(&["typ"]); - } - return true; + { + let value = str.get(); + ctx.from = ctx.leaf.offset(); + if value.starts_with('@') { + let all_versions = value.contains(':'); + ctx.package_completions(all_versions); + } else { + ctx.file_completions_with_extensions(&["typ"]); } + return true; + } // Behind an import list: // "#import "path.typ": |", // "#import "path.typ": a, b, |". - if let Some(prev) = ctx.leaf.prev_sibling() + if let Some(prev) = ctx.leaf.prev_sibling() && let Some(ast::Expr::ModuleImport(import)) = prev.get().cast() && let Some(ast::Imports::Items(items)) = import.imports() && let Some(source) = prev.children().find(|child| child.is::()) - { - ctx.from = ctx.cursor; - import_item_completions(ctx, items, &source); - return true; - } + { + ctx.from = ctx.cursor; + import_item_completions(ctx, items, &source); + return true; + } // Behind a half-started identifier in an import list: // "#import "path.typ": thi|", - if ctx.leaf.kind() == SyntaxKind::Ident + if ctx.leaf.kind() == SyntaxKind::Ident && let Some(parent) = ctx.leaf.parent() && parent.kind() == SyntaxKind::ImportItemPath && let Some(grand) = parent.parent() @@ -536,11 +538,11 @@ fn complete_imports(ctx: &mut CompletionContext) -> bool { && let Some(ast::Expr::ModuleImport(import)) = great.get().cast() && let Some(ast::Imports::Items(items)) = import.imports() && let Some(source) = great.children().find(|child| child.is::()) - { - ctx.from = ctx.leaf.offset(); - import_item_completions(ctx, items, &source); - return true; - } + { + ctx.from = ctx.leaf.offset(); + import_item_completions(ctx, items, &source); + return true; + } false } @@ -589,14 +591,14 @@ fn complete_rules(ctx: &mut CompletionContext) -> bool { } // Behind a half-completed show rule: "show strong: |". - if let Some(prev) = ctx.leaf.prev_leaf() + if let Some(prev) = ctx.leaf.prev_leaf() && matches!(prev.kind(), SyntaxKind::Colon) && matches!(prev.parent_kind(), Some(SyntaxKind::ShowRule)) - { - ctx.from = ctx.cursor; - show_rule_recipe_completions(ctx); - return true; - } + { + ctx.from = ctx.cursor; + show_rule_recipe_completions(ctx); + return true; + } false } @@ -662,8 +664,7 @@ fn show_rule_recipe_completions(ctx: &mut CompletionContext) { /// Complete call and set rule parameters. fn complete_params(ctx: &mut CompletionContext) -> bool { // Ensure that we are in a function call or set rule's argument list. - let (callee, set, args, args_linked) = - if let Some(parent) = ctx.leaf.parent() + let (callee, set, args, args_linked) = if let Some(parent) = ctx.leaf.parent() && let Some(parent) = match parent.kind() { SyntaxKind::Named => parent.parent(), _ => Some(parent), @@ -676,12 +677,11 @@ fn complete_params(ctx: &mut CompletionContext) -> bool { ast::Expr::FuncCall(call) => Some(call.callee()), ast::Expr::SetRule(set) => Some(set.target()), _ => None, - } - { - (callee, set, args, parent) - } else { - return false; - }; + } { + (callee, set, args, parent) + } else { + return false; + }; // Find the piece of syntax that decides what we're completing. let mut deciding = ctx.leaf.clone(); @@ -697,30 +697,30 @@ fn complete_params(ctx: &mut CompletionContext) -> bool { } // Parameter values: "func(param:|)", "func(param: |)". - if let SyntaxKind::Colon = deciding.kind() + if let SyntaxKind::Colon = deciding.kind() && let Some(prev) = deciding.prev_leaf() && let Some(param) = prev.get().cast::() - { - if let Some(next) = deciding.next_leaf() { - ctx.from = ctx.cursor.min(next.offset()); - } - - named_param_value_completions(ctx, callee, ¶m); - return true; + { + if let Some(next) = deciding.next_leaf() { + ctx.from = ctx.cursor.min(next.offset()); } + named_param_value_completions(ctx, callee, ¶m); + return true; + } + // Parameters: "func(|)", "func(hi|)", "func(12,|)". - if let SyntaxKind::LeftParen | SyntaxKind::Comma = deciding.kind() + if let SyntaxKind::LeftParen | SyntaxKind::Comma = deciding.kind() && (deciding.kind() != SyntaxKind::Comma || deciding.range().end < ctx.cursor) - { - if let Some(next) = deciding.next_leaf() { - ctx.from = ctx.cursor.min(next.offset()); - } - - param_completions(ctx, callee, set, args, args_linked); - return true; + { + if let Some(next) = deciding.next_leaf() { + ctx.from = ctx.cursor.min(next.offset()); } + param_completions(ctx, callee, set, args, args_linked); + return true; + } + false } @@ -1079,13 +1079,13 @@ fn code_completions(ctx: &mut CompletionContext, hash: bool) { fn is_in_equation_show_rule(leaf: &LinkedNode<'_>) -> bool { let mut node = leaf; while let Some(parent) = node.parent() { - if let Some(expr) = parent.get().cast::() + if let Some(expr) = parent.get().cast::() && let ast::Expr::ShowRule(show) = expr && let Some(ast::Expr::FieldAccess(field)) = show.selector() && field.field().as_str() == "equation" - { - return true; - } + { + return true; + } node = parent; } false @@ -1355,10 +1355,12 @@ impl<'a> CompletionContext<'a> { } } else if at { apply = Some(eco_format!("at(\"{label}\")")); - } else if label.starts_with('"') && self.after.starts_with('"') - && let Some(trimmed) = label.strip_suffix('"') { - apply = Some(trimmed.into()); - } + } else if label.starts_with('"') + && self.after.starts_with('"') + && let Some(trimmed) = label.strip_suffix('"') + { + apply = Some(trimmed.into()); + } self.completions.push(Completion { kind: kind.unwrap_or_else(|| match value { @@ -1543,7 +1545,7 @@ mod tests { use typst::layout::PagedDocument; - use super::{autocomplete, Completion, CompletionKind}; + use super::{Completion, CompletionKind, autocomplete}; use crate::tests::{FilePos, TestWorld, WorldLike}; /// Quote a string. @@ -1561,7 +1563,7 @@ mod tests { fn must_include<'a>(&self, includes: impl IntoIterator) -> &Self; fn must_exclude<'a>(&self, excludes: impl IntoIterator) -> &Self; fn must_apply<'a>(&self, label: &str, apply: impl Into>) - -> &Self; + -> &Self; } impl ResponseExt for Response { diff --git a/crates/typst-ide/src/definition.rs b/crates/typst-ide/src/definition.rs index 4c2b80cd4..4986f2cbe 100644 --- a/crates/typst-ide/src/definition.rs +++ b/crates/typst-ide/src/definition.rs @@ -1,12 +1,12 @@ use typst::foundations::{Label, Selector, Value}; use typst::layout::PagedDocument; -use typst::syntax::{ast, LinkedNode, Side, Source, Span}; +use typst::syntax::{LinkedNode, Side, Source, Span, ast}; use typst::utils::PicoStr; use crate::utils::globals; use crate::{ - analyze_expr, analyze_import, deref_target, named_items, DerefTarget, IdeWorld, - NamedItem, + DerefTarget, IdeWorld, NamedItem, analyze_expr, analyze_import, deref_target, + named_items, }; /// A definition of some item. @@ -90,11 +90,11 @@ mod tests { use std::borrow::Borrow; use std::ops::Range; + use typst::WorldExt; use typst::foundations::{IntoValue, NativeElement}; use typst::syntax::Side; - use typst::WorldExt; - use super::{definition, Definition}; + use super::{Definition, definition}; use crate::tests::{FilePos, TestWorld, WorldLike}; type Response = (TestWorld, Option); diff --git a/crates/typst-ide/src/jump.rs b/crates/typst-ide/src/jump.rs index f0035163b..df252843d 100644 --- a/crates/typst-ide/src/jump.rs +++ b/crates/typst-ide/src/jump.rs @@ -1,10 +1,10 @@ use std::num::NonZeroUsize; +use typst::WorldExt; use typst::layout::{Frame, FrameItem, PagedDocument, Point, Position, Size}; use typst::model::{Destination, Url}; use typst::syntax::{FileId, LinkedNode, Side, Source, Span, SyntaxKind}; use typst::visualize::{Curve, CurveItem, FillRule, Geometry}; -use typst::WorldExt; use crate::IdeWorld; @@ -37,15 +37,16 @@ pub fn jump_from_click( // Try to find a link first. for (pos, item) in frame.items() { if let FrameItem::Link(dest, size) = item - && is_in_rect(*pos, *size, click) { - return Some(match dest { - Destination::Url(url) => Jump::Url(url.clone()), - Destination::Position(pos) => Jump::Position(*pos), - Destination::Location(loc) => { - Jump::Position(document.introspector.position(*loc)) - } - }); - } + && is_in_rect(*pos, *size, click) + { + return Some(match dest { + Destination::Url(url) => Jump::Url(url.clone()), + Destination::Position(pos) => Jump::Position(*pos), + Destination::Location(loc) => { + Jump::Position(document.introspector.position(*loc)) + } + }); + } } // If there's no link, search for a jump target. @@ -54,9 +55,10 @@ pub fn jump_from_click( FrameItem::Group(group) => { let pos = click - pos; if let Some(clip) = &group.clip - && !clip.contains(FillRule::NonZero, pos) { - continue; - } + && !clip.contains(FillRule::NonZero, pos) + { + continue; + } // Realistic transforms should always be invertible. // An example of one that isn't is a scale of 0, which would // not be clickable anyway. @@ -177,9 +179,10 @@ pub fn jump_from_cursor( fn find_in_frame(frame: &Frame, span: Span) -> Option { for &(mut pos, ref item) in frame.items() { if let FrameItem::Group(group) = item - && let Some(point) = find_in_frame(&group.frame, span) { - return Some(pos + point.transform(group.transform)); - } + && let Some(point) = find_in_frame(&group.frame, span) + { + return Some(pos + point.transform(group.transform)); + } if let FrameItem::Text(text) = item { for glyph in &text.glyphs { @@ -219,7 +222,7 @@ mod tests { use typst::layout::{Abs, Point, Position}; - use super::{jump_from_click, jump_from_cursor, Jump}; + use super::{Jump, jump_from_click, jump_from_cursor}; use crate::tests::{FilePos, TestWorld, WorldLike}; fn point(x: f64, y: f64) -> Point { diff --git a/crates/typst-ide/src/lib.rs b/crates/typst-ide/src/lib.rs index c0edcce9f..9444718b4 100644 --- a/crates/typst-ide/src/lib.rs +++ b/crates/typst-ide/src/lib.rs @@ -9,16 +9,16 @@ mod tooltip; mod utils; pub use self::analyze::{analyze_expr, analyze_import, analyze_labels}; -pub use self::complete::{autocomplete, Completion, CompletionKind}; -pub use self::definition::{definition, Definition}; -pub use self::jump::{jump_from_click, jump_from_cursor, Jump}; -pub use self::matchers::{deref_target, named_items, DerefTarget, NamedItem}; -pub use self::tooltip::{tooltip, Tooltip}; +pub use self::complete::{Completion, CompletionKind, autocomplete}; +pub use self::definition::{Definition, definition}; +pub use self::jump::{Jump, jump_from_click, jump_from_cursor}; +pub use self::matchers::{DerefTarget, NamedItem, deref_target, named_items}; +pub use self::tooltip::{Tooltip, tooltip}; use ecow::EcoString; -use typst::syntax::package::PackageSpec; -use typst::syntax::FileId; use typst::World; +use typst::syntax::FileId; +use typst::syntax::package::PackageSpec; /// Extends the `World` for IDE functionality. pub trait IdeWorld: World { diff --git a/crates/typst-ide/src/matchers.rs b/crates/typst-ide/src/matchers.rs index 709d1d156..f460af8ca 100644 --- a/crates/typst-ide/src/matchers.rs +++ b/crates/typst-ide/src/matchers.rs @@ -1,9 +1,9 @@ use ecow::EcoString; use typst::foundations::{Module, Value}; use typst::syntax::ast::AstNode; -use typst::syntax::{ast, LinkedNode, Span, SyntaxKind}; +use typst::syntax::{LinkedNode, Span, SyntaxKind, ast}; -use crate::{analyze_import, IdeWorld}; +use crate::{IdeWorld, analyze_import}; /// Find the named items starting from the given position. pub fn named_items( @@ -60,9 +60,10 @@ pub fn named_items( // Seeing the module itself. if let Some((name, span)) = name_and_span - && let Some(res) = recv(NamedItem::Module(&name, span, module)) { - return Some(res); - } + && let Some(res) = recv(NamedItem::Module(&name, span, module)) + { + return Some(res); + } // Seeing the imported items. match imports { @@ -124,14 +125,15 @@ pub fn named_items( if let Some(parent) = node.parent() { if let Some(v) = parent.cast::() - && node.prev_sibling_kind() != Some(SyntaxKind::In) { - let pattern = v.pattern(); - for ident in pattern.bindings() { - if let Some(res) = recv(NamedItem::Var(ident)) { - return Some(res); - } + && node.prev_sibling_kind() != Some(SyntaxKind::In) + { + let pattern = v.pattern(); + for ident in pattern.bindings() { + if let Some(res) = recv(NamedItem::Var(ident)) { + return Some(res); } } + } if let Some(v) = parent.cast::().filter(|v| { // Check if the node is in the body of the closure. @@ -154,9 +156,10 @@ pub fn named_items( } ast::Param::Spread(s) => { if let Some(sink_ident) = s.sink_ident() - && let Some(t) = recv(NamedItem::Var(sink_ident)) { - return Some(t); - } + && let Some(t) = recv(NamedItem::Var(sink_ident)) + { + return Some(t); + } } } } diff --git a/crates/typst-ide/src/tests.rs b/crates/typst-ide/src/tests.rs index 168dfc9f2..08fef6811 100644 --- a/crates/typst-ide/src/tests.rs +++ b/crates/typst-ide/src/tests.rs @@ -9,7 +9,7 @@ use typst::layout::{Abs, Margin, PageElem}; use typst::syntax::package::{PackageSpec, PackageVersion}; use typst::syntax::{FileId, Source, VirtualPath}; use typst::text::{Font, FontBook, TextElem, TextSize}; -use typst::utils::{singleton, LazyHash}; +use typst::utils::{LazyHash, singleton}; use typst::{Feature, Library, LibraryExt, World}; use crate::IdeWorld; diff --git a/crates/typst-ide/src/tooltip.rs b/crates/typst-ide/src/tooltip.rs index 078465206..7c79eb170 100644 --- a/crates/typst-ide/src/tooltip.rs +++ b/crates/typst-ide/src/tooltip.rs @@ -1,16 +1,16 @@ use std::fmt::Write; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst::engine::Sink; -use typst::foundations::{repr, Binding, Capturer, CastInfo, Repr, Value}; +use typst::foundations::{Binding, Capturer, CastInfo, Repr, Value, repr}; use typst::layout::{Length, PagedDocument}; use typst::syntax::ast::AstNode; -use typst::syntax::{ast, LinkedNode, Side, Source, SyntaxKind}; -use typst::utils::{round_with_precision, Numeric}; +use typst::syntax::{LinkedNode, Side, Source, SyntaxKind, ast}; +use typst::utils::{Numeric, round_with_precision}; use typst_eval::CapturesVisitor; use crate::utils::{plain_docs_sentence, summarize_font_family}; -use crate::{analyze_expr, analyze_import, analyze_labels, IdeWorld}; +use crate::{IdeWorld, analyze_expr, analyze_import, analyze_labels}; /// Describe the item under the cursor. /// @@ -66,9 +66,10 @@ fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { } if let &Value::Length(length) = value - && let Some(tooltip) = length_tooltip(length) { - return Some(tooltip); - } + && let Some(tooltip) = length_tooltip(length) + { + return Some(tooltip); + } } if expr.is_literal() { @@ -92,9 +93,10 @@ fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { } if let Some((_, count)) = last - && count > 1 { - write!(pieces.last_mut().unwrap(), " (×{count})").unwrap(); - } + && count > 1 + { + write!(pieces.last_mut().unwrap(), " (×{count})").unwrap(); + } if iter.next().is_some() { pieces.push("...".into()); @@ -106,18 +108,18 @@ fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { /// Tooltips for imports. fn import_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { - if leaf.kind() == SyntaxKind::Star + if leaf.kind() == SyntaxKind::Star && let Some(parent) = leaf.parent() && let Some(import) = parent.cast::() && let Some(node) = parent.find(import.source().span()) && let Some(value) = analyze_import(world, &node) && let Some(scope) = value.scope() - { - let names: Vec<_> = - scope.iter().map(|(name, ..)| eco_format!("`{name}`")).collect(); - let list = repr::separated_list(&names, "and"); - return Some(Tooltip::Text(eco_format!("This star imports {list}"))); - } + { + let names: Vec<_> = + scope.iter().map(|(name, ..)| eco_format!("`{name}`")).collect(); + let list = repr::separated_list(&names, "and"); + return Some(Tooltip::Text(eco_format!("This star imports {list}"))); + } None } @@ -211,20 +213,20 @@ fn named_param_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option() && let Some(param) = func.param(&ident) - { - return Some(Tooltip::Text(plain_docs_sentence(param.docs))); - } + { + return Some(Tooltip::Text(plain_docs_sentence(param.docs))); + } // Hovering over a string parameter value. - if let Some(string) = leaf.cast::() + if let Some(string) = leaf.cast::() && let Some(param) = func.param(&named.name()) && let Some(docs) = find_string_doc(¶m.input, &string.get()) - { - return Some(Tooltip::Text(docs.into())); - } + { + return Some(Tooltip::Text(docs.into())); + } None } @@ -242,8 +244,8 @@ fn find_string_doc(info: &CastInfo, string: &str) -> Option<&'static str> { /// Tooltip for font. fn font_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { - // Ensure that we are on top of a string. - if let Some(string) = leaf.cast::() + // Ensure that we are on top of a string. + if let Some(string) = leaf.cast::() && let lower = string.get().to_lowercase() // Ensure that we are in the arguments to the text function. @@ -256,11 +258,10 @@ fn font_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { .book() .families() .find(|&(family, _)| family.to_lowercase().as_str() == lower.as_str()) - - { - let detail = summarize_font_family(iter.collect()); - return Some(Tooltip::Text(detail)); - } + { + let detail = summarize_font_family(iter.collect()); + return Some(Tooltip::Text(detail)); + } None } @@ -271,7 +272,7 @@ mod tests { use typst::syntax::Side; - use super::{tooltip, Tooltip}; + use super::{Tooltip, tooltip}; use crate::tests::{FilePos, TestWorld, WorldLike}; type Response = Option; diff --git a/crates/typst-ide/src/utils.rs b/crates/typst-ide/src/utils.rs index 13de402ba..95b16808c 100644 --- a/crates/typst-ide/src/utils.rs +++ b/crates/typst-ide/src/utils.rs @@ -2,7 +2,7 @@ use std::fmt::Write; use std::ops::ControlFlow; use comemo::Track; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst::engine::{Engine, Route, Sink, Traced}; use typst::foundations::{Scope, Value}; use typst::introspection::Introspector; @@ -119,11 +119,7 @@ pub fn globals<'a>(world: &'a dyn IdeWorld, leaf: &LinkedNode) -> &'a Scope { .is_none_or(|prev| !matches!(prev.kind(), SyntaxKind::Hash)); let library = world.library(); - if in_math { - library.math.scope() - } else { - library.global.scope() - } + if in_math { library.math.scope() } else { library.global.scope() } } /// Checks whether the given value or any of its constituent parts satisfy the diff --git a/crates/typst-kit/src/package.rs b/crates/typst-kit/src/package.rs index e62e843cd..06e9f04d6 100644 --- a/crates/typst-kit/src/package.rs +++ b/crates/typst-kit/src/package.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use ecow::eco_format; use once_cell::sync::OnceCell; use serde::Deserialize; -use typst_library::diag::{bail, PackageError, PackageResult, StrResult}; +use typst_library::diag::{PackageError, PackageResult, StrResult, bail}; use typst_syntax::package::{PackageSpec, PackageVersion, VersionlessPackageSpec}; use crate::download::{Downloader, Progress}; @@ -189,7 +189,7 @@ impl PackageStorage { } } Err(err) => { - return Err(PackageError::NetworkFailed(Some(eco_format!("{err}")))) + return Err(PackageError::NetworkFailed(Some(eco_format!("{err}")))); } }; diff --git a/crates/typst-layout/src/flow/block.rs b/crates/typst-layout/src/flow/block.rs index 11096dc7a..395d4335e 100644 --- a/crates/typst-layout/src/flow/block.rs +++ b/crates/typst-layout/src/flow/block.rs @@ -408,9 +408,10 @@ fn distribute<'a>( // last region (it will overflow, but there's nothing else // we can do). if !remaining.approx_empty() - && let Some(last) = buf.last_mut() { - *last += remaining; - } + && let Some(last) = buf.last_mut() + { + *last += remaining; + } // Distribute the heights to the first region and the // backlog. There is no last region, since the height is diff --git a/crates/typst-layout/src/flow/collect.rs b/crates/typst-layout/src/flow/collect.rs index 561b578bb..36c45af51 100644 --- a/crates/typst-layout/src/flow/collect.rs +++ b/crates/typst-layout/src/flow/collect.rs @@ -2,10 +2,11 @@ use std::cell::{LazyCell, RefCell}; use std::fmt::{self, Debug, Formatter}; use std::hash::Hash; -use bumpalo::boxed::Box as BumpBox; use bumpalo::Bump; +use bumpalo::boxed::Box as BumpBox; use comemo::{Track, Tracked, TrackedMut}; -use typst_library::diag::{bail, warning, SourceResult}; +use typst_library::World; +use typst_library::diag::{SourceResult, bail, warning}; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{Packed, Resolve, Smart, StyleChain}; use typst_library::introspection::{ @@ -19,10 +20,9 @@ use typst_library::layout::{ use typst_library::model::ParElem; use typst_library::routines::{Pair, Routines}; use typst_library::text::TextElem; -use typst_library::World; use typst_utils::SliceExt; -use super::{layout_multi_block, layout_single_block, FlowMode}; +use super::{FlowMode, layout_multi_block, layout_single_block}; use crate::inline::ParSituation; use crate::modifiers::layout_and_modify; @@ -685,9 +685,10 @@ impl CachedCell { let mut slot = self.0.borrow_mut(); if let Some((hash, output)) = &*slot - && *hash == input_hash { - return output.clone(); - } + && *hash == input_hash + { + return output.clone(); + } let output = f(input); *slot = Some((input_hash, output.clone())); diff --git a/crates/typst-layout/src/flow/compose.rs b/crates/typst-layout/src/flow/compose.rs index ed514a248..4d937193b 100644 --- a/crates/typst-layout/src/flow/compose.rs +++ b/crates/typst-layout/src/flow/compose.rs @@ -18,7 +18,7 @@ use typst_syntax::Span; use typst_utils::{NonZeroExt, Numeric}; use super::{ - distribute, Config, FlowMode, FlowResult, LineNumberConfig, PlacedChild, Stop, Work, + Config, FlowMode, FlowResult, LineNumberConfig, PlacedChild, Stop, Work, distribute, }; /// Composes the contents of a single page/region. A region can have multiple @@ -319,11 +319,7 @@ impl<'a, 'b> Composer<'a, 'b, '_, '_> { let used = base.y - remaining; let half = need / 2.0; let ratio = (used + half) / base.y; - if ratio <= 0.5 { - FixedAlignment::Start - } else { - FixedAlignment::End - } + if ratio <= 0.5 { FixedAlignment::Start } else { FixedAlignment::End } }); // Select the insertion area where we'll put this float. diff --git a/crates/typst-layout/src/flow/mod.rs b/crates/typst-layout/src/flow/mod.rs index cb029dce8..b6ecc92f7 100644 --- a/crates/typst-layout/src/flow/mod.rs +++ b/crates/typst-layout/src/flow/mod.rs @@ -14,7 +14,8 @@ use std::rc::Rc; use bumpalo::Bump; use comemo::{Track, Tracked, TrackedMut}; use ecow::EcoVec; -use typst_library::diag::{bail, At, SourceDiagnostic, SourceResult}; +use typst_library::World; +use typst_library::diag::{At, SourceDiagnostic, SourceResult, bail}; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{Content, Packed, Resolve, StyleChain}; use typst_library::introspection::{ @@ -27,14 +28,13 @@ use typst_library::layout::{ use typst_library::model::{FootnoteElem, FootnoteEntry, LineNumberingScope, ParLine}; use typst_library::routines::{Arenas, FragmentKind, Pair, RealizationKind, Routines}; use typst_library::text::TextElem; -use typst_library::World; use typst_utils::{NonZeroExt, Numeric}; use self::block::{layout_multi_block, layout_single_block}; use self::collect::{ - collect, Child, LineChild, MultiChild, MultiSpill, PlacedChild, SingleChild, + Child, LineChild, MultiChild, MultiSpill, PlacedChild, SingleChild, collect, }; -use self::compose::{compose, Composer}; +use self::compose::{Composer, compose}; use self::distribute::distribute; /// Lays out content into a single region, producing a single frame. diff --git a/crates/typst-layout/src/grid/layouter.rs b/crates/typst-layout/src/grid/layouter.rs index ee613f8f2..2e8cc9e55 100644 --- a/crates/typst-layout/src/grid/layouter.rs +++ b/crates/typst-layout/src/grid/layouter.rs @@ -1,6 +1,6 @@ use std::fmt::Debug; -use typst_library::diag::{bail, SourceResult}; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{Resolve, StyleChain}; use typst_library::layout::grid::resolve::{ @@ -16,8 +16,8 @@ use typst_syntax::Span; use typst_utils::Numeric; use super::{ - generate_line_segments, hline_stroke_at_column, layout_cell, vline_stroke_at_row, - LineSegment, Rowspan, UnbreakableRowGroup, + LineSegment, Rowspan, UnbreakableRowGroup, generate_line_segments, + hline_stroke_at_column, layout_cell, vline_stroke_at_row, }; /// Performs grid layout. @@ -275,35 +275,39 @@ impl<'a> GridLayouter<'a> { self.measure_columns(engine)?; if let Some(footer) = &self.grid.footer - && footer.repeated { - // Ensure rows in the first region will be aware of the - // possible presence of the footer. - self.prepare_footer(footer, engine, 0)?; - self.regions.size.y -= self.current.footer_height; - self.current.initial_after_repeats = self.regions.size.y; - } + && footer.repeated + { + // Ensure rows in the first region will be aware of the + // possible presence of the footer. + self.prepare_footer(footer, engine, 0)?; + self.regions.size.y -= self.current.footer_height; + self.current.initial_after_repeats = self.regions.size.y; + } let mut y = 0; let mut consecutive_header_count = 0; while y < self.grid.rows.len() { if let Some(next_header) = self.upcoming_headers.get(consecutive_header_count) - && next_header.range.contains(&y) { - self.place_new_headers(&mut consecutive_header_count, engine)?; - y = next_header.range.end; + && next_header.range.contains(&y) + { + self.place_new_headers(&mut consecutive_header_count, engine)?; + y = next_header.range.end; - // Skip header rows during normal layout. - continue; - } + // Skip header rows during normal layout. + continue; + } if let Some(footer) = &self.grid.footer - && footer.repeated && y >= footer.start { - if y == footer.start { - self.layout_footer(footer, engine, self.finished.len())?; - self.flush_orphans(); - } - y = footer.end; - continue; + && footer.repeated + && y >= footer.start + { + if y == footer.start { + self.layout_footer(footer, engine, self.finished.len())?; + self.flush_orphans(); } + y = footer.end; + continue; + } self.layout_row(y, engine, 0)?; @@ -1280,12 +1284,12 @@ impl<'a> GridLayouter<'a> { if let Some([first, rest @ ..]) = frames.get(measurement_data.frames_in_previous_regions..) && can_skip - && breakable - && first.is_empty() - && rest.iter().any(|frame| !frame.is_empty()) - { - return Ok(None); - } + && breakable + && first.is_empty() + && rest.iter().any(|frame| !frame.is_empty()) + { + return Ok(None); + } // Skip frames from previous regions if applicable. let mut sizes = frames @@ -1524,16 +1528,17 @@ impl<'a> GridLayouter<'a> { // were placed, so remove those rows and try again in a new region, // unless this is the last region. if let Some(orphan_snapshot) = self.current.lrows_orphan_snapshot.take() - && !last { - self.current.lrows.truncate(orphan_snapshot); - self.current.repeated_header_rows = - self.current.repeated_header_rows.min(orphan_snapshot); + && !last + { + self.current.lrows.truncate(orphan_snapshot); + self.current.repeated_header_rows = + self.current.repeated_header_rows.min(orphan_snapshot); - if orphan_snapshot == 0 { - // Removed all repeated headers. - self.current.last_repeated_header_end = 0; - } + if orphan_snapshot == 0 { + // Removed all repeated headers. + self.current.last_repeated_header_end = 0; } + } if self .current @@ -1564,22 +1569,21 @@ impl<'a> GridLayouter<'a> { && self.current.could_progress_at_top; let mut laid_out_footer_start = None; - if !footer_would_be_widow - && let Some(footer) = &self.grid.footer { - // Don't layout the footer if it would be alone with the header - // in the page (hence the widow check), and don't layout it - // twice (check below). - // - // TODO(subfooters): this check can be replaced by a vector of - // repeating footers in the future, and/or some "pending - // footers" vector for footers we're about to place. - if footer.repeated - && self.current.lrows.iter().all(|row| row.index() < footer.start) - { - laid_out_footer_start = Some(footer.start); - self.layout_footer(footer, engine, self.finished.len())?; - } + if !footer_would_be_widow && let Some(footer) = &self.grid.footer { + // Don't layout the footer if it would be alone with the header + // in the page (hence the widow check), and don't layout it + // twice (check below). + // + // TODO(subfooters): this check can be replaced by a vector of + // repeating footers in the future, and/or some "pending + // footers" vector for footers we're about to place. + if footer.repeated + && self.current.lrows.iter().all(|row| row.index() < footer.start) + { + laid_out_footer_start = Some(footer.start); + self.layout_footer(footer, engine, self.finished.len())?; } + } // Determine the height of existing rows in the region. let mut used = Abs::zero(); diff --git a/crates/typst-layout/src/grid/lines.rs b/crates/typst-layout/src/grid/lines.rs index 0b823c07d..1c93fdb4d 100644 --- a/crates/typst-layout/src/grid/lines.rs +++ b/crates/typst-layout/src/grid/lines.rs @@ -1,8 +1,8 @@ use std::sync::Arc; use typst_library::foundations::{AlternativeFold, Fold}; -use typst_library::layout::grid::resolve::{CellGrid, Line, Repeatable}; use typst_library::layout::Abs; +use typst_library::layout::grid::resolve::{CellGrid, Line, Repeatable}; use typst_library::visualize::Stroke; use super::RowPiece; @@ -292,11 +292,12 @@ pub fn vline_stroke_at_row( // column), and/or one row below (if at a gutter row), in order to // check if it would be merged with a cell before the vline. if let Some(parent) = grid.effective_parent_cell_position(x, y) - && parent.x < x { - // There is a colspan cell going through this vline's position, - // so don't draw it here. - return None; - } + && parent.x < x + { + // There is a colspan cell going through this vline's position, + // so don't draw it here. + return None; + } } let (left_cell_stroke, left_cell_prioritized) = x @@ -416,26 +417,27 @@ pub fn hline_stroke_at_column( // column), and/or one row below (if at a gutter row), in order to // check if it would be merged with a cell before the hline. if let Some(parent) = grid.effective_parent_cell_position(x, y) - && parent.y < y { - // Get the first 'y' spanned by the possible rowspan in this region. - // The 'parent.y' row and any other spanned rows above 'y' could be - // missing from this region, which could have lead the check above - // to be triggered, even though there is no spanned row above the - // hline in the final layout of this region, and thus no overlap - // with the hline, allowing it to be drawn regardless of the - // theoretical presence of a rowspan going across its position. - let local_parent_y = rows - .iter() - .find(|row| row.y >= parent.y) - .map(|row| row.y) - .unwrap_or(y); + && parent.y < y + { + // Get the first 'y' spanned by the possible rowspan in this region. + // The 'parent.y' row and any other spanned rows above 'y' could be + // missing from this region, which could have lead the check above + // to be triggered, even though there is no spanned row above the + // hline in the final layout of this region, and thus no overlap + // with the hline, allowing it to be drawn regardless of the + // theoretical presence of a rowspan going across its position. + let local_parent_y = rows + .iter() + .find(|row| row.y >= parent.y) + .map(|row| row.y) + .unwrap_or(y); - if local_parent_y < y { - // There is a rowspan cell going through this hline's - // position, so don't draw it here. - return None; - } + if local_parent_y < y { + // There is a rowspan cell going through this hline's + // position, so don't draw it here. + return None; } + } } // When the hline is at the top of the region and this isn't the first diff --git a/crates/typst-layout/src/grid/mod.rs b/crates/typst-layout/src/grid/mod.rs index 1b4380f0a..2f78e090d 100644 --- a/crates/typst-layout/src/grid/mod.rs +++ b/crates/typst-layout/src/grid/mod.rs @@ -9,13 +9,13 @@ use typst_library::diag::SourceResult; use typst_library::engine::Engine; use typst_library::foundations::{Packed, StyleChain}; use typst_library::introspection::Locator; -use typst_library::layout::grid::resolve::{grid_to_cellgrid, table_to_cellgrid, Cell}; +use typst_library::layout::grid::resolve::{Cell, grid_to_cellgrid, table_to_cellgrid}; use typst_library::layout::{Fragment, GridElem, Regions}; use typst_library::model::TableElem; use self::layouter::RowPiece; use self::lines::{ - generate_line_segments, hline_stroke_at_column, vline_stroke_at_row, LineSegment, + LineSegment, generate_line_segments, hline_stroke_at_column, vline_stroke_at_row, }; use self::rowspans::{Rowspan, UnbreakableRowGroup}; diff --git a/crates/typst-layout/src/grid/repeated.rs b/crates/typst-layout/src/grid/repeated.rs index 573ef1a47..62f82f56f 100644 --- a/crates/typst-layout/src/grid/repeated.rs +++ b/crates/typst-layout/src/grid/repeated.rs @@ -241,15 +241,17 @@ impl<'a> GridLayouter<'a> { } if let Some(footer) = &self.grid.footer - && footer.repeated && skipped_region { - // Simulate the footer again; the region's 'full' might have - // changed. - self.regions.size.y += self.current.footer_height; - self.current.footer_height = self - .simulate_footer(footer, &self.regions, engine, disambiguator)? - .height; - self.regions.size.y -= self.current.footer_height; - } + && footer.repeated + && skipped_region + { + // Simulate the footer again; the region's 'full' might have + // changed. + self.regions.size.y += self.current.footer_height; + self.current.footer_height = self + .simulate_footer(footer, &self.regions, engine, disambiguator)? + .height; + self.regions.size.y -= self.current.footer_height; + } let repeating_header_rows = total_header_row_count(self.repeating_headers.iter().copied()); diff --git a/crates/typst-layout/src/grid/rowspans.rs b/crates/typst-layout/src/grid/rowspans.rs index c31bfcb28..66da9bd85 100644 --- a/crates/typst-layout/src/grid/rowspans.rs +++ b/crates/typst-layout/src/grid/rowspans.rs @@ -4,8 +4,8 @@ use typst_library::foundations::Resolve; use typst_library::layout::grid::resolve::Repeatable; use typst_library::layout::{Abs, Axes, Frame, Point, Region, Regions, Size, Sizing}; -use super::layouter::{points, Row}; -use super::{layout_cell, Cell, GridLayouter}; +use super::layouter::{Row, points}; +use super::{Cell, GridLayouter, layout_cell}; /// All information needed to layout a single rowspan. pub struct Rowspan { @@ -239,14 +239,16 @@ impl GridLayouter<'_> { // unbreakable cells (with or without a rowspan setting). let mut amount_unbreakable_rows = None; if let Some(footer) = &self.grid.footer - && !footer.repeated && current_row >= footer.start { - // Non-repeated footer, so keep it unbreakable. - // - // TODO(subfooters): This will become unnecessary - // once non-repeated footers are treated differently and - // have widow prevention. - amount_unbreakable_rows = Some(self.grid.rows.len() - footer.start); - } + && !footer.repeated + && current_row >= footer.start + { + // Non-repeated footer, so keep it unbreakable. + // + // TODO(subfooters): This will become unnecessary + // once non-repeated footers are treated differently and + // have widow prevention. + amount_unbreakable_rows = Some(self.grid.rows.len() - footer.start); + } let row_group = self.simulate_unbreakable_row_group( current_row, @@ -1268,7 +1270,8 @@ fn subtract_end_sizes(sizes: &mut Vec, mut subtract: Abs) { subtract -= sizes.pop().unwrap(); } if subtract > Abs::zero() - && let Some(last_size) = sizes.last_mut() { - *last_size -= subtract; - } + && let Some(last_size) = sizes.last_mut() + { + *last_size -= subtract; + } } diff --git a/crates/typst-layout/src/inline/collect.rs b/crates/typst-layout/src/inline/collect.rs index 1856cb13d..6b6b24579 100644 --- a/crates/typst-layout/src/inline/collect.rs +++ b/crates/typst-layout/src/inline/collect.rs @@ -6,14 +6,14 @@ use typst_library::layout::{ }; use typst_library::routines::Pair; use typst_library::text::{ - is_default_ignorable, LinebreakElem, SmartQuoteElem, SmartQuoter, SmartQuotes, - SpaceElem, TextElem, + LinebreakElem, SmartQuoteElem, SmartQuoter, SmartQuotes, SpaceElem, TextElem, + is_default_ignorable, }; use typst_syntax::Span; use typst_utils::Numeric; use super::*; -use crate::modifiers::{layout_and_modify, FrameModifiers, FrameModify}; +use crate::modifiers::{FrameModifiers, FrameModify, layout_and_modify}; // The characters by which spacing, inline content and pins are replaced in the // full text. @@ -275,10 +275,11 @@ impl<'a> Collector<'a> { // Merge adjacent text segments with the same styles. if let Some(Segment::Text(last_len, last_styles)) = self.segments.last_mut() - && *last_styles == styles { - *last_len += segment_len; - return; - } + && *last_styles == styles + { + *last_len += segment_len; + return; + } self.segments.push(Segment::Text(segment_len, styles)); } diff --git a/crates/typst-layout/src/inline/line.rs b/crates/typst-layout/src/inline/line.rs index 2d921b394..311dc7c69 100644 --- a/crates/typst-layout/src/inline/line.rs +++ b/crates/typst-layout/src/inline/line.rs @@ -6,7 +6,7 @@ use typst_library::foundations::Resolve; use typst_library::introspection::{SplitLocator, Tag}; use typst_library::layout::{Abs, Dir, Em, Fr, Frame, FrameItem, Point}; use typst_library::model::ParLineMarker; -use typst_library::text::{variant, Lang, TextElem}; +use typst_library::text::{Lang, TextElem, variant}; use typst_utils::Numeric; use super::*; @@ -156,15 +156,17 @@ pub fn line<'a>( // Add a hyphen at the line start, if a previous dash should be repeated. if pred.is_some_and(|pred| should_repeat_hyphen(pred, full)) - && let Some(shaped) = items.first_text_mut() { - shaped.prepend_hyphen(engine, p.config.fallback); - } + && let Some(shaped) = items.first_text_mut() + { + shaped.prepend_hyphen(engine, p.config.fallback); + } // Add a hyphen at the line end, if we ended on a soft hyphen. if dash == Some(Dash::Soft) - && let Some(shaped) = items.last_text_mut() { - shaped.push_hyphen(engine, p.config.fallback); - } + && let Some(shaped) = items.last_text_mut() + { + shaped.push_hyphen(engine, p.config.fallback); + } // Deal with CJ characters at line boundaries. adjust_cj_at_line_boundaries(p, full, &mut items); @@ -217,9 +219,10 @@ fn collect_items<'a>( // Add fallback text to expand the line height, if necessary. if !items.iter().any(|item| matches!(item, Item::Text(_))) - && let Some(fallback) = fallback { - items.push(fallback, usize::MAX); - } + && let Some(fallback) = fallback + { + items.push(fallback, usize::MAX); + } items } @@ -460,25 +463,25 @@ pub fn commit( // Handle hanging punctuation to the left. if let Some(Item::Text(text)) = line.items.first() && let Some(glyph) = text.glyphs.first() - && !text.dir.is_positive() - && text.styles.get(TextElem::overhang) - && (line.items.len() > 1 || text.glyphs.len() > 1) - { - let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); - offset -= amount; - remaining += amount; - } + && !text.dir.is_positive() + && text.styles.get(TextElem::overhang) + && (line.items.len() > 1 || text.glyphs.len() > 1) + { + let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); + offset -= amount; + remaining += amount; + } // Handle hanging punctuation to the right. if let Some(Item::Text(text)) = line.items.last() && let Some(glyph) = text.glyphs.last() - && text.dir.is_positive() - && text.styles.get(TextElem::overhang) - && (line.items.len() > 1 || text.glyphs.len() > 1) - { - let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); - remaining += amount; - } + && text.dir.is_positive() + && text.styles.get(TextElem::overhang) + && (line.items.len() > 1 || text.glyphs.len() > 1) + { + let amount = overhang(glyph.c) * glyph.x_advance.at(glyph.size); + remaining += amount; + } // Determine how much additional space is needed. The justification_ratio is // for the first step justification, extra_justification is for the last diff --git a/crates/typst-layout/src/inline/linebreak.rs b/crates/typst-layout/src/inline/linebreak.rs index e40027edb..94053cf68 100644 --- a/crates/typst-layout/src/inline/linebreak.rs +++ b/crates/typst-layout/src/inline/linebreak.rs @@ -2,8 +2,8 @@ use std::ops::{Add, Sub}; use std::sync::LazyLock; use az::SaturatingAs; -use icu_properties::maps::{CodePointMapData, CodePointMapDataBorrowed}; use icu_properties::LineBreak; +use icu_properties::maps::{CodePointMapData, CodePointMapDataBorrowed}; use icu_provider::AsDeserializingBufferProvider; use icu_provider_adapters::fork::ForkByKeyProvider; use icu_provider_blob::BlobDataProvider; @@ -11,7 +11,7 @@ use icu_segmenter::LineSegmenter; use typst_library::engine::Engine; use typst_library::layout::{Abs, Em}; use typst_library::model::Linebreaks; -use typst_library::text::{is_default_ignorable, Lang, TextElem}; +use typst_library::text::{Lang, TextElem, is_default_ignorable}; use typst_syntax::link_prefix; use unicode_segmentation::UnicodeSegmentation; @@ -137,11 +137,12 @@ fn linebreak_simple<'a>( // into the stack and rebuild the line from the attempt's end. The // resulting line cannot be broken up further. if !width.fits(attempt.width) - && let Some((last_attempt, last_end)) = last.take() { - lines.push(last_attempt); - start = last_end; - attempt = line(engine, p, start..end, breakpoint, lines.last()); - } + && let Some((last_attempt, last_end)) = last.take() + { + lines.push(last_attempt); + start = last_end; + attempt = line(engine, p, start..end, breakpoint, lines.last()); + } // Finish the current line if there is a mandatory line break (i.e. due // to "\n") or if the line doesn't fit horizontally already since then @@ -893,11 +894,7 @@ impl CostMetrics { /// we allow less because otherwise we get an invalid layout fairly often, /// which makes our bound useless. fn min_ratio(&self, approx: bool) -> f64 { - if approx { - self.min_approx_ratio - } else { - self.min_ratio - } + if approx { self.min_approx_ratio } else { self.min_ratio } } } diff --git a/crates/typst-layout/src/inline/mod.rs b/crates/typst-layout/src/inline/mod.rs index 06223cebf..addda137b 100644 --- a/crates/typst-layout/src/inline/mod.rs +++ b/crates/typst-layout/src/inline/mod.rs @@ -12,6 +12,7 @@ pub use self::box_::layout_box; pub use self::shaping::create_shape_plan; use comemo::{Track, Tracked, TrackedMut}; +use typst_library::World; use typst_library::diag::SourceResult; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{Packed, Smart, StyleChain}; @@ -23,18 +24,17 @@ use typst_library::model::{ }; use typst_library::routines::{Arenas, Pair, RealizationKind, Routines}; use typst_library::text::{Costs, Lang, TextElem}; -use typst_library::World; use typst_utils::{Numeric, SliceExt}; -use self::collect::{collect, Item, Segment, SpanMapper}; +use self::collect::{Item, Segment, SpanMapper, collect}; use self::deco::decorate; use self::finalize::finalize; -use self::line::{apply_shift, commit, line, Line}; -use self::linebreak::{linebreak, Breakpoint}; -use self::prepare::{prepare, Preparation}; +use self::line::{Line, apply_shift, commit, line}; +use self::linebreak::{Breakpoint, linebreak}; +use self::prepare::{Preparation, prepare}; use self::shaping::{ - cjk_punct_style, is_of_cj_script, shape_range, ShapedGlyph, ShapedText, - BEGIN_PUNCT_PAT, END_PUNCT_PAT, + BEGIN_PUNCT_PAT, END_PUNCT_PAT, ShapedGlyph, ShapedText, cjk_punct_style, + is_of_cj_script, shape_range, }; /// Range of a substring of text. @@ -190,11 +190,7 @@ fn configuration( Config { justify, linebreaks: base.linebreaks.unwrap_or_else(|| { - if justify { - Linebreaks::Optimized - } else { - Linebreaks::Simple - } + if justify { Linebreaks::Optimized } else { Linebreaks::Simple } }), first_line_indent: { let FirstLineIndent { amount, all } = base.first_line_indent; diff --git a/crates/typst-layout/src/inline/shaping.rs b/crates/typst-layout/src/inline/shaping.rs index a8f2bcaba..74996b5be 100644 --- a/crates/typst-layout/src/inline/shaping.rs +++ b/crates/typst-layout/src/inline/shaping.rs @@ -4,21 +4,21 @@ use std::sync::Arc; use az::SaturatingAs; use rustybuzz::{BufferFlags, Feature, ShapePlan, UnicodeBuffer}; -use ttf_parser::gsub::SubstitutionSubtable; use ttf_parser::Tag; +use ttf_parser::gsub::SubstitutionSubtable; +use typst_library::World; use typst_library::engine::Engine; use typst_library::foundations::{Smart, StyleChain}; use typst_library::layout::{Abs, Dir, Em, Frame, FrameItem, Point, Size}; use typst_library::text::{ - families, features, is_default_ignorable, language, variant, Font, FontFamily, - FontVariant, Glyph, Lang, Region, ShiftSettings, TextEdgeBounds, TextElem, TextItem, + Font, FontFamily, FontVariant, Glyph, Lang, Region, ShiftSettings, TextEdgeBounds, + TextElem, TextItem, families, features, is_default_ignorable, language, variant, }; -use typst_library::World; use typst_utils::SliceExt; use unicode_bidi::{BidiInfo, Level as BidiLevel}; use unicode_script::{Script, UnicodeScript}; -use super::{decorate, Item, Range, SpanMapper}; +use super::{Item, Range, SpanMapper, decorate}; use crate::modifiers::FrameModifyText; /// The result of shaping text. @@ -539,11 +539,7 @@ impl<'a> ShapedText<'a> { // Find any glyph with the text index. let found = self.glyphs.binary_search_by(|g: &ShapedGlyph| { let ordering = g.range.start.cmp(&text_index); - if ltr { - ordering - } else { - ordering.reverse() - } + if ltr { ordering } else { ordering.reverse() } }); let mut idx = match found { diff --git a/crates/typst-layout/src/lists.rs b/crates/typst-layout/src/lists.rs index adb793fb9..3a3ea8227 100644 --- a/crates/typst-layout/src/lists.rs +++ b/crates/typst-layout/src/lists.rs @@ -24,11 +24,7 @@ pub fn layout_list( let body_indent = elem.body_indent.get(styles); let tight = elem.tight.get(styles); let gutter = elem.spacing.get(styles).unwrap_or_else(|| { - if tight { - styles.get(ParElem::leading) - } else { - styles.get(ParElem::spacing) - } + if tight { styles.get(ParElem::leading) } else { styles.get(ParElem::spacing) } }); let Depth(depth) = styles.get(ListElem::depth); @@ -88,22 +84,15 @@ pub fn layout_enum( let body_indent = elem.body_indent.get(styles); let tight = elem.tight.get(styles); let gutter = elem.spacing.get(styles).unwrap_or_else(|| { - if tight { - styles.get(ParElem::leading) - } else { - styles.get(ParElem::spacing) - } + if tight { styles.get(ParElem::leading) } else { styles.get(ParElem::spacing) } }); let mut cells = vec![]; let mut locator = locator.split(); - let mut number = elem.start.get(styles).unwrap_or_else(|| { - if reversed { - elem.children.len() as u64 - } else { - 1 - } - }); + let mut number = elem + .start + .get(styles) + .unwrap_or_else(|| if reversed { elem.children.len() as u64 } else { 1 }); let mut parents = styles.get_cloned(EnumElem::parents); let full = elem.full.get(styles); diff --git a/crates/typst-layout/src/math/accent.rs b/crates/typst-layout/src/math/accent.rs index e7f051ace..b9ca0f6dd 100644 --- a/crates/typst-layout/src/math/accent.rs +++ b/crates/typst-layout/src/math/accent.rs @@ -4,8 +4,8 @@ use typst_library::layout::{Em, Frame, Point, Size}; use typst_library::math::AccentElem; use super::{ - style_cramped, style_dtls, style_flac, FrameFragment, GlyphFragment, MathContext, - MathFragment, + FrameFragment, GlyphFragment, MathContext, MathFragment, style_cramped, style_dtls, + style_flac, }; /// How much the accent can be shorter than the base. diff --git a/crates/typst-layout/src/math/attach.rs b/crates/typst-layout/src/math/attach.rs index 78b6f5515..954f840f9 100644 --- a/crates/typst-layout/src/math/attach.rs +++ b/crates/typst-layout/src/math/attach.rs @@ -7,8 +7,8 @@ use typst_library::math::{ use typst_utils::OptionExt; use super::{ - stretch_fragment, style_for_subscript, style_for_superscript, FrameFragment, Limits, - MathContext, MathFragment, + FrameFragment, Limits, MathContext, MathFragment, stretch_fragment, + style_for_subscript, style_for_superscript, }; macro_rules! measure { diff --git a/crates/typst-layout/src/math/frac.rs b/crates/typst-layout/src/math/frac.rs index 12a2c6fd1..50fd09851 100644 --- a/crates/typst-layout/src/math/frac.rs +++ b/crates/typst-layout/src/math/frac.rs @@ -7,8 +7,8 @@ use typst_library::visualize::{FixedStroke, Geometry}; use typst_syntax::Span; use super::{ - style_for_denominator, style_for_numerator, FrameFragment, GlyphFragment, - MathContext, DELIM_SHORT_FALL, + DELIM_SHORT_FALL, FrameFragment, GlyphFragment, MathContext, style_for_denominator, + style_for_numerator, }; const FRAC_AROUND: Em = Em::new(0.1); diff --git a/crates/typst-layout/src/math/fragment.rs b/crates/typst-layout/src/math/fragment.rs index 877158100..3497587c0 100644 --- a/crates/typst-layout/src/math/fragment.rs +++ b/crates/typst-layout/src/math/fragment.rs @@ -2,18 +2,18 @@ use std::fmt::{self, Debug, Formatter}; use az::SaturatingAs; use rustybuzz::{BufferFlags, UnicodeBuffer}; -use ttf_parser::math::{GlyphAssembly, GlyphConstruction, GlyphPart}; use ttf_parser::GlyphId; -use typst_library::diag::{bail, warning, SourceResult}; +use ttf_parser::math::{GlyphAssembly, GlyphConstruction, GlyphPart}; +use typst_library::diag::{SourceResult, bail, warning}; use typst_library::foundations::StyleChain; use typst_library::introspection::Tag; use typst_library::layout::{ Abs, Axes, Axis, Corner, Em, Frame, FrameItem, Point, Size, VAlignment, }; use typst_library::math::{EquationElem, MathSize}; -use typst_library::text::{features, language, Font, Glyph, TextElem, TextItem}; +use typst_library::text::{Font, Glyph, TextElem, TextItem, features, language}; use typst_syntax::Span; -use typst_utils::{default_math_class, Get}; +use typst_utils::{Get, default_math_class}; use unicode_math_class::MathClass; use super::MathContext; @@ -681,7 +681,11 @@ fn min_connector_overlap(font: &Font) -> Option { .map(|variants| font.to_em(variants.min_connector_overlap)) } -fn glyph_construction(font: &Font, id: GlyphId, axis: Axis) -> Option> { +fn glyph_construction( + font: &Font, + id: GlyphId, + axis: Axis, +) -> Option> { font.ttf() .tables() .math? @@ -810,7 +814,10 @@ fn assemble( /// Return an iterator over the assembly's parts with extenders repeated the /// specified number of times. -fn parts(assembly: GlyphAssembly<'_>, repeat: usize) -> impl Iterator + '_ { +fn parts( + assembly: GlyphAssembly<'_>, + repeat: usize, +) -> impl Iterator + '_ { assembly.parts.into_iter().flat_map(move |part| { let count = if part.part_flags.extender() { repeat } else { 1 }; std::iter::repeat_n(part, count) diff --git a/crates/typst-layout/src/math/lr.rs b/crates/typst-layout/src/math/lr.rs index 59dac03af..2a5dd79c9 100644 --- a/crates/typst-layout/src/math/lr.rs +++ b/crates/typst-layout/src/math/lr.rs @@ -5,7 +5,7 @@ use typst_library::math::{EquationElem, LrElem, MidElem}; use typst_utils::SliceExt; use unicode_math_class::MathClass; -use super::{stretch_fragment, MathContext, MathFragment, DELIM_SHORT_FALL}; +use super::{DELIM_SHORT_FALL, MathContext, MathFragment, stretch_fragment}; /// Lays out an [`LrElem`]. #[typst_macros::time(name = "math.lr", span = elem.span())] @@ -22,9 +22,10 @@ pub fn layout_lr( // Extract implicit LrElem. if let Some(lr) = body.to_packed::() - && lr.size.get(styles).is_one() { - body = &lr.body; - } + && lr.size.get(styles).is_one() + { + body = &lr.body; + } let mut fragments = ctx.layout_into_fragments(body, styles)?; @@ -55,10 +56,11 @@ pub fn layout_lr( // Handle MathFragment::Glyph fragments that should be scaled up. for fragment in inner_fragments.iter_mut() { if let MathFragment::Glyph(glyph) = fragment - && glyph.mid_stretched == Some(false) { - glyph.mid_stretched = Some(true); - scale(ctx, fragment, relative_to, height); - } + && glyph.mid_stretched == Some(false) + { + glyph.mid_stretched = Some(true); + scale(ctx, fragment, relative_to, height); + } } // Remove weak SpacingFragment immediately after the opening or immediately diff --git a/crates/typst-layout/src/math/mat.rs b/crates/typst-layout/src/math/mat.rs index 4a897a03e..1969dda57 100644 --- a/crates/typst-layout/src/math/mat.rs +++ b/crates/typst-layout/src/math/mat.rs @@ -1,4 +1,4 @@ -use typst_library::diag::{bail, warning, SourceResult}; +use typst_library::diag::{SourceResult, bail, warning}; use typst_library::foundations::{Content, Packed, Resolve, StyleChain}; use typst_library::layout::{ Abs, Axes, Em, FixedAlignment, Frame, FrameItem, Point, Ratio, Rel, Size, @@ -9,8 +9,8 @@ use typst_library::visualize::{FillRule, FixedStroke, Geometry, LineCap, Shape}; use typst_syntax::Span; use super::{ - alignments, style_for_denominator, AlignmentResult, FrameFragment, GlyphFragment, - LeftRightAlternator, MathContext, DELIM_SHORT_FALL, + AlignmentResult, DELIM_SHORT_FALL, FrameFragment, GlyphFragment, LeftRightAlternator, + MathContext, alignments, style_for_denominator, }; const VERTICAL_PADDING: Ratio = Ratio::new(0.1); diff --git a/crates/typst-layout/src/math/mod.rs b/crates/typst-layout/src/math/mod.rs index 5ee3e14a8..c12af43f9 100644 --- a/crates/typst-layout/src/math/mod.rs +++ b/crates/typst-layout/src/math/mod.rs @@ -13,7 +13,8 @@ mod stretch; mod text; mod underover; -use typst_library::diag::{bail, SourceResult}; +use typst_library::World; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{ Content, NativeElement, Packed, Resolve, StyleChain, SymbolElem, @@ -28,15 +29,14 @@ use typst_library::math::*; use typst_library::model::ParElem; use typst_library::routines::{Arenas, RealizationKind}; use typst_library::text::{ - families, variant, Font, LinebreakElem, SpaceElem, TextEdgeBounds, TextElem, + Font, LinebreakElem, SpaceElem, TextEdgeBounds, TextElem, families, variant, }; -use typst_library::World; use typst_syntax::Span; use typst_utils::Numeric; use unicode_math_class::MathClass; use self::fragment::{ - has_dtls_feat, stretch_axes, FrameFragment, GlyphFragment, Limits, MathFragment, + FrameFragment, GlyphFragment, Limits, MathFragment, has_dtls_feat, stretch_axes, }; use self::run::{LeftRightAlternator, MathRun, MathRunFrameBuilder}; use self::shared::*; @@ -604,12 +604,10 @@ fn layout_h( styles: StyleChain, ) -> SourceResult<()> { if let Spacing::Rel(rel) = elem.amount - && rel.rel.is_zero() { - ctx.push(MathFragment::Spacing( - rel.abs.resolve(styles), - elem.weak.get(styles), - )); - } + && rel.rel.is_zero() + { + ctx.push(MathFragment::Spacing(rel.abs.resolve(styles), elem.weak.get(styles))); + } Ok(()) } diff --git a/crates/typst-layout/src/math/root.rs b/crates/typst-layout/src/math/root.rs index 30948e08e..e66619ea9 100644 --- a/crates/typst-layout/src/math/root.rs +++ b/crates/typst-layout/src/math/root.rs @@ -5,7 +5,7 @@ use typst_library::math::{EquationElem, MathSize, RootElem}; use typst_library::text::TextElem; use typst_library::visualize::{FixedStroke, Geometry}; -use super::{style_cramped, FrameFragment, GlyphFragment, MathContext}; +use super::{FrameFragment, GlyphFragment, MathContext, style_cramped}; /// Lays out a [`RootElem`]. /// diff --git a/crates/typst-layout/src/math/run.rs b/crates/typst-layout/src/math/run.rs index fb206dc2e..1ef2608cf 100644 --- a/crates/typst-layout/src/math/run.rs +++ b/crates/typst-layout/src/math/run.rs @@ -2,11 +2,11 @@ use std::iter::once; use typst_library::foundations::{Resolve, StyleChain}; use typst_library::layout::{Abs, AlignElem, Em, Frame, InlineItem, Point, Size}; -use typst_library::math::{EquationElem, MathSize, MEDIUM, THICK, THIN}; +use typst_library::math::{EquationElem, MEDIUM, MathSize, THICK, THIN}; use typst_library::model::ParElem; use unicode_math_class::MathClass; -use super::{alignments, FrameFragment, MathFragment}; +use super::{FrameFragment, MathFragment, alignments}; const TIGHT_LEADING: Em = Em::new(0.25); @@ -88,9 +88,10 @@ impl MathRun { // Insert spacing between the last and this non-ignorant item. if !fragment.is_ignorant() { if let Some(i) = last - && let Some(s) = spacing(&resolved[i], space.take(), &fragment) { - resolved.insert(i + 1, s); - } + && let Some(s) = spacing(&resolved[i], space.take(), &fragment) + { + resolved.insert(i + 1, s); + } last = Some(resolved.len()); } @@ -123,9 +124,10 @@ impl MathRun { // A linebreak at the very end does not introduce an extra row. if let Some(f) = self.0.last() - && matches!(f, MathFragment::Linebreak) { - count -= 1 - } + && matches!(f, MathFragment::Linebreak) + { + count -= 1 + } count } @@ -343,9 +345,10 @@ impl MathRun { space_is_visible = true; if let Some(f_next) = iter.peek() - && !is_space(f_next) { - items.push(InlineItem::Space(Abs::zero(), true)); - } + && !is_space(f_next) + { + items.push(InlineItem::Space(Abs::zero(), true)); + } } else { space_is_visible = false; } diff --git a/crates/typst-layout/src/math/shared.rs b/crates/typst-layout/src/math/shared.rs index c9d20aa68..2763c1622 100644 --- a/crates/typst-layout/src/math/shared.rs +++ b/crates/typst-layout/src/math/shared.rs @@ -1,5 +1,5 @@ -use ttf_parser::math::MathValue; use ttf_parser::Tag; +use ttf_parser::math::MathValue; use typst_library::foundations::{Style, StyleChain}; use typst_library::layout::{Abs, Em, FixedAlignment, Frame, Point, Size}; use typst_library::math::{EquationElem, MathSize}; diff --git a/crates/typst-layout/src/math/stretch.rs b/crates/typst-layout/src/math/stretch.rs index b9a6b15ae..615d1e6bf 100644 --- a/crates/typst-layout/src/math/stretch.rs +++ b/crates/typst-layout/src/math/stretch.rs @@ -1,10 +1,10 @@ -use typst_library::diag::{warning, SourceResult}; +use typst_library::diag::{SourceResult, warning}; use typst_library::foundations::{Packed, StyleChain}; use typst_library::layout::{Abs, Axis, Rel}; use typst_library::math::StretchElem; use typst_utils::Get; -use super::{stretch_axes, MathContext, MathFragment}; +use super::{MathContext, MathFragment, stretch_axes}; /// Lays out a [`StretchElem`]. #[typst_macros::time(name = "math.stretch", span = elem.span())] diff --git a/crates/typst-layout/src/math/text.rs b/crates/typst-layout/src/math/text.rs index 634969cd4..fe9c7203a 100644 --- a/crates/typst-layout/src/math/text.rs +++ b/crates/typst-layout/src/math/text.rs @@ -1,6 +1,6 @@ use std::f64::consts::SQRT_2; -use codex::styling::{to_style, MathStyle}; +use codex::styling::{MathStyle, to_style}; use ecow::EcoString; use typst_library::diag::SourceResult; use typst_library::foundations::{Packed, StyleChain, SymbolElem}; @@ -9,13 +9,13 @@ use typst_library::math::{EquationElem, MathSize}; use typst_library::text::{ BottomEdge, BottomEdgeMetric, TextElem, TopEdge, TopEdgeMetric, }; -use typst_syntax::{is_newline, Span}; +use typst_syntax::{Span, is_newline}; use unicode_math_class::MathClass; use unicode_segmentation::UnicodeSegmentation; use super::{ - has_dtls_feat, style_dtls, FrameFragment, GlyphFragment, MathContext, MathFragment, - MathRun, + FrameFragment, GlyphFragment, MathContext, MathFragment, MathRun, has_dtls_feat, + style_dtls, }; /// Lays out a [`TextElem`]. diff --git a/crates/typst-layout/src/math/underover.rs b/crates/typst-layout/src/math/underover.rs index 1e1aeb41d..e1ca657f8 100644 --- a/crates/typst-layout/src/math/underover.rs +++ b/crates/typst-layout/src/math/underover.rs @@ -10,8 +10,8 @@ use typst_library::visualize::{FixedStroke, Geometry}; use typst_syntax::Span; use super::{ - stack, style_cramped, style_for_subscript, style_for_superscript, FrameFragment, - GlyphFragment, LeftRightAlternator, MathContext, MathRun, + FrameFragment, GlyphFragment, LeftRightAlternator, MathContext, MathRun, stack, + style_cramped, style_for_subscript, style_for_superscript, }; const BRACE_GAP: Em = Em::new(0.25); diff --git a/crates/typst-layout/src/pages/mod.rs b/crates/typst-layout/src/pages/mod.rs index ec0dc2c05..ea86e3f3d 100644 --- a/crates/typst-layout/src/pages/mod.rs +++ b/crates/typst-layout/src/pages/mod.rs @@ -7,6 +7,7 @@ mod run; use std::num::NonZeroUsize; use comemo::{Tracked, TrackedMut}; +use typst_library::World; use typst_library::diag::SourceResult; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{Content, StyleChain}; @@ -16,11 +17,10 @@ use typst_library::introspection::{ use typst_library::layout::{FrameItem, Page, PagedDocument, Point, Transform}; use typst_library::model::DocumentInfo; use typst_library::routines::{Arenas, Pair, RealizationKind, Routines}; -use typst_library::World; -use self::collect::{collect, Item}; +use self::collect::{Item, collect}; use self::finalize::finalize; -use self::run::{layout_blank_page, layout_page_run, LayoutedPage}; +use self::run::{LayoutedPage, layout_blank_page, layout_page_run}; /// Layout content into a document. /// diff --git a/crates/typst-layout/src/pages/run.rs b/crates/typst-layout/src/pages/run.rs index 8c1a34ed5..c327adba2 100644 --- a/crates/typst-layout/src/pages/run.rs +++ b/crates/typst-layout/src/pages/run.rs @@ -1,4 +1,5 @@ use comemo::{Track, Tracked, TrackedMut}; +use typst_library::World; use typst_library::diag::SourceResult; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{ @@ -16,10 +17,9 @@ use typst_library::model::Numbering; use typst_library::routines::{Pair, Routines}; use typst_library::text::{LocalName, TextElem}; use typst_library::visualize::Paint; -use typst_library::World; use typst_utils::Numeric; -use crate::flow::{layout_flow, FlowMode}; +use crate::flow::{FlowMode, layout_flow}; /// A mostly finished layout for one page. Needs only knowledge of its exact /// page number to be finalized into a `Page`. (Because the margins can depend diff --git a/crates/typst-layout/src/repeat.rs b/crates/typst-layout/src/repeat.rs index 40179c349..91c39fed9 100644 --- a/crates/typst-layout/src/repeat.rs +++ b/crates/typst-layout/src/repeat.rs @@ -1,4 +1,4 @@ -use typst_library::diag::{bail, SourceResult}; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{Packed, Resolve, StyleChain}; use typst_library::introspection::Locator; diff --git a/crates/typst-layout/src/rules.rs b/crates/typst-layout/src/rules.rs index f21cd17ab..a3616f96e 100644 --- a/crates/typst-layout/src/rules.rs +++ b/crates/typst-layout/src/rules.rs @@ -1,12 +1,12 @@ use std::num::NonZeroUsize; use comemo::Track; -use ecow::{eco_format, EcoVec}; +use ecow::{EcoVec, eco_format}; use smallvec::smallvec; -use typst_library::diag::{bail, At, SourceResult}; +use typst_library::diag::{At, SourceResult, bail}; use typst_library::foundations::{ - dict, Content, Context, NativeElement, NativeRuleMap, Packed, Resolve, ShowFn, Smart, - StyleChain, Target, + Content, Context, NativeElement, NativeRuleMap, Packed, Resolve, ShowFn, Smart, + StyleChain, Target, dict, }; use typst_library::introspection::{Counter, Locator, LocatorLink}; use typst_library::layout::{ @@ -161,11 +161,7 @@ const TERMS_RULE: ShowFn = |elem, _, styles| { let indent = elem.indent.get(styles); let hanging_indent = elem.hanging_indent.get(styles); let gutter = elem.spacing.get(styles).unwrap_or_else(|| { - if tight { - styles.get(ParElem::leading) - } else { - styles.get(ParElem::spacing) - } + if tight { styles.get(ParElem::leading) } else { styles.get(ParElem::spacing) } }); let pad = hanging_indent + indent; diff --git a/crates/typst-layout/src/shapes.rs b/crates/typst-layout/src/shapes.rs index 1a9b38f25..d0d3a5e1d 100644 --- a/crates/typst-layout/src/shapes.rs +++ b/crates/typst-layout/src/shapes.rs @@ -1,7 +1,7 @@ use std::f64::consts::SQRT_2; use kurbo::{CubicBez, ParamCurveExtrema}; -use typst_library::diag::{bail, SourceResult}; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{Content, Packed, Resolve, Smart, StyleChain}; use typst_library::introspection::Locator; diff --git a/crates/typst-layout/src/stack.rs b/crates/typst-layout/src/stack.rs index 5df626fdf..892b08137 100644 --- a/crates/typst-layout/src/stack.rs +++ b/crates/typst-layout/src/stack.rs @@ -1,4 +1,4 @@ -use typst_library::diag::{bail, SourceResult}; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{Content, Packed, Resolve, StyleChain, StyledElem}; use typst_library::introspection::{Locator, SplitLocator}; diff --git a/crates/typst-layout/src/transforms.rs b/crates/typst-layout/src/transforms.rs index e545dd512..beeeea034 100644 --- a/crates/typst-layout/src/transforms.rs +++ b/crates/typst-layout/src/transforms.rs @@ -1,6 +1,6 @@ use std::cell::LazyCell; -use typst_library::diag::{bail, SourceResult}; +use typst_library::diag::{SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{Content, Packed, Resolve, Smart, StyleChain}; use typst_library::introspection::Locator; diff --git a/crates/typst-library/src/diag.rs b/crates/typst-library/src/diag.rs index 611ec6338..2b9ff6376 100644 --- a/crates/typst-library/src/diag.rs +++ b/crates/typst-library/src/diag.rs @@ -8,7 +8,7 @@ use std::string::FromUtf8Error; use az::SaturatingAs; use comemo::Tracked; -use ecow::{eco_vec, EcoVec}; +use ecow::{EcoVec, eco_vec}; use typst_syntax::package::{PackageSpec, PackageVersion}; use typst_syntax::{Lines, Span, Spanned, SyntaxError}; use utf8_iter::ErrorReportingUtf8Chars; @@ -298,11 +298,11 @@ impl Trace for SourceResult { // Skip traces that surround the error. if let Some(error_range) = world.range(error.span) && error.span.id() == span.id() - && trace_range.start <= error_range.start - && trace_range.end >= error_range.end - { - continue; - } + && trace_range.start <= error_range.start + && trace_range.end >= error_range.end + { + continue; + } error.trace.push(Spanned::new(make_point(), span)); } @@ -838,7 +838,9 @@ pub fn format_xml_like_error(format: &str, error: roxmltree::Error) -> LoadError let pos = LineCol::one_based(error.pos().row as usize, error.pos().col as usize); let message = match error { roxmltree::Error::UnexpectedCloseTag(expected, actual, _) => { - eco_format!("failed to parse {format} (found closing tag '{actual}' instead of '{expected}')") + eco_format!( + "failed to parse {format} (found closing tag '{actual}' instead of '{expected}')" + ) } roxmltree::Error::UnknownEntityReference(entity, _) => { eco_format!("failed to parse {format} (unknown entity '{entity}')") diff --git a/crates/typst-library/src/engine.rs b/crates/typst-library/src/engine.rs index a85fc8ca2..cb98f4599 100644 --- a/crates/typst-library/src/engine.rs +++ b/crates/typst-library/src/engine.rs @@ -8,11 +8,11 @@ use ecow::EcoVec; use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; use typst_syntax::{FileId, Span}; -use crate::diag::{bail, HintedStrResult, SourceDiagnostic, SourceResult, StrResult}; +use crate::World; +use crate::diag::{HintedStrResult, SourceDiagnostic, SourceResult, StrResult, bail}; use crate::foundations::{Styles, Value}; use crate::introspection::Introspector; use crate::routines::Routines; -use crate::World; /// Holds all data needed during compilation. pub struct Engine<'a> { @@ -47,7 +47,11 @@ impl Engine<'_> { } /// Runs tasks on the engine in parallel. - pub fn parallelize(&mut self, iter: P, f: F) -> impl Iterator + use + pub fn parallelize( + &mut self, + iter: P, + f: F, + ) -> impl Iterator + use where P: IntoIterator, I: Iterator, @@ -111,11 +115,7 @@ impl Traced { /// We hide the span if it isn't in the given file so that only results for /// the file with the traced span are invalidated. pub fn get(&self, id: FileId) -> Option { - if self.0.and_then(Span::id) == Some(id) { - self.0 - } else { - None - } + if self.0.and_then(Span::id) == Some(id) { self.0 } else { None } } } diff --git a/crates/typst-library/src/foundations/args.rs b/crates/typst-library/src/foundations/args.rs index 430c4e9ad..343d60456 100644 --- a/crates/typst-library/src/foundations/args.rs +++ b/crates/typst-library/src/foundations/args.rs @@ -1,12 +1,12 @@ use std::fmt::{self, Debug, Formatter}; use std::ops::Add; -use ecow::{eco_format, eco_vec, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format, eco_vec}; use typst_syntax::{Span, Spanned}; -use crate::diag::{bail, error, At, SourceDiagnostic, SourceResult, StrResult}; +use crate::diag::{At, SourceDiagnostic, SourceResult, StrResult, bail, error}; use crate::foundations::{ - cast, func, repr, scope, ty, Array, Dict, FromValue, IntoValue, Repr, Str, Value, + Array, Dict, FromValue, IntoValue, Repr, Str, Value, cast, func, repr, scope, ty, }; /// Captured arguments to a function. diff --git a/crates/typst-library/src/foundations/array.rs b/crates/typst-library/src/foundations/array.rs index 87a301049..5e72ce889 100644 --- a/crates/typst-library/src/foundations/array.rs +++ b/crates/typst-library/src/foundations/array.rs @@ -4,16 +4,16 @@ use std::num::{NonZeroI64, NonZeroUsize}; use std::ops::{Add, AddAssign}; use comemo::Tracked; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; use serde::{Deserialize, Serialize}; use smallvec::SmallVec; use typst_syntax::{Span, Spanned}; -use crate::diag::{bail, At, HintedStrResult, SourceDiagnostic, SourceResult, StrResult}; +use crate::diag::{At, HintedStrResult, SourceDiagnostic, SourceResult, StrResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, func, ops, repr, scope, ty, Args, Bytes, CastInfo, Context, Dict, FromValue, - Func, IntoValue, Reflect, Repr, Str, Value, Version, + Args, Bytes, CastInfo, Context, Dict, FromValue, Func, IntoValue, Reflect, Repr, Str, + Value, Version, cast, func, ops, repr, scope, ty, }; /// Create a new [`Array`] from values. diff --git a/crates/typst-library/src/foundations/auto.rs b/crates/typst-library/src/foundations/auto.rs index 8237b4509..c8ae0706e 100644 --- a/crates/typst-library/src/foundations/auto.rs +++ b/crates/typst-library/src/foundations/auto.rs @@ -4,8 +4,8 @@ use ecow::EcoString; use crate::diag::HintedStrResult; use crate::foundations::{ - ty, CastInfo, Fold, FromValue, IntoValue, Reflect, Repr, Resolve, StyleChain, Type, - Value, + CastInfo, Fold, FromValue, IntoValue, Reflect, Repr, Resolve, StyleChain, Type, + Value, ty, }; /// A value that indicates a smart default. diff --git a/crates/typst-library/src/foundations/bool.rs b/crates/typst-library/src/foundations/bool.rs index e88c8c6ff..32f6845df 100644 --- a/crates/typst-library/src/foundations/bool.rs +++ b/crates/typst-library/src/foundations/bool.rs @@ -1,6 +1,6 @@ use ecow::EcoString; -use crate::foundations::{ty, Repr}; +use crate::foundations::{Repr, ty}; /// A type with two states. /// diff --git a/crates/typst-library/src/foundations/bytes.rs b/crates/typst-library/src/foundations/bytes.rs index 180dcdad5..f4547439d 100644 --- a/crates/typst-library/src/foundations/bytes.rs +++ b/crates/typst-library/src/foundations/bytes.rs @@ -5,13 +5,13 @@ use std::ops::{Add, AddAssign, Deref}; use std::str::Utf8Error; use std::sync::Arc; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use serde::{Serialize, Serializer}; use typst_syntax::Lines; use typst_utils::LazyHash; -use crate::diag::{bail, StrResult}; -use crate::foundations::{cast, func, scope, ty, Array, Reflect, Repr, Str, Value}; +use crate::diag::{StrResult, bail}; +use crate::foundations::{Array, Reflect, Repr, Str, Value, cast, func, scope, ty}; /// A sequence of bytes. /// diff --git a/crates/typst-library/src/foundations/calc.rs b/crates/typst-library/src/foundations/calc.rs index 1fe1ff1fc..8aa6c6bcb 100644 --- a/crates/typst-library/src/foundations/calc.rs +++ b/crates/typst-library/src/foundations/calc.rs @@ -7,8 +7,8 @@ use az::SaturatingAs; use typst_syntax::{Span, Spanned}; use typst_utils::{round_int_with_precision, round_with_precision}; -use crate::diag::{bail, At, HintedString, SourceResult, StrResult}; -use crate::foundations::{cast, func, ops, Decimal, IntoValue, Module, Scope, Value}; +use crate::diag::{At, HintedString, SourceResult, StrResult, bail}; +use crate::foundations::{Decimal, IntoValue, Module, Scope, Value, cast, func, ops}; use crate::layout::{Angle, Fr, Length, Ratio}; /// A module with calculation definitions. diff --git a/crates/typst-library/src/foundations/cast.rs b/crates/typst-library/src/foundations/cast.rs index 17d194e1a..95c29a40a 100644 --- a/crates/typst-library/src/foundations/cast.rs +++ b/crates/typst-library/src/foundations/cast.rs @@ -14,7 +14,7 @@ use unicode_math_class::MathClass; use crate::diag::{At, HintedStrResult, HintedString, SourceResult, StrResult}; use crate::foundations::{ - array, repr, Fold, NativeElement, Packed, Repr, Str, Type, Value, + Fold, NativeElement, Packed, Repr, Str, Type, Value, array, repr, }; /// Determine details of a type. @@ -348,12 +348,14 @@ impl CastInfo { } } } else if let Value::Decimal(_) = found - && !matching_type && parts.iter().any(|p| p == "float") { - msg.hint(eco_format!( - "if loss of precision is acceptable, explicitly cast the \ + && !matching_type + && parts.iter().any(|p| p == "float") + { + msg.hint(eco_format!( + "if loss of precision is acceptable, explicitly cast the \ decimal to a float with `float(value)`" - )); - } + )); + } msg } diff --git a/crates/typst-library/src/foundations/content/element.rs b/crates/typst-library/src/foundations/content/element.rs index 65c2e28b5..6e3c6d889 100644 --- a/crates/typst-library/src/foundations/content/element.rs +++ b/crates/typst-library/src/foundations/content/element.rs @@ -11,8 +11,8 @@ use typst_utils::Static; use crate::diag::SourceResult; use crate::engine::Engine; use crate::foundations::{ - cast, Args, Content, ContentVtable, FieldAccessError, Func, ParamInfo, Repr, Scope, - Selector, StyleChain, Styles, Value, + Args, Content, ContentVtable, FieldAccessError, Func, ParamInfo, Repr, Scope, + Selector, StyleChain, Styles, Value, cast, }; use crate::text::{Lang, Region}; @@ -243,7 +243,7 @@ pub trait Set { pub trait Synthesize { /// Prepare the element for show rule application. fn synthesize(&mut self, engine: &mut Engine, styles: StyleChain) - -> SourceResult<()>; + -> SourceResult<()>; } /// Defines built-in show set rules for an element. diff --git a/crates/typst-library/src/foundations/content/field.rs b/crates/typst-library/src/foundations/content/field.rs index 8d0fe529c..a8e679441 100644 --- a/crates/typst-library/src/foundations/content/field.rs +++ b/crates/typst-library/src/foundations/content/field.rs @@ -3,7 +3,7 @@ use std::hash::Hash; use std::marker::PhantomData; use std::sync::OnceLock; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use crate::foundations::{ Container, Content, FieldVtable, Fold, FoldFn, IntoValue, NativeElement, Packed, diff --git a/crates/typst-library/src/foundations/content/mod.rs b/crates/typst-library/src/foundations/content/mod.rs index f5e8314d8..ca5c7b6d8 100644 --- a/crates/typst-library/src/foundations/content/mod.rs +++ b/crates/typst-library/src/foundations/content/mod.rs @@ -17,7 +17,7 @@ use std::iter::{self, Sum}; use std::ops::{Add, AddAssign, ControlFlow}; use comemo::Tracked; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use serde::{Serialize, Serializer}; use typst_syntax::Span; @@ -26,8 +26,8 @@ use typst_utils::singleton; use crate::diag::{SourceResult, StrResult}; use crate::engine::Engine; use crate::foundations::{ - func, repr, scope, ty, Context, Dict, IntoValue, Label, Property, Recipe, - RecipeIndex, Repr, Selector, Str, Style, StyleChain, Styles, Value, + Context, Dict, IntoValue, Label, Property, Recipe, RecipeIndex, Repr, Selector, Str, + Style, StyleChain, Styles, Value, func, repr, scope, ty, }; use crate::introspection::Location; use crate::layout::{AlignElem, Alignment, Axes, Length, MoveElem, PadElem, Rel, Sides}; @@ -175,9 +175,10 @@ impl Content { styles: Option, ) -> Result { if id == 255 - && let Some(label) = self.label() { - return Ok(label.into_value()); - } + && let Some(label) = self.label() + { + return Ok(label.into_value()); + } match self.0.handle().field(id) { Some(handle) => match styles { diff --git a/crates/typst-library/src/foundations/content/raw.rs b/crates/typst-library/src/foundations/content/raw.rs index dde26bd79..713700502 100644 --- a/crates/typst-library/src/foundations/content/raw.rs +++ b/crates/typst-library/src/foundations/content/raw.rs @@ -5,7 +5,7 @@ use std::ptr::NonNull; use std::sync::atomic::{self, AtomicUsize, Ordering}; use typst_syntax::Span; -use typst_utils::{fat, HashLock, SmallBitSet}; +use typst_utils::{HashLock, SmallBitSet, fat}; use super::vtable; use crate::foundations::{Element, Label, NativeElement, Packed}; diff --git a/crates/typst-library/src/foundations/context.rs b/crates/typst-library/src/foundations/context.rs index 56d87775e..d9b8a48f6 100644 --- a/crates/typst-library/src/foundations/context.rs +++ b/crates/typst-library/src/foundations/context.rs @@ -1,9 +1,9 @@ use comemo::Track; -use crate::diag::{bail, Hint, HintedStrResult, SourceResult}; +use crate::diag::{Hint, HintedStrResult, SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - elem, Args, Construct, Content, Func, ShowFn, StyleChain, Value, + Args, Construct, Content, Func, ShowFn, StyleChain, Value, elem, }; use crate::introspection::{Locatable, Location}; diff --git a/crates/typst-library/src/foundations/datetime.rs b/crates/typst-library/src/foundations/datetime.rs index 2fc48a521..ffc6aaafa 100644 --- a/crates/typst-library/src/foundations/datetime.rs +++ b/crates/typst-library/src/foundations/datetime.rs @@ -2,17 +2,17 @@ use std::cmp::Ordering; use std::hash::Hash; use std::ops::{Add, Sub}; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; use time::error::{Format, InvalidFormatDescription}; use time::macros::format_description; -use time::{format_description, Month, PrimitiveDateTime}; +use time::{Month, PrimitiveDateTime, format_description}; -use crate::diag::{bail, StrResult}; +use crate::World; +use crate::diag::{StrResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, func, repr, scope, ty, Dict, Duration, Repr, Smart, Str, Value, + Dict, Duration, Repr, Smart, Str, Value, cast, func, repr, scope, ty, }; -use crate::World; /// Represents a date, a time, or a combination of both. /// diff --git a/crates/typst-library/src/foundations/decimal.rs b/crates/typst-library/src/foundations/decimal.rs index d363a6a41..998de8e95 100644 --- a/crates/typst-library/src/foundations/decimal.rs +++ b/crates/typst-library/src/foundations/decimal.rs @@ -3,14 +3,14 @@ use std::hash::{Hash, Hasher}; use std::ops::Neg; use std::str::FromStr; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use rust_decimal::MathematicalOps; -use typst_syntax::{ast, Span, Spanned}; +use typst_syntax::{Span, Spanned, ast}; -use crate::diag::{warning, At, SourceResult}; -use crate::engine::Engine; -use crate::foundations::{cast, func, repr, scope, ty, Repr, Str}; use crate::World; +use crate::diag::{At, SourceResult, warning}; +use crate::engine::Engine; +use crate::foundations::{Repr, Str, cast, func, repr, scope, ty}; /// A fixed-point decimal number type. /// diff --git a/crates/typst-library/src/foundations/dict.rs b/crates/typst-library/src/foundations/dict.rs index ba161f44c..d5dfc7aa4 100644 --- a/crates/typst-library/src/foundations/dict.rs +++ b/crates/typst-library/src/foundations/dict.rs @@ -3,7 +3,7 @@ use std::hash::{Hash, Hasher}; use std::ops::{Add, AddAssign}; use std::sync::Arc; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use indexmap::IndexMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use typst_syntax::is_ident; @@ -11,7 +11,7 @@ use typst_utils::ArcExt; use crate::diag::{Hint, HintedStrResult, StrResult}; use crate::foundations::{ - array, cast, func, repr, scope, ty, Array, Module, Repr, Str, Value, + Array, Module, Repr, Str, Value, array, cast, func, repr, scope, ty, }; /// Create a new [`Dict`] from key-value pairs. diff --git a/crates/typst-library/src/foundations/duration.rs b/crates/typst-library/src/foundations/duration.rs index 90685fa34..2dcef0d85 100644 --- a/crates/typst-library/src/foundations/duration.rs +++ b/crates/typst-library/src/foundations/duration.rs @@ -1,10 +1,10 @@ use std::fmt::{self, Debug, Formatter}; use std::ops::{Add, Div, Mul, Neg, Sub}; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use time::ext::NumericalDuration; -use crate::foundations::{func, repr, scope, ty, Repr}; +use crate::foundations::{Repr, func, repr, scope, ty}; /// Represents a positive or negative span of time. #[ty(scope, cast)] diff --git a/crates/typst-library/src/foundations/fields.rs b/crates/typst-library/src/foundations/fields.rs index 422f30b88..83b5d073e 100644 --- a/crates/typst-library/src/foundations/fields.rs +++ b/crates/typst-library/src/foundations/fields.rs @@ -1,6 +1,6 @@ //! Fields on values. -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use crate::diag::StrResult; use crate::foundations::{IntoValue, Type, Value, Version}; diff --git a/crates/typst-library/src/foundations/float.rs b/crates/typst-library/src/foundations/float.rs index 353e498d3..b9d5b97cc 100644 --- a/crates/typst-library/src/foundations/float.rs +++ b/crates/typst-library/src/foundations/float.rs @@ -1,10 +1,10 @@ use std::num::ParseFloatError; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; -use crate::diag::{bail, StrResult}; +use crate::diag::{StrResult, bail}; use crate::foundations::{ - cast, func, repr, scope, ty, Bytes, Decimal, Endianness, Repr, Str, + Bytes, Decimal, Endianness, Repr, Str, cast, func, repr, scope, ty, }; use crate::layout::Ratio; diff --git a/crates/typst-library/src/foundations/func.rs b/crates/typst-library/src/foundations/func.rs index dd999ddc3..5b43ad37c 100644 --- a/crates/typst-library/src/foundations/func.rs +++ b/crates/typst-library/src/foundations/func.rs @@ -5,15 +5,15 @@ use std::fmt::{self, Debug, Formatter}; use std::sync::{Arc, LazyLock}; use comemo::{Tracked, TrackedMut}; -use ecow::{eco_format, EcoString}; -use typst_syntax::{ast, Span, SyntaxNode}; -use typst_utils::{singleton, LazyHash, Static}; +use ecow::{EcoString, eco_format}; +use typst_syntax::{Span, SyntaxNode, ast}; +use typst_utils::{LazyHash, Static, singleton}; -use crate::diag::{bail, At, DeprecationSink, SourceResult, StrResult}; +use crate::diag::{At, DeprecationSink, SourceResult, StrResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, repr, scope, ty, Args, Bytes, CastInfo, Content, Context, Element, IntoArgs, - PluginFunc, Scope, Selector, Type, Value, + Args, Bytes, CastInfo, Content, Context, Element, IntoArgs, PluginFunc, Scope, + Selector, Type, Value, cast, repr, scope, ty, }; /// A mapping from argument values to a return value. diff --git a/crates/typst-library/src/foundations/int.rs b/crates/typst-library/src/foundations/int.rs index 13f457a11..aa8655889 100644 --- a/crates/typst-library/src/foundations/int.rs +++ b/crates/typst-library/src/foundations/int.rs @@ -2,12 +2,12 @@ use std::num::{ NonZeroI64, NonZeroIsize, NonZeroU32, NonZeroU64, NonZeroUsize, ParseIntError, }; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use smallvec::SmallVec; -use crate::diag::{bail, StrResult}; +use crate::diag::{StrResult, bail}; use crate::foundations::{ - cast, func, repr, scope, ty, Bytes, Cast, Decimal, Repr, Str, Value, + Bytes, Cast, Decimal, Repr, Str, Value, cast, func, repr, scope, ty, }; /// A whole number. diff --git a/crates/typst-library/src/foundations/label.rs b/crates/typst-library/src/foundations/label.rs index b1ac58bf2..5a9e76538 100644 --- a/crates/typst-library/src/foundations/label.rs +++ b/crates/typst-library/src/foundations/label.rs @@ -1,8 +1,8 @@ -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_utils::{PicoStr, ResolvedPicoStr}; use crate::diag::StrResult; -use crate::foundations::{bail, func, scope, ty, Repr, Str}; +use crate::foundations::{Repr, Str, bail, func, scope, ty}; /// A label for an element. /// diff --git a/crates/typst-library/src/foundations/mod.rs b/crates/typst-library/src/foundations/mod.rs index 382beb2cd..8a94107c2 100644 --- a/crates/typst-library/src/foundations/mod.rs +++ b/crates/typst-library/src/foundations/mod.rs @@ -80,7 +80,7 @@ use comemo::TrackedMut; use ecow::EcoString; use typst_syntax::Spanned; -use crate::diag::{bail, SourceResult, StrResult}; +use crate::diag::{SourceResult, StrResult, bail}; use crate::engine::Engine; use crate::{Feature, Features}; diff --git a/crates/typst-library/src/foundations/module.rs b/crates/typst-library/src/foundations/module.rs index 14eefca39..83c6d0492 100644 --- a/crates/typst-library/src/foundations/module.rs +++ b/crates/typst-library/src/foundations/module.rs @@ -1,11 +1,11 @@ use std::fmt::{self, Debug, Formatter}; use std::sync::Arc; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_syntax::FileId; -use crate::diag::{bail, DeprecationSink, StrResult}; -use crate::foundations::{repr, ty, Content, Scope, Value}; +use crate::diag::{DeprecationSink, StrResult, bail}; +use crate::foundations::{Content, Scope, Value, repr, ty}; /// A collection of variables and functions that are commonly related to /// a single theme. diff --git a/crates/typst-library/src/foundations/none.rs b/crates/typst-library/src/foundations/none.rs index d376c0c5b..b38ccaf3e 100644 --- a/crates/typst-library/src/foundations/none.rs +++ b/crates/typst-library/src/foundations/none.rs @@ -5,7 +5,7 @@ use serde::{Serialize, Serializer}; use crate::diag::HintedStrResult; use crate::foundations::{ - cast, ty, CastInfo, FromValue, IntoValue, Reflect, Repr, Type, Value, + CastInfo, FromValue, IntoValue, Reflect, Repr, Type, Value, cast, ty, }; /// A value that indicates the absence of any other value. diff --git a/crates/typst-library/src/foundations/ops.rs b/crates/typst-library/src/foundations/ops.rs index 3c6a5e6cf..0aed5af4f 100644 --- a/crates/typst-library/src/foundations/ops.rs +++ b/crates/typst-library/src/foundations/ops.rs @@ -5,9 +5,9 @@ use std::cmp::Ordering; use ecow::eco_format; use typst_utils::Numeric; -use crate::diag::{bail, HintedStrResult, StrResult}; +use crate::diag::{HintedStrResult, StrResult, bail}; use crate::foundations::{ - format_str, Datetime, IntoValue, Regex, Repr, SymbolElem, Value, + Datetime, IntoValue, Regex, Repr, SymbolElem, Value, format_str, }; use crate::layout::{Alignment, Length, Rel}; use crate::text::TextElem; diff --git a/crates/typst-library/src/foundations/plugin.rs b/crates/typst-library/src/foundations/plugin.rs index a04443bf4..7908407b3 100644 --- a/crates/typst-library/src/foundations/plugin.rs +++ b/crates/typst-library/src/foundations/plugin.rs @@ -2,13 +2,13 @@ use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex}; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_syntax::Spanned; use wasmi::Memory; -use crate::diag::{bail, At, SourceResult, StrResult}; +use crate::diag::{At, SourceResult, StrResult, bail}; use crate::engine::Engine; -use crate::foundations::{cast, func, scope, Binding, Bytes, Func, Module, Scope, Value}; +use crate::foundations::{Binding, Bytes, Func, Module, Scope, Value, cast, func, scope}; use crate::loading::{DataSource, Load}; /// Loads a WebAssembly module. diff --git a/crates/typst-library/src/foundations/repr.rs b/crates/typst-library/src/foundations/repr.rs index e219b0f1c..ea9ff4ce6 100644 --- a/crates/typst-library/src/foundations/repr.rs +++ b/crates/typst-library/src/foundations/repr.rs @@ -1,9 +1,9 @@ //! Debug representation of values. -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_utils::round_with_precision; -use crate::foundations::{func, Str, Value}; +use crate::foundations::{Str, Value, func}; /// The Unicode minus sign. pub const MINUS_SIGN: &str = "\u{2212}"; diff --git a/crates/typst-library/src/foundations/scope.rs b/crates/typst-library/src/foundations/scope.rs index 838584ccd..551e3dd78 100644 --- a/crates/typst-library/src/foundations/scope.rs +++ b/crates/typst-library/src/foundations/scope.rs @@ -1,12 +1,12 @@ use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; -use ecow::{eco_format, EcoString}; -use indexmap::map::Entry; +use ecow::{EcoString, eco_format}; use indexmap::IndexMap; +use indexmap::map::Entry; use typst_syntax::Span; -use crate::diag::{bail, DeprecationSink, HintedStrResult, HintedString, StrResult}; +use crate::diag::{DeprecationSink, HintedStrResult, HintedString, StrResult, bail}; use crate::foundations::{ Func, IntoValue, NativeElement, NativeFunc, NativeFuncData, NativeType, Value, }; diff --git a/crates/typst-library/src/foundations/selector.rs b/crates/typst-library/src/foundations/selector.rs index b8e34eb95..7485a46ff 100644 --- a/crates/typst-library/src/foundations/selector.rs +++ b/crates/typst-library/src/foundations/selector.rs @@ -2,13 +2,13 @@ use std::any::{Any, TypeId}; use std::sync::Arc; use comemo::Tracked; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; use smallvec::SmallVec; -use crate::diag::{bail, HintedStrResult, StrResult}; +use crate::diag::{HintedStrResult, StrResult, bail}; use crate::foundations::{ - cast, func, repr, scope, ty, CastInfo, Content, Context, Dict, Element, FromValue, - Func, Label, Reflect, Regex, Repr, Str, StyleChain, Symbol, Type, Value, + CastInfo, Content, Context, Dict, Element, FromValue, Func, Label, Reflect, Regex, + Repr, Str, StyleChain, Symbol, Type, Value, cast, func, repr, scope, ty, }; use crate::introspection::{Introspector, Locatable, Location, Unqueriable}; diff --git a/crates/typst-library/src/foundations/str.rs b/crates/typst-library/src/foundations/str.rs index e500b1a4d..4299a9348 100644 --- a/crates/typst-library/src/foundations/str.rs +++ b/crates/typst-library/src/foundations/str.rs @@ -10,11 +10,11 @@ use typst_syntax::{Span, Spanned}; use unicode_normalization::UnicodeNormalization; use unicode_segmentation::UnicodeSegmentation; -use crate::diag::{bail, At, SourceResult, StrResult}; +use crate::diag::{At, SourceResult, StrResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, dict, func, repr, scope, ty, Array, Bytes, Cast, Context, Decimal, Dict, Func, - IntoValue, Label, Repr, Type, Value, Version, + Array, Bytes, Cast, Context, Decimal, Dict, Func, IntoValue, Label, Repr, Type, + Value, Version, cast, dict, func, repr, scope, ty, }; use crate::layout::Alignment; @@ -881,7 +881,11 @@ fn out_of_bounds(index: i64, len: usize) -> EcoString { /// The out of bounds access error message when no default value was given. #[cold] fn no_default_and_out_of_bounds(index: i64, len: usize) -> EcoString { - eco_format!("no default value was specified and string index out of bounds (index: {}, len: {})", index, len) + eco_format!( + "no default value was specified and string index out of bounds (index: {}, len: {})", + index, + len + ) } /// The char boundary access error message. diff --git a/crates/typst-library/src/foundations/styles.rs b/crates/typst-library/src/foundations/styles.rs index 0da036f6f..74dd039de 100644 --- a/crates/typst-library/src/foundations/styles.rs +++ b/crates/typst-library/src/foundations/styles.rs @@ -5,7 +5,7 @@ use std::hash::{Hash, Hasher}; use std::{mem, ptr}; use comemo::Tracked; -use ecow::{eco_vec, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_vec}; use smallvec::SmallVec; use typst_syntax::Span; use typst_utils::LazyHash; @@ -13,8 +13,8 @@ use typst_utils::LazyHash; use crate::diag::{SourceResult, Trace, Tracepoint}; use crate::engine::Engine; use crate::foundations::{ - cast, ty, Content, Context, Element, Field, Func, NativeElement, OneOrMultiple, - Packed, RefableProperty, Repr, Selector, SettableProperty, Target, + Content, Context, Element, Field, Func, NativeElement, OneOrMultiple, Packed, + RefableProperty, Repr, Selector, SettableProperty, Target, cast, ty, }; use crate::text::{FontFamily, FontList, TextElem}; @@ -621,11 +621,7 @@ impl<'a> StyleChain<'a> { .properties(func, id) .map(|block| block.downcast::(func, id).clone()); - if let Some(folded) = iter.reduce(fold) { - fold(folded, default) - } else { - default - } + if let Some(folded) = iter.reduce(fold) { fold(folded, default) } else { default } } /// Iterate over all values for the given property in the chain. diff --git a/crates/typst-library/src/foundations/symbol.rs b/crates/typst-library/src/foundations/symbol.rs index f57bb0c2a..898068afb 100644 --- a/crates/typst-library/src/foundations/symbol.rs +++ b/crates/typst-library/src/foundations/symbol.rs @@ -3,15 +3,15 @@ use std::fmt::{self, Debug, Display, Formatter, Write}; use std::sync::Arc; use codex::ModifierSet; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use serde::{Serialize, Serializer}; -use typst_syntax::{is_ident, Span, Spanned}; +use typst_syntax::{Span, Spanned, is_ident}; use typst_utils::hash128; -use crate::diag::{bail, DeprecationSink, SourceResult, StrResult}; +use crate::diag::{DeprecationSink, SourceResult, StrResult, bail}; use crate::foundations::{ - cast, elem, func, scope, ty, Array, Content, Func, NativeElement, NativeFunc, Packed, - PlainText, Repr as _, + Array, Content, Func, NativeElement, NativeFunc, Packed, PlainText, Repr as _, cast, + elem, func, scope, ty, }; /// A Unicode symbol. diff --git a/crates/typst-library/src/foundations/target.rs b/crates/typst-library/src/foundations/target.rs index ff90f1f7b..c020ac806 100644 --- a/crates/typst-library/src/foundations/target.rs +++ b/crates/typst-library/src/foundations/target.rs @@ -1,7 +1,7 @@ use comemo::Tracked; use crate::diag::HintedStrResult; -use crate::foundations::{elem, func, Cast, Context}; +use crate::foundations::{Cast, Context, elem, func}; /// The export target. #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash, Cast)] diff --git a/crates/typst-library/src/foundations/ty.rs b/crates/typst-library/src/foundations/ty.rs index 9d7690283..2b59e2ce4 100644 --- a/crates/typst-library/src/foundations/ty.rs +++ b/crates/typst-library/src/foundations/ty.rs @@ -5,12 +5,12 @@ use std::cmp::Ordering; use std::fmt::{self, Debug, Display, Formatter}; use std::sync::LazyLock; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_utils::Static; -use crate::diag::{bail, DeprecationSink, StrResult}; +use crate::diag::{DeprecationSink, StrResult, bail}; use crate::foundations::{ - cast, func, AutoValue, Func, NativeFuncData, NoneValue, Repr, Scope, Value, + AutoValue, Func, NativeFuncData, NoneValue, Repr, Scope, Value, cast, func, }; /// Describes a kind of value. diff --git a/crates/typst-library/src/foundations/value.rs b/crates/typst-library/src/foundations/value.rs index 4bcf2d4e3..f0acd5036 100644 --- a/crates/typst-library/src/foundations/value.rs +++ b/crates/typst-library/src/foundations/value.rs @@ -4,19 +4,19 @@ use std::fmt::{self, Debug, Formatter}; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer}; use serde::de::{Error, MapAccess, SeqAccess, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; -use typst_syntax::{ast, Span}; +use typst_syntax::{Span, ast}; use typst_utils::ArcExt; use crate::diag::{DeprecationSink, HintedStrResult, HintedString, StrResult}; use crate::foundations::{ - fields, ops, repr, Args, Array, AutoValue, Bytes, CastInfo, Content, Datetime, - Decimal, Dict, Duration, Fold, FromValue, Func, IntoValue, Label, Module, - NativeElement, NativeType, NoneValue, Reflect, Repr, Resolve, Scope, Str, Styles, - Symbol, SymbolElem, Type, Version, + Args, Array, AutoValue, Bytes, CastInfo, Content, Datetime, Decimal, Dict, Duration, + Fold, FromValue, Func, IntoValue, Label, Module, NativeElement, NativeType, + NoneValue, Reflect, Repr, Resolve, Scope, Str, Styles, Symbol, SymbolElem, Type, + Version, fields, ops, repr, }; use crate::layout::{Abs, Angle, Em, Fr, Length, Ratio, Rel}; use crate::text::{RawContent, RawElem, TextElem}; diff --git a/crates/typst-library/src/foundations/version.rs b/crates/typst-library/src/foundations/version.rs index 62c029179..71b0b7153 100644 --- a/crates/typst-library/src/foundations/version.rs +++ b/crates/typst-library/src/foundations/version.rs @@ -3,10 +3,10 @@ use std::fmt::{self, Display, Formatter, Write}; use std::hash::Hash; use std::iter::repeat; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; -use crate::diag::{bail, StrResult}; -use crate::foundations::{cast, func, repr, scope, ty, Repr}; +use crate::diag::{StrResult, bail}; +use crate::foundations::{Repr, cast, func, repr, scope, ty}; /// A version with an arbitrary number of components. /// diff --git a/crates/typst-library/src/introspection/counter.rs b/crates/typst-library/src/introspection/counter.rs index b3c52de4e..f6083303d 100644 --- a/crates/typst-library/src/introspection/counter.rs +++ b/crates/typst-library/src/introspection/counter.rs @@ -2,24 +2,24 @@ use std::num::NonZeroUsize; use std::str::FromStr; use comemo::{Track, Tracked, TrackedMut}; -use ecow::{eco_format, eco_vec, EcoString, EcoVec}; -use smallvec::{smallvec, SmallVec}; +use ecow::{EcoString, EcoVec, eco_format, eco_vec}; +use smallvec::{SmallVec, smallvec}; use typst_syntax::Span; use typst_utils::NonZeroExt; -use crate::diag::{bail, At, HintedStrResult, SourceResult}; +use crate::World; +use crate::diag::{At, HintedStrResult, SourceResult, bail}; use crate::engine::{Engine, Route, Sink, Traced}; use crate::foundations::{ - cast, elem, func, scope, select_where, ty, Args, Array, Construct, Content, Context, - Element, Func, IntoValue, Label, LocatableSelector, NativeElement, Packed, Repr, - Selector, ShowFn, Smart, Str, StyleChain, Value, + Args, Array, Construct, Content, Context, Element, Func, IntoValue, Label, + LocatableSelector, NativeElement, Packed, Repr, Selector, ShowFn, Smart, Str, + StyleChain, Value, cast, elem, func, scope, select_where, ty, }; use crate::introspection::{Introspector, Locatable, Location, Tag}; use crate::layout::{Frame, FrameItem, PageElem}; use crate::math::EquationElem; use crate::model::{FigureElem, FootnoteElem, HeadingElem, Numbering, NumberingPattern}; use crate::routines::Routines; -use crate::World; /// Counts through pages, elements, and more. /// diff --git a/crates/typst-library/src/introspection/here.rs b/crates/typst-library/src/introspection/here.rs index 510093247..27cb56224 100644 --- a/crates/typst-library/src/introspection/here.rs +++ b/crates/typst-library/src/introspection/here.rs @@ -1,7 +1,7 @@ use comemo::Tracked; use crate::diag::HintedStrResult; -use crate::foundations::{func, Context}; +use crate::foundations::{Context, func}; use crate::introspection::Location; /// Provides the current location in the document. diff --git a/crates/typst-library/src/introspection/introspector.rs b/crates/typst-library/src/introspection/introspector.rs index 76a0faa35..377b577fb 100644 --- a/crates/typst-library/src/introspection/introspector.rs +++ b/crates/typst-library/src/introspection/introspector.rs @@ -8,7 +8,7 @@ use ecow::{EcoString, EcoVec}; use smallvec::SmallVec; use typst_utils::NonZeroExt; -use crate::diag::{bail, StrResult}; +use crate::diag::{StrResult, bail}; use crate::foundations::{Content, Label, Repr, Selector}; use crate::introspection::{Location, Tag}; use crate::layout::{Frame, FrameItem, Point, Position, Transform}; diff --git a/crates/typst-library/src/introspection/locate.rs b/crates/typst-library/src/introspection/locate.rs index 50f217851..4d386e033 100644 --- a/crates/typst-library/src/introspection/locate.rs +++ b/crates/typst-library/src/introspection/locate.rs @@ -2,7 +2,7 @@ use comemo::Tracked; use crate::diag::HintedStrResult; use crate::engine::Engine; -use crate::foundations::{func, Context, LocatableSelector}; +use crate::foundations::{Context, LocatableSelector, func}; use crate::introspection::Location; /// Determines the location of an element in the document. diff --git a/crates/typst-library/src/introspection/location.rs b/crates/typst-library/src/introspection/location.rs index 8f4caaec4..d0a6ec21c 100644 --- a/crates/typst-library/src/introspection/location.rs +++ b/crates/typst-library/src/introspection/location.rs @@ -4,7 +4,7 @@ use std::num::NonZeroUsize; use ecow::EcoString; use crate::engine::Engine; -use crate::foundations::{func, scope, ty, Repr}; +use crate::foundations::{Repr, func, scope, ty}; use crate::layout::Position; use crate::model::Numbering; diff --git a/crates/typst-library/src/introspection/metadata.rs b/crates/typst-library/src/introspection/metadata.rs index 8ad74b96b..5cc188ee2 100644 --- a/crates/typst-library/src/introspection/metadata.rs +++ b/crates/typst-library/src/introspection/metadata.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Value}; +use crate::foundations::{Value, elem}; use crate::introspection::Locatable; /// Exposes a value to the query system without producing visible content. diff --git a/crates/typst-library/src/introspection/query.rs b/crates/typst-library/src/introspection/query.rs index b742ac010..1691c0f0c 100644 --- a/crates/typst-library/src/introspection/query.rs +++ b/crates/typst-library/src/introspection/query.rs @@ -2,7 +2,7 @@ use comemo::Tracked; use crate::diag::HintedStrResult; use crate::engine::Engine; -use crate::foundations::{func, Array, Context, LocatableSelector, Value}; +use crate::foundations::{Array, Context, LocatableSelector, Value, func}; /// Finds elements in the document. /// diff --git a/crates/typst-library/src/introspection/state.rs b/crates/typst-library/src/introspection/state.rs index 2d15a5de0..c7d1a5be5 100644 --- a/crates/typst-library/src/introspection/state.rs +++ b/crates/typst-library/src/introspection/state.rs @@ -1,16 +1,16 @@ use comemo::{Track, Tracked, TrackedMut}; -use ecow::{eco_format, eco_vec, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format, eco_vec}; use typst_syntax::Span; -use crate::diag::{bail, At, SourceResult}; +use crate::World; +use crate::diag::{At, SourceResult, bail}; use crate::engine::{Engine, Route, Sink, Traced}; use crate::foundations::{ - cast, elem, func, scope, select_where, ty, Args, Construct, Content, Context, Func, - LocatableSelector, NativeElement, Repr, Selector, Str, Value, + Args, Construct, Content, Context, Func, LocatableSelector, NativeElement, Repr, + Selector, Str, Value, cast, elem, func, scope, select_where, ty, }; use crate::introspection::{Introspector, Locatable, Location}; use crate::routines::Routines; -use crate::World; /// Manages stateful parts of your document. /// diff --git a/crates/typst-library/src/introspection/tag.rs b/crates/typst-library/src/introspection/tag.rs index b2bae28e4..8df9e0176 100644 --- a/crates/typst-library/src/introspection/tag.rs +++ b/crates/typst-library/src/introspection/tag.rs @@ -1,9 +1,9 @@ use std::fmt::{self, Debug, Formatter}; -use crate::diag::{bail, SourceResult}; +use crate::diag::{SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - elem, Args, Construct, Content, NativeElement, Packed, Unlabellable, + Args, Construct, Content, NativeElement, Packed, Unlabellable, elem, }; use crate::introspection::Location; diff --git a/crates/typst-library/src/layout/abs.rs b/crates/typst-library/src/layout/abs.rs index e19b037aa..c9844ed4c 100644 --- a/crates/typst-library/src/layout/abs.rs +++ b/crates/typst-library/src/layout/abs.rs @@ -5,7 +5,7 @@ use std::ops::{Add, Div, Mul, Neg, Rem}; use ecow::EcoString; use typst_utils::{Numeric, Scalar}; -use crate::foundations::{cast, repr, Fold, Repr, Value}; +use crate::foundations::{Fold, Repr, Value, cast, repr}; /// An absolute length. #[derive(Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] diff --git a/crates/typst-library/src/layout/align.rs b/crates/typst-library/src/layout/align.rs index 447648f01..4ce195f81 100644 --- a/crates/typst-library/src/layout/align.rs +++ b/crates/typst-library/src/layout/align.rs @@ -1,11 +1,11 @@ use std::ops::Add; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; -use crate::diag::{bail, HintedStrResult, StrResult}; +use crate::diag::{HintedStrResult, StrResult, bail}; use crate::foundations::{ - cast, elem, func, scope, ty, CastInfo, Content, Fold, FromValue, IntoValue, Reflect, - Repr, Resolve, StyleChain, Value, + CastInfo, Content, Fold, FromValue, IntoValue, Reflect, Repr, Resolve, StyleChain, + Value, cast, elem, func, scope, ty, }; use crate::layout::{Abs, Axes, Axis, Dir, Side}; use crate::text::TextElem; diff --git a/crates/typst-library/src/layout/angle.rs b/crates/typst-library/src/layout/angle.rs index d14107860..6ace7cf69 100644 --- a/crates/typst-library/src/layout/angle.rs +++ b/crates/typst-library/src/layout/angle.rs @@ -6,7 +6,7 @@ use std::ops::{Add, Div, Mul, Neg}; use ecow::EcoString; use typst_utils::{Numeric, Scalar}; -use crate::foundations::{func, repr, scope, ty, Repr}; +use crate::foundations::{Repr, func, repr, scope, ty}; /// An angle describing a rotation. /// diff --git a/crates/typst-library/src/layout/axes.rs b/crates/typst-library/src/layout/axes.rs index e4303f98b..ec2b16744 100644 --- a/crates/typst-library/src/layout/axes.rs +++ b/crates/typst-library/src/layout/axes.rs @@ -4,10 +4,10 @@ use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Deref, Not}; use typst_utils::Get; -use crate::diag::{bail, HintedStrResult}; +use crate::diag::{HintedStrResult, bail}; use crate::foundations::{ - array, cast, Array, CastInfo, FromValue, IntoValue, Reflect, Resolve, Smart, - StyleChain, Value, + Array, CastInfo, FromValue, IntoValue, Reflect, Resolve, Smart, StyleChain, Value, + array, cast, }; use crate::layout::{Abs, Dir, Rel, Size}; diff --git a/crates/typst-library/src/layout/columns.rs b/crates/typst-library/src/layout/columns.rs index e7bce393b..3452f17d4 100644 --- a/crates/typst-library/src/layout/columns.rs +++ b/crates/typst-library/src/layout/columns.rs @@ -1,6 +1,6 @@ use std::num::NonZeroUsize; -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; use crate::layout::{Length, Ratio, Rel}; /// Separates a region into multiple equally sized columns. diff --git a/crates/typst-library/src/layout/container.rs b/crates/typst-library/src/layout/container.rs index cff66fe38..084d07bf4 100644 --- a/crates/typst-library/src/layout/container.rs +++ b/crates/typst-library/src/layout/container.rs @@ -1,8 +1,8 @@ -use crate::diag::{bail, SourceResult}; +use crate::diag::{SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, Args, AutoValue, Construct, Content, NativeElement, Packed, Smart, - StyleChain, Value, + Args, AutoValue, Construct, Content, NativeElement, Packed, Smart, StyleChain, Value, + cast, elem, }; use crate::introspection::Locator; use crate::layout::{ diff --git a/crates/typst-library/src/layout/corners.rs b/crates/typst-library/src/layout/corners.rs index e47fee1e7..f822a45cb 100644 --- a/crates/typst-library/src/layout/corners.rs +++ b/crates/typst-library/src/layout/corners.rs @@ -151,9 +151,10 @@ where { fn into_value(self) -> Value { if self.is_uniform() - && let Some(top_left) = self.top_left { - return top_left.into_value(); - } + && let Some(top_left) = self.top_left + { + return top_left.into_value(); + } let mut dict = Dict::new(); let mut handle = |key: &str, component: Option| { diff --git a/crates/typst-library/src/layout/dir.rs b/crates/typst-library/src/layout/dir.rs index 699c8c481..c4559477b 100644 --- a/crates/typst-library/src/layout/dir.rs +++ b/crates/typst-library/src/layout/dir.rs @@ -1,6 +1,6 @@ use ecow::EcoString; -use crate::foundations::{func, scope, ty, Repr}; +use crate::foundations::{Repr, func, scope, ty}; use crate::layout::{Axis, Side}; /// The four directions into which content can be laid out. diff --git a/crates/typst-library/src/layout/em.rs b/crates/typst-library/src/layout/em.rs index 460bf5fa7..3dbda7550 100644 --- a/crates/typst-library/src/layout/em.rs +++ b/crates/typst-library/src/layout/em.rs @@ -5,7 +5,7 @@ use std::ops::{Add, Div, Mul, Neg}; use ecow::EcoString; use typst_utils::{Numeric, Scalar}; -use crate::foundations::{cast, repr, Repr, Resolve, StyleChain, Value}; +use crate::foundations::{Repr, Resolve, StyleChain, Value, cast, repr}; use crate::layout::{Abs, Length}; use crate::text::TextElem; @@ -39,11 +39,7 @@ impl Em { /// Creates an em length from an absolute length at the given font size. pub fn from_abs(length: Abs, font_size: Abs) -> Self { let result = length / font_size; - if result.is_finite() { - Self(Scalar::new(result)) - } else { - Self::zero() - } + if result.is_finite() { Self(Scalar::new(result)) } else { Self::zero() } } /// Creates an em length from a length at the given font size. @@ -64,11 +60,7 @@ impl Em { /// Converts to an absolute length at the given font size. pub fn at(self, font_size: Abs) -> Abs { let resolved = font_size * self.get(); - if resolved.is_finite() { - resolved - } else { - Abs::zero() - } + if resolved.is_finite() { resolved } else { Abs::zero() } } } @@ -164,10 +156,6 @@ impl Resolve for Em { type Output = Abs; fn resolve(self, styles: StyleChain) -> Self::Output { - if self.is_zero() { - Abs::zero() - } else { - self.at(styles.resolve(TextElem::size)) - } + if self.is_zero() { Abs::zero() } else { self.at(styles.resolve(TextElem::size)) } } } diff --git a/crates/typst-library/src/layout/fr.rs b/crates/typst-library/src/layout/fr.rs index ff8a6e6b1..f76d32f96 100644 --- a/crates/typst-library/src/layout/fr.rs +++ b/crates/typst-library/src/layout/fr.rs @@ -5,7 +5,7 @@ use std::ops::{Add, Div, Mul, Neg}; use ecow::EcoString; use typst_utils::{Numeric, Scalar}; -use crate::foundations::{repr, ty, Repr}; +use crate::foundations::{Repr, repr, ty}; use crate::layout::Abs; /// Defines how the remaining space in a layout is distributed. diff --git a/crates/typst-library/src/layout/frame.rs b/crates/typst-library/src/layout/frame.rs index a26a7d0ef..7dfeb6e49 100644 --- a/crates/typst-library/src/layout/frame.rs +++ b/crates/typst-library/src/layout/frame.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use typst_syntax::Span; use typst_utils::{LazyHash, Numeric}; -use crate::foundations::{cast, dict, Dict, Label, Value}; +use crate::foundations::{Dict, Label, Value, cast, dict}; use crate::introspection::{Location, Tag}; use crate::layout::{Abs, Axes, FixedAlignment, Length, Point, Size, Transform}; use crate::model::Destination; diff --git a/crates/typst-library/src/layout/grid/mod.rs b/crates/typst-library/src/layout/grid/mod.rs index 658523ec6..de540a578 100644 --- a/crates/typst-library/src/layout/grid/mod.rs +++ b/crates/typst-library/src/layout/grid/mod.rs @@ -4,14 +4,14 @@ use std::num::{NonZeroU32, NonZeroUsize}; use std::sync::Arc; use comemo::Track; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use typst_utils::NonZeroExt; -use crate::diag::{bail, At, HintedStrResult, HintedString, SourceResult}; +use crate::diag::{At, HintedStrResult, HintedString, SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, scope, Array, CastInfo, Content, Context, Fold, FromValue, Func, - IntoValue, Packed, Reflect, Resolve, Smart, StyleChain, Value, + Array, CastInfo, Content, Context, Fold, FromValue, Func, IntoValue, Packed, Reflect, + Resolve, Smart, StyleChain, Value, cast, elem, scope, }; use crate::layout::{ Alignment, Length, OuterHAlignment, OuterVAlignment, Rel, Sides, Sizing, diff --git a/crates/typst-library/src/layout/grid/resolve.rs b/crates/typst-library/src/layout/grid/resolve.rs index edf50cdd2..b7d2ffa6c 100644 --- a/crates/typst-library/src/layout/grid/resolve.rs +++ b/crates/typst-library/src/layout/grid/resolve.rs @@ -3,8 +3,9 @@ use std::ops::{Deref, DerefMut, Range}; use std::sync::Arc; use ecow::eco_format; +use typst_library::Dir; use typst_library::diag::{ - bail, At, Hint, HintedStrResult, HintedString, SourceResult, Trace, Tracepoint, + At, Hint, HintedStrResult, HintedString, SourceResult, Trace, Tracepoint, bail, }; use typst_library::engine::Engine; use typst_library::foundations::{Content, Fold, Packed, Smart, StyleChain}; @@ -16,7 +17,6 @@ use typst_library::layout::{ use typst_library::model::{TableCell, TableChild, TableElem, TableItem}; use typst_library::text::TextElem; use typst_library::visualize::{Paint, Stroke}; -use typst_library::Dir; use typst_syntax::Span; use typst_utils::NonZeroExt; @@ -495,11 +495,7 @@ impl Repeatable { /// Returns `Some` if the value is repeated, `None` otherwise. #[inline] pub fn as_repeated(&self) -> Option<&T> { - if self.repeated { - Some(&self.inner) - } else { - None - } + if self.repeated { Some(&self.inner) } else { None } } } @@ -858,22 +854,14 @@ impl<'a> CellGrid<'a> { /// might span if the grid has gutters. #[inline] pub fn effective_colspan_of_cell(&self, cell: &Cell) -> usize { - if self.has_gutter { - 2 * cell.colspan.get() - 1 - } else { - cell.colspan.get() - } + if self.has_gutter { 2 * cell.colspan.get() - 1 } else { cell.colspan.get() } } /// Returns the effective rowspan of a cell, considering the gutters it /// might span if the grid has gutters. #[inline] pub fn effective_rowspan_of_cell(&self, cell: &Cell) -> usize { - if self.has_gutter { - 2 * cell.rowspan.get() - 1 - } else { - cell.rowspan.get() - } + if self.has_gutter { 2 * cell.rowspan.get() - 1 } else { cell.rowspan.get() } } #[inline] @@ -2099,12 +2087,14 @@ fn check_for_conflicting_cell_row( } if let Some((_, _, footer)) = footer - && cell_y < footer.end && cell_y + rowspan > footer.start { - bail!( - "cell would conflict with footer spanning the same position"; - hint: "try reducing the cell's rowspan or moving the footer" - ); - } + && cell_y < footer.end + && cell_y + rowspan > footer.start + { + bail!( + "cell would conflict with footer spanning the same position"; + hint: "try reducing the cell's rowspan or moving the footer" + ); + } Ok(()) } diff --git a/crates/typst-library/src/layout/hide.rs b/crates/typst-library/src/layout/hide.rs index bb40447d5..7e096eaa9 100644 --- a/crates/typst-library/src/layout/hide.rs +++ b/crates/typst-library/src/layout/hide.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; /// Hides content without affecting layout. /// diff --git a/crates/typst-library/src/layout/layout.rs b/crates/typst-library/src/layout/layout.rs index 00897bcfe..8855813c1 100644 --- a/crates/typst-library/src/layout/layout.rs +++ b/crates/typst-library/src/layout/layout.rs @@ -1,6 +1,6 @@ use typst_syntax::Span; -use crate::foundations::{elem, func, Content, Func, NativeElement}; +use crate::foundations::{Content, Func, NativeElement, elem, func}; use crate::introspection::Locatable; /// Provides access to the current outer container's (or page's, if none) diff --git a/crates/typst-library/src/layout/length.rs b/crates/typst-library/src/layout/length.rs index 800140c47..76ee2ce56 100644 --- a/crates/typst-library/src/layout/length.rs +++ b/crates/typst-library/src/layout/length.rs @@ -3,12 +3,12 @@ use std::fmt::{self, Debug, Formatter}; use std::ops::{Add, Div, Mul, Neg}; use comemo::Tracked; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_syntax::Span; use typst_utils::Numeric; -use crate::diag::{bail, HintedStrResult, SourceResult}; -use crate::foundations::{func, scope, ty, Context, Fold, Repr, Resolve, StyleChain}; +use crate::diag::{HintedStrResult, SourceResult, bail}; +use crate::foundations::{Context, Fold, Repr, Resolve, StyleChain, func, scope, ty}; use crate::layout::{Abs, Em}; /// A size or distance, possibly expressed with contextual units. diff --git a/crates/typst-library/src/layout/measure.rs b/crates/typst-library/src/layout/measure.rs index 93c48ad40..aa7f3c7c4 100644 --- a/crates/typst-library/src/layout/measure.rs +++ b/crates/typst-library/src/layout/measure.rs @@ -3,7 +3,7 @@ use typst_syntax::Span; use crate::diag::{At, SourceResult}; use crate::engine::Engine; -use crate::foundations::{dict, func, Content, Context, Dict, Resolve, Smart}; +use crate::foundations::{Content, Context, Dict, Resolve, Smart, dict, func}; use crate::introspection::{Locator, LocatorLink}; use crate::layout::{Abs, Axes, Length, Region, Size}; diff --git a/crates/typst-library/src/layout/pad.rs b/crates/typst-library/src/layout/pad.rs index d533df35b..8279c4e2d 100644 --- a/crates/typst-library/src/layout/pad.rs +++ b/crates/typst-library/src/layout/pad.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; use crate::layout::{Length, Rel}; /// Adds spacing around content. diff --git a/crates/typst-library/src/layout/page.rs b/crates/typst-library/src/layout/page.rs index ab8cc8ea4..64ed99e34 100644 --- a/crates/typst-library/src/layout/page.rs +++ b/crates/typst-library/src/layout/page.rs @@ -2,13 +2,13 @@ use std::num::NonZeroUsize; use std::ops::RangeInclusive; use std::str::FromStr; -use typst_utils::{singleton, NonZeroExt, Scalar}; +use typst_utils::{NonZeroExt, Scalar, singleton}; -use crate::diag::{bail, SourceResult}; +use crate::diag::{SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, Args, AutoValue, Cast, Construct, Content, Dict, Fold, NativeElement, - Set, Smart, Value, + Args, AutoValue, Cast, Construct, Content, Dict, Fold, NativeElement, Set, Smart, + Value, cast, elem, }; use crate::introspection::Introspector; use crate::layout::{ diff --git a/crates/typst-library/src/layout/place.rs b/crates/typst-library/src/layout/place.rs index b6c4a0cc1..4c92a8d9f 100644 --- a/crates/typst-library/src/layout/place.rs +++ b/crates/typst-library/src/layout/place.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, scope, Cast, Content, Packed, Smart}; +use crate::foundations::{Cast, Content, Packed, Smart, elem, scope}; use crate::introspection::{Locatable, Unqueriable}; use crate::layout::{Alignment, Em, Length, Rel}; diff --git a/crates/typst-library/src/layout/ratio.rs b/crates/typst-library/src/layout/ratio.rs index cf826c2b5..bb36045a8 100644 --- a/crates/typst-library/src/layout/ratio.rs +++ b/crates/typst-library/src/layout/ratio.rs @@ -4,7 +4,7 @@ use std::ops::{Add, Div, Mul, Neg}; use ecow::EcoString; use typst_utils::{Numeric, Scalar}; -use crate::foundations::{repr, ty, Repr}; +use crate::foundations::{Repr, repr, ty}; /// A ratio of a whole. /// @@ -80,11 +80,7 @@ impl Ratio { /// Return the ratio of the given `whole`. pub fn of(self, whole: T) -> T { let resolved = whole * self.get(); - if resolved.is_finite() { - resolved - } else { - T::zero() - } + if resolved.is_finite() { resolved } else { T::zero() } } } diff --git a/crates/typst-library/src/layout/rel.rs b/crates/typst-library/src/layout/rel.rs index 7fe5d9c05..5569a762c 100644 --- a/crates/typst-library/src/layout/rel.rs +++ b/crates/typst-library/src/layout/rel.rs @@ -2,10 +2,10 @@ use std::cmp::Ordering; use std::fmt::{self, Debug, Formatter}; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_utils::Numeric; -use crate::foundations::{cast, ty, Fold, Repr, Resolve, StyleChain}; +use crate::foundations::{Fold, Repr, Resolve, StyleChain, cast, ty}; use crate::layout::{Abs, Em, Length, Ratio}; /// A length in relation to some known length. diff --git a/crates/typst-library/src/layout/repeat.rs b/crates/typst-library/src/layout/repeat.rs index a38d5f896..ef7a5bb05 100644 --- a/crates/typst-library/src/layout/repeat.rs +++ b/crates/typst-library/src/layout/repeat.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; use crate::layout::Length; /// Repeats content to the available space. diff --git a/crates/typst-library/src/layout/sides.rs b/crates/typst-library/src/layout/sides.rs index 1147eeb77..fc2f1114e 100644 --- a/crates/typst-library/src/layout/sides.rs +++ b/crates/typst-library/src/layout/sides.rs @@ -3,10 +3,10 @@ use std::ops::Add; use typst_utils::Get; -use crate::diag::{bail, HintedStrResult}; +use crate::diag::{HintedStrResult, bail}; use crate::foundations::{ - cast, AlternativeFold, CastInfo, Dict, Fold, FromValue, IntoValue, Reflect, Resolve, - StyleChain, Value, + AlternativeFold, CastInfo, Dict, Fold, FromValue, IntoValue, Reflect, Resolve, + StyleChain, Value, cast, }; use crate::layout::{Abs, Alignment, Axes, Axis, Corner, Rel, Size}; @@ -185,9 +185,10 @@ where { fn into_value(self) -> Value { if self.is_uniform() - && let Some(left) = self.left { - return left.into_value(); - } + && let Some(left) = self.left + { + return left.into_value(); + } let mut dict = Dict::new(); let mut handle = |key: &str, component: Option| { diff --git a/crates/typst-library/src/layout/spacing.rs b/crates/typst-library/src/layout/spacing.rs index b3ca1e812..8549c6b97 100644 --- a/crates/typst-library/src/layout/spacing.rs +++ b/crates/typst-library/src/layout/spacing.rs @@ -1,6 +1,6 @@ use typst_utils::Numeric; -use crate::foundations::{cast, elem, Content}; +use crate::foundations::{Content, cast, elem}; use crate::layout::{Abs, Em, Fr, Length, Ratio, Rel}; /// Inserts horizontal spacing into a paragraph. diff --git a/crates/typst-library/src/layout/stack.rs b/crates/typst-library/src/layout/stack.rs index fca1ecb86..90e55ca35 100644 --- a/crates/typst-library/src/layout/stack.rs +++ b/crates/typst-library/src/layout/stack.rs @@ -1,6 +1,6 @@ use std::fmt::{self, Debug, Formatter}; -use crate::foundations::{cast, elem, Content}; +use crate::foundations::{Content, cast, elem}; use crate::layout::{Dir, Spacing}; /// Arranges content and spacing horizontally or vertically. diff --git a/crates/typst-library/src/layout/transform.rs b/crates/typst-library/src/layout/transform.rs index c2d9a21c7..8543e6146 100644 --- a/crates/typst-library/src/layout/transform.rs +++ b/crates/typst-library/src/layout/transform.rs @@ -1,4 +1,4 @@ -use crate::foundations::{cast, elem, Content, Smart}; +use crate::foundations::{Content, Smart, cast, elem}; use crate::layout::{Abs, Alignment, Angle, HAlignment, Length, Ratio, Rel, VAlignment}; /// Moves content without affecting layout. diff --git a/crates/typst-library/src/loading/cbor.rs b/crates/typst-library/src/loading/cbor.rs index d95f73844..f6661395c 100644 --- a/crates/typst-library/src/loading/cbor.rs +++ b/crates/typst-library/src/loading/cbor.rs @@ -3,7 +3,7 @@ use typst_syntax::Spanned; use crate::diag::{At, SourceResult}; use crate::engine::Engine; -use crate::foundations::{func, scope, Bytes, Value}; +use crate::foundations::{Bytes, Value, func, scope}; use crate::loading::{DataSource, Load}; /// Reads structured data from a CBOR file. diff --git a/crates/typst-library/src/loading/csv.rs b/crates/typst-library/src/loading/csv.rs index d5b54a06c..a12eb9766 100644 --- a/crates/typst-library/src/loading/csv.rs +++ b/crates/typst-library/src/loading/csv.rs @@ -1,9 +1,9 @@ use az::SaturatingAs; use typst_syntax::Spanned; -use crate::diag::{bail, LineCol, LoadError, LoadedWithin, ReportPos, SourceResult}; +use crate::diag::{LineCol, LoadError, LoadedWithin, ReportPos, SourceResult, bail}; use crate::engine::Engine; -use crate::foundations::{cast, func, scope, Array, Dict, IntoValue, Type, Value}; +use crate::foundations::{Array, Dict, IntoValue, Type, Value, cast, func, scope}; use crate::loading::{DataSource, Load, Readable}; /// Reads structured data from a CSV file. diff --git a/crates/typst-library/src/loading/json.rs b/crates/typst-library/src/loading/json.rs index 7d0732ba0..a503825b4 100644 --- a/crates/typst-library/src/loading/json.rs +++ b/crates/typst-library/src/loading/json.rs @@ -3,7 +3,7 @@ use typst_syntax::Spanned; use crate::diag::{At, LineCol, LoadError, LoadedWithin, SourceResult}; use crate::engine::Engine; -use crate::foundations::{func, scope, Str, Value}; +use crate::foundations::{Str, Value, func, scope}; use crate::loading::{DataSource, Load, Readable}; /// Reads structured data from a JSON file. diff --git a/crates/typst-library/src/loading/mod.rs b/crates/typst-library/src/loading/mod.rs index 67f4be834..172248b74 100644 --- a/crates/typst-library/src/loading/mod.rs +++ b/crates/typst-library/src/loading/mod.rs @@ -27,10 +27,10 @@ pub use self::toml_::*; pub use self::xml_::*; pub use self::yaml_::*; +use crate::World; use crate::diag::{At, SourceResult}; use crate::foundations::OneOrMultiple; -use crate::foundations::{cast, Bytes, Scope, Str}; -use crate::World; +use crate::foundations::{Bytes, Scope, Str, cast}; /// Hook up all `data-loading` definitions. pub(super) fn define(global: &mut Scope) { diff --git a/crates/typst-library/src/loading/read.rs b/crates/typst-library/src/loading/read.rs index 91e6e4366..d003f1d38 100644 --- a/crates/typst-library/src/loading/read.rs +++ b/crates/typst-library/src/loading/read.rs @@ -3,7 +3,7 @@ use typst_syntax::Spanned; use crate::diag::{LoadedWithin, SourceResult}; use crate::engine::Engine; -use crate::foundations::{func, Cast}; +use crate::foundations::{Cast, func}; use crate::loading::{DataSource, Load, Readable}; /// Reads plain text or data from a file. diff --git a/crates/typst-library/src/loading/toml.rs b/crates/typst-library/src/loading/toml.rs index a4252feca..a14162d6b 100644 --- a/crates/typst-library/src/loading/toml.rs +++ b/crates/typst-library/src/loading/toml.rs @@ -3,7 +3,7 @@ use typst_syntax::Spanned; use crate::diag::{At, LoadError, LoadedWithin, ReportPos, SourceResult}; use crate::engine::Engine; -use crate::foundations::{func, scope, Str, Value}; +use crate::foundations::{Str, Value, func, scope}; use crate::loading::{DataSource, Load, Readable}; /// Reads structured data from a TOML file. diff --git a/crates/typst-library/src/loading/xml.rs b/crates/typst-library/src/loading/xml.rs index 0023c5df5..9a6197df7 100644 --- a/crates/typst-library/src/loading/xml.rs +++ b/crates/typst-library/src/loading/xml.rs @@ -1,9 +1,9 @@ use roxmltree::ParsingOptions; use typst_syntax::Spanned; -use crate::diag::{format_xml_like_error, LoadError, LoadedWithin, SourceResult}; +use crate::diag::{LoadError, LoadedWithin, SourceResult, format_xml_like_error}; use crate::engine::Engine; -use crate::foundations::{dict, func, scope, Array, Dict, IntoValue, Str, Value}; +use crate::foundations::{Array, Dict, IntoValue, Str, Value, dict, func, scope}; use crate::loading::{DataSource, Load, Readable}; /// Reads structured data from an XML file. diff --git a/crates/typst-library/src/loading/yaml.rs b/crates/typst-library/src/loading/yaml.rs index 0edf1f901..e26438cf5 100644 --- a/crates/typst-library/src/loading/yaml.rs +++ b/crates/typst-library/src/loading/yaml.rs @@ -3,7 +3,7 @@ use typst_syntax::Spanned; use crate::diag::{At, LineCol, LoadError, LoadedWithin, ReportPos, SourceResult}; use crate::engine::Engine; -use crate::foundations::{func, scope, Str, Value}; +use crate::foundations::{Str, Value, func, scope}; use crate::loading::{DataSource, Load, Readable}; /// Reads structured data from a YAML file. diff --git a/crates/typst-library/src/math/accent.rs b/crates/typst-library/src/math/accent.rs index 5a9c47aea..79e223042 100644 --- a/crates/typst-library/src/math/accent.rs +++ b/crates/typst-library/src/math/accent.rs @@ -1,12 +1,12 @@ use std::sync::LazyLock; -use icu_properties::maps::CodePointMapData; use icu_properties::CanonicalCombiningClass; +use icu_properties::maps::CodePointMapData; use icu_provider::AsDeserializingBufferProvider; use icu_provider_blob::BlobDataProvider; use crate::diag::bail; -use crate::foundations::{cast, elem, func, Content, NativeElement, SymbolElem}; +use crate::foundations::{Content, NativeElement, SymbolElem, cast, elem, func}; use crate::layout::{Length, Rel}; use crate::math::Mathy; diff --git a/crates/typst-library/src/math/attach.rs b/crates/typst-library/src/math/attach.rs index 0dda1d33d..ddcd63d7f 100644 --- a/crates/typst-library/src/math/attach.rs +++ b/crates/typst-library/src/math/attach.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content, Packed}; +use crate::foundations::{Content, Packed, elem}; use crate::layout::{Length, Rel}; use crate::math::{EquationElem, Mathy}; diff --git a/crates/typst-library/src/math/cancel.rs b/crates/typst-library/src/math/cancel.rs index 886370954..415e7ee7e 100644 --- a/crates/typst-library/src/math/cancel.rs +++ b/crates/typst-library/src/math/cancel.rs @@ -1,4 +1,4 @@ -use crate::foundations::{cast, elem, Content, Func, Smart}; +use crate::foundations::{Content, Func, Smart, cast, elem}; use crate::layout::{Abs, Angle, Length, Ratio, Rel}; use crate::math::Mathy; use crate::visualize::Stroke; diff --git a/crates/typst-library/src/math/equation.rs b/crates/typst-library/src/math/equation.rs index db5253834..45831f52c 100644 --- a/crates/typst-library/src/math/equation.rs +++ b/crates/typst-library/src/math/equation.rs @@ -7,7 +7,7 @@ use unicode_math_class::MathClass; use crate::diag::SourceResult; use crate::engine::Engine; use crate::foundations::{ - elem, Content, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, Synthesize, + Content, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, Synthesize, elem, }; use crate::introspection::{Count, Counter, CounterUpdate, Locatable}; use crate::layout::{ diff --git a/crates/typst-library/src/math/frac.rs b/crates/typst-library/src/math/frac.rs index dd5986b5f..b10b5b183 100644 --- a/crates/typst-library/src/math/frac.rs +++ b/crates/typst-library/src/math/frac.rs @@ -1,7 +1,7 @@ use typst_syntax::Spanned; use crate::diag::bail; -use crate::foundations::{elem, Content, Value}; +use crate::foundations::{Content, Value, elem}; use crate::math::Mathy; /// A mathematical fraction. diff --git a/crates/typst-library/src/math/lr.rs b/crates/typst-library/src/math/lr.rs index 5f5cb8616..19fe1efdc 100644 --- a/crates/typst-library/src/math/lr.rs +++ b/crates/typst-library/src/math/lr.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, func, Content, NativeElement, SymbolElem}; +use crate::foundations::{Content, NativeElement, SymbolElem, elem, func}; use crate::layout::{Length, Rel}; use crate::math::Mathy; diff --git a/crates/typst-library/src/math/matrix.rs b/crates/typst-library/src/math/matrix.rs index 2a51caefd..440f62aa1 100644 --- a/crates/typst-library/src/math/matrix.rs +++ b/crates/typst-library/src/math/matrix.rs @@ -1,12 +1,12 @@ -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use typst_syntax::Spanned; -use typst_utils::{default_math_class, Numeric}; +use typst_utils::{Numeric, default_math_class}; use unicode_math_class::MathClass; -use crate::diag::{bail, At, HintedStrResult, StrResult}; +use crate::diag::{At, HintedStrResult, StrResult, bail}; use crate::foundations::{ - array, cast, dict, elem, Array, Content, Dict, Fold, NoneValue, Resolve, Smart, - StyleChain, Symbol, Value, + Array, Content, Dict, Fold, NoneValue, Resolve, Smart, StyleChain, Symbol, Value, + array, cast, dict, elem, }; use crate::layout::{Abs, Em, HAlignment, Length, Rel}; use crate::math::Mathy; diff --git a/crates/typst-library/src/math/mod.rs b/crates/typst-library/src/math/mod.rs index 3d39e2fd2..c560b81ec 100644 --- a/crates/typst-library/src/math/mod.rs +++ b/crates/typst-library/src/math/mod.rs @@ -27,7 +27,7 @@ pub use self::underover::*; use typst_utils::singleton; use unicode_math_class::MathClass; -use crate::foundations::{elem, Content, Module, NativeElement, Scope}; +use crate::foundations::{Content, Module, NativeElement, Scope, elem}; use crate::layout::{Em, HElem}; use crate::text::TextElem; diff --git a/crates/typst-library/src/math/op.rs b/crates/typst-library/src/math/op.rs index 55696e534..06aa00673 100644 --- a/crates/typst-library/src/math/op.rs +++ b/crates/typst-library/src/math/op.rs @@ -1,8 +1,8 @@ use ecow::EcoString; -use crate::foundations::{elem, Content, NativeElement, Scope, SymbolElem}; +use crate::foundations::{Content, NativeElement, Scope, SymbolElem, elem}; use crate::layout::HElem; -use crate::math::{upright, Mathy, THIN}; +use crate::math::{Mathy, THIN, upright}; use crate::text::TextElem; /// A text operator in an equation. diff --git a/crates/typst-library/src/math/root.rs b/crates/typst-library/src/math/root.rs index ad111700b..52629803a 100644 --- a/crates/typst-library/src/math/root.rs +++ b/crates/typst-library/src/math/root.rs @@ -1,6 +1,6 @@ use typst_syntax::Span; -use crate::foundations::{elem, func, Content, NativeElement}; +use crate::foundations::{Content, NativeElement, elem, func}; use crate::math::Mathy; /// A square root. diff --git a/crates/typst-library/src/math/style.rs b/crates/typst-library/src/math/style.rs index 6a85fd123..f8ffb9b1f 100644 --- a/crates/typst-library/src/math/style.rs +++ b/crates/typst-library/src/math/style.rs @@ -1,6 +1,6 @@ use codex::styling::MathVariant; -use crate::foundations::{func, Cast, Content}; +use crate::foundations::{Cast, Content, func}; use crate::math::EquationElem; /// Bold font style in math. diff --git a/crates/typst-library/src/math/underover.rs b/crates/typst-library/src/math/underover.rs index 302c51afe..6f002d432 100644 --- a/crates/typst-library/src/math/underover.rs +++ b/crates/typst-library/src/math/underover.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; use crate::math::Mathy; /// A horizontal line under content. diff --git a/crates/typst-library/src/model/bibliography.rs b/crates/typst-library/src/model/bibliography.rs index ef7e69273..23e89f86b 100644 --- a/crates/typst-library/src/model/bibliography.rs +++ b/crates/typst-library/src/model/bibliography.rs @@ -6,34 +6,35 @@ use std::path::Path; use std::sync::{Arc, LazyLock}; use comemo::{Track, Tracked}; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; use hayagriva::archive::ArchivedStyle; use hayagriva::io::BibLaTeXError; use hayagriva::{ - citationberg, BibliographyDriver, BibliographyRequest, CitationItem, CitationRequest, - Library, SpecificLocator, + BibliographyDriver, BibliographyRequest, CitationItem, CitationRequest, Library, + SpecificLocator, citationberg, }; use indexmap::IndexMap; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use typst_syntax::{Span, Spanned, SyntaxMode}; use typst_utils::{ManuallyHash, PicoStr}; +use crate::World; use crate::diag::{ - bail, error, At, HintedStrResult, LoadError, LoadResult, LoadedWithin, ReportPos, - SourceResult, StrResult, + At, HintedStrResult, LoadError, LoadResult, LoadedWithin, ReportPos, SourceResult, + StrResult, bail, error, }; use crate::engine::{Engine, Sink}; use crate::foundations::{ - elem, Bytes, CastInfo, Content, Derived, FromValue, IntoValue, Label, NativeElement, + Bytes, CastInfo, Content, Derived, FromValue, IntoValue, Label, NativeElement, OneOrMultiple, Packed, Reflect, Scope, ShowSet, Smart, StyleChain, Styles, - Synthesize, Value, + Synthesize, Value, elem, }; use crate::introspection::{Introspector, Locatable, Location}; use crate::layout::{ BlockBody, BlockElem, Em, GridCell, GridChild, GridElem, GridItem, HElem, PadElem, Sizing, TrackSizings, }; -use crate::loading::{format_yaml_error, DataSource, Load, LoadSource, Loaded}; +use crate::loading::{DataSource, Load, LoadSource, Loaded, format_yaml_error}; use crate::model::{ CitationForm, CiteGroup, Destination, FootnoteElem, HeadingElem, LinkElem, Url, }; @@ -42,7 +43,6 @@ use crate::text::{ FontStyle, Lang, LocalName, Region, Smallcaps, SubElem, SuperElem, TextElem, WeightDelta, }; -use crate::World; /// A bibliography / reference listing. /// @@ -928,10 +928,11 @@ impl ElemRenderer<'_> { } if let Some(hayagriva::ElemMeta::Entry(i)) = elem.meta - && let Some(location) = (self.link)(i) { - let dest = Destination::Location(location); - content = content.linked(dest); - } + && let Some(location) = (self.link)(i) + { + let dest = Destination::Location(location); + content = content.linked(dest); + } Ok(content) } diff --git a/crates/typst-library/src/model/cite.rs b/crates/typst-library/src/model/cite.rs index b3ae3e522..f30e7a9c4 100644 --- a/crates/typst-library/src/model/cite.rs +++ b/crates/typst-library/src/model/cite.rs @@ -1,9 +1,9 @@ use typst_syntax::Spanned; -use crate::diag::{error, At, HintedString, SourceResult}; +use crate::diag::{At, HintedString, SourceResult, error}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, Cast, Content, Derived, Label, Packed, Smart, StyleChain, Synthesize, + Cast, Content, Derived, Label, Packed, Smart, StyleChain, Synthesize, cast, elem, }; use crate::introspection::Locatable; use crate::model::bibliography::Works; diff --git a/crates/typst-library/src/model/document.rs b/crates/typst-library/src/model/document.rs index 47e999735..6d668ac3f 100644 --- a/crates/typst-library/src/model/document.rs +++ b/crates/typst-library/src/model/document.rs @@ -1,10 +1,10 @@ use ecow::EcoString; -use crate::diag::{bail, HintedStrResult, SourceResult}; +use crate::diag::{HintedStrResult, SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, Args, Array, Construct, Content, Datetime, OneOrMultiple, Smart, - StyleChain, Styles, Value, + Args, Array, Construct, Content, Datetime, OneOrMultiple, Smart, StyleChain, Styles, + Value, cast, elem, }; /// The root element of a document and its metadata. diff --git a/crates/typst-library/src/model/emph.rs b/crates/typst-library/src/model/emph.rs index 6267736b3..b9eb9ebdd 100644 --- a/crates/typst-library/src/model/emph.rs +++ b/crates/typst-library/src/model/emph.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; /// Emphasizes content by toggling italics. /// diff --git a/crates/typst-library/src/model/enum.rs b/crates/typst-library/src/model/enum.rs index 93a2c1dc6..adb738879 100644 --- a/crates/typst-library/src/model/enum.rs +++ b/crates/typst-library/src/model/enum.rs @@ -3,7 +3,7 @@ use std::str::FromStr; use smallvec::SmallVec; use crate::diag::bail; -use crate::foundations::{cast, elem, scope, Array, Content, Packed, Smart, Styles}; +use crate::foundations::{Array, Content, Packed, Smart, Styles, cast, elem, scope}; use crate::layout::{Alignment, Em, HAlignment, Length, VAlignment}; use crate::model::{ListItemLike, ListLike, Numbering, NumberingPattern}; diff --git a/crates/typst-library/src/model/figure.rs b/crates/typst-library/src/model/figure.rs index ac3676eea..daab37e44 100644 --- a/crates/typst-library/src/model/figure.rs +++ b/crates/typst-library/src/model/figure.rs @@ -5,11 +5,11 @@ use std::str::FromStr; use ecow::EcoString; use typst_utils::NonZeroExt; -use crate::diag::{bail, SourceResult}; +use crate::diag::{SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, scope, select_where, Content, Element, NativeElement, Packed, Selector, - ShowSet, Smart, StyleChain, Styles, Synthesize, + Content, Element, NativeElement, Packed, Selector, ShowSet, Smart, StyleChain, + Styles, Synthesize, cast, elem, scope, select_where, }; use crate::introspection::{ Count, Counter, CounterKey, CounterUpdate, Locatable, Location, diff --git a/crates/typst-library/src/model/footnote.rs b/crates/typst-library/src/model/footnote.rs index b920a8ae4..51b9f25fd 100644 --- a/crates/typst-library/src/model/footnote.rs +++ b/crates/typst-library/src/model/footnote.rs @@ -3,11 +3,11 @@ use std::str::FromStr; use typst_utils::NonZeroExt; -use crate::diag::{bail, StrResult}; +use crate::diag::{StrResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, scope, Content, Label, NativeElement, Packed, ShowSet, Smart, StyleChain, - Styles, + Content, Label, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, cast, + elem, scope, }; use crate::introspection::{Count, CounterUpdate, Locatable, Location}; use crate::layout::{Abs, Em, Length, Ratio}; diff --git a/crates/typst-library/src/model/heading.rs b/crates/typst-library/src/model/heading.rs index 0f2a1d338..f5e7f4f37 100644 --- a/crates/typst-library/src/model/heading.rs +++ b/crates/typst-library/src/model/heading.rs @@ -5,7 +5,7 @@ use typst_utils::NonZeroExt; use crate::diag::SourceResult; use crate::engine::Engine; use crate::foundations::{ - elem, Content, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, Synthesize, + Content, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, Synthesize, elem, }; use crate::introspection::{Count, Counter, CounterUpdate, Locatable}; use crate::layout::{BlockElem, Em, Length}; diff --git a/crates/typst-library/src/model/link.rs b/crates/typst-library/src/model/link.rs index 7e8f58756..16e1cc5a9 100644 --- a/crates/typst-library/src/model/link.rs +++ b/crates/typst-library/src/model/link.rs @@ -1,11 +1,11 @@ use std::ops::Deref; use comemo::Tracked; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; -use crate::diag::{bail, StrResult}; +use crate::diag::{StrResult, bail}; use crate::foundations::{ - cast, elem, Content, Label, Packed, Repr, ShowSet, Smart, StyleChain, Styles, + Content, Label, Packed, Repr, ShowSet, Smart, StyleChain, Styles, cast, elem, }; use crate::introspection::{Introspector, Locatable, Location}; use crate::layout::Position; diff --git a/crates/typst-library/src/model/list.rs b/crates/typst-library/src/model/list.rs index 660716de7..5df37ad33 100644 --- a/crates/typst-library/src/model/list.rs +++ b/crates/typst-library/src/model/list.rs @@ -1,10 +1,10 @@ use comemo::Track; -use crate::diag::{bail, SourceResult}; +use crate::diag::{SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, scope, Array, Content, Context, Depth, Func, NativeElement, Packed, - Smart, StyleChain, Styles, Value, + Array, Content, Context, Depth, Func, NativeElement, Packed, Smart, StyleChain, + Styles, Value, cast, elem, scope, }; use crate::layout::{Em, Length}; use crate::text::TextElem; diff --git a/crates/typst-library/src/model/numbering.rs b/crates/typst-library/src/model/numbering.rs index 449dfdb33..a53954a7c 100644 --- a/crates/typst-library/src/model/numbering.rs +++ b/crates/typst-library/src/model/numbering.rs @@ -1,14 +1,14 @@ use std::str::FromStr; use chinese_number::{ - from_u64_to_chinese_ten_thousand as u64_to_chinese, ChineseCase, ChineseVariant, + ChineseCase, ChineseVariant, from_u64_to_chinese_ten_thousand as u64_to_chinese, }; use comemo::Tracked; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; use crate::diag::SourceResult; use crate::engine::Engine; -use crate::foundations::{cast, func, Context, Func, Str, Value}; +use crate::foundations::{Context, Func, Str, Value, cast, func}; /// Applies a numbering to a sequence of numbers. /// diff --git a/crates/typst-library/src/model/outline.rs b/crates/typst-library/src/model/outline.rs index 4bda02ba3..96c4eb2b4 100644 --- a/crates/typst-library/src/model/outline.rs +++ b/crates/typst-library/src/model/outline.rs @@ -6,12 +6,11 @@ use smallvec::SmallVec; use typst_syntax::Span; use typst_utils::{Get, NonZeroExt}; -use crate::diag::{bail, error, At, HintedStrResult, SourceResult, StrResult}; +use crate::diag::{At, HintedStrResult, SourceResult, StrResult, bail, error}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, func, scope, select_where, Args, Construct, Content, Context, Func, - LocatableSelector, NativeElement, Packed, Resolve, ShowSet, Smart, StyleChain, - Styles, + Args, Construct, Content, Context, Func, LocatableSelector, NativeElement, Packed, + Resolve, ShowSet, Smart, StyleChain, Styles, cast, elem, func, scope, select_where, }; use crate::introspection::{ Counter, CounterKey, Introspector, Locatable, Location, Locator, LocatorLink, diff --git a/crates/typst-library/src/model/par.rs b/crates/typst-library/src/model/par.rs index 8aceec2c7..372e63e00 100644 --- a/crates/typst-library/src/model/par.rs +++ b/crates/typst-library/src/model/par.rs @@ -1,10 +1,10 @@ use typst_utils::singleton; -use crate::diag::{bail, SourceResult}; +use crate::diag::{SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, dict, elem, scope, Args, Cast, Construct, Content, Dict, NativeElement, Packed, - Smart, Unlabellable, Value, + Args, Cast, Construct, Content, Dict, NativeElement, Packed, Smart, Unlabellable, + Value, cast, dict, elem, scope, }; use crate::introspection::{Count, CounterUpdate, Locatable}; use crate::layout::{Em, HAlignment, Length, OuterHAlignment}; diff --git a/crates/typst-library/src/model/quote.rs b/crates/typst-library/src/model/quote.rs index 5ce4a92f5..5ffa1fdc9 100644 --- a/crates/typst-library/src/model/quote.rs +++ b/crates/typst-library/src/model/quote.rs @@ -1,8 +1,8 @@ use typst_syntax::Span; use crate::foundations::{ - cast, elem, Content, Depth, Label, NativeElement, Packed, ShowSet, Smart, StyleChain, - Styles, + Content, Depth, Label, NativeElement, Packed, ShowSet, Smart, StyleChain, Styles, + cast, elem, }; use crate::introspection::Locatable; use crate::layout::{BlockElem, Em, PadElem}; diff --git a/crates/typst-library/src/model/reference.rs b/crates/typst-library/src/model/reference.rs index cf1b43da0..ff695182f 100644 --- a/crates/typst-library/src/model/reference.rs +++ b/crates/typst-library/src/model/reference.rs @@ -1,11 +1,11 @@ use comemo::Track; use ecow::eco_format; -use crate::diag::{bail, At, Hint, SourceResult}; +use crate::diag::{At, Hint, SourceResult, bail}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, Cast, Content, Context, Func, IntoValue, Label, NativeElement, Packed, - Repr, Smart, StyleChain, Synthesize, TargetElem, + Cast, Content, Context, Func, IntoValue, Label, NativeElement, Packed, Repr, Smart, + StyleChain, Synthesize, TargetElem, cast, elem, }; use crate::introspection::{Counter, CounterKey, Locatable}; use crate::math::EquationElem; @@ -211,10 +211,11 @@ impl Synthesize for Packed { elem.element = Some(None); if !BibliographyElem::has(engine, elem.target) - && let Ok(found) = engine.introspector.query_label(elem.target).cloned() { - elem.element = Some(Some(found)); - return Ok(()); - } + && let Ok(found) = engine.introspector.query_label(elem.target).cloned() + { + elem.element = Some(Some(found)); + return Ok(()); + } Ok(()) } diff --git a/crates/typst-library/src/model/strong.rs b/crates/typst-library/src/model/strong.rs index 7751c95bc..a1cfb36ab 100644 --- a/crates/typst-library/src/model/strong.rs +++ b/crates/typst-library/src/model/strong.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; /// Strongly emphasizes content by increasing the font weight. /// diff --git a/crates/typst-library/src/model/table.rs b/crates/typst-library/src/model/table.rs index e46efc818..412ca4229 100644 --- a/crates/typst-library/src/model/table.rs +++ b/crates/typst-library/src/model/table.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use typst_utils::NonZeroExt; -use crate::diag::{bail, HintedStrResult, HintedString}; -use crate::foundations::{cast, elem, scope, Content, Packed, Smart}; +use crate::diag::{HintedStrResult, HintedString, bail}; +use crate::foundations::{Content, Packed, Smart, cast, elem, scope}; use crate::layout::{ Abs, Alignment, Celled, GridCell, GridFooter, GridHLine, GridHeader, GridVLine, Length, OuterHAlignment, OuterVAlignment, Rel, Sides, TrackSizings, diff --git a/crates/typst-library/src/model/terms.rs b/crates/typst-library/src/model/terms.rs index 71b1bad6d..47939b9b4 100644 --- a/crates/typst-library/src/model/terms.rs +++ b/crates/typst-library/src/model/terms.rs @@ -1,6 +1,6 @@ use crate::diag::bail; use crate::foundations::{ - cast, elem, scope, Array, Content, NativeElement, Packed, Smart, Styles, + Array, Content, NativeElement, Packed, Smart, Styles, cast, elem, scope, }; use crate::layout::{Em, HElem, Length}; use crate::model::{ListItemLike, ListLike}; diff --git a/crates/typst-library/src/pdf/embed.rs b/crates/typst-library/src/pdf/embed.rs index 3aba85623..2b93a591a 100644 --- a/crates/typst-library/src/pdf/embed.rs +++ b/crates/typst-library/src/pdf/embed.rs @@ -1,10 +1,10 @@ use ecow::EcoString; use typst_syntax::Spanned; -use crate::diag::At; -use crate::foundations::{elem, Bytes, Cast, Derived}; -use crate::introspection::Locatable; use crate::World; +use crate::diag::At; +use crate::foundations::{Bytes, Cast, Derived, elem}; +use crate::introspection::Locatable; /// A file that will be embedded into the output PDF. /// diff --git a/crates/typst-library/src/routines.rs b/crates/typst-library/src/routines.rs index 01964800f..6fa7d69c8 100644 --- a/crates/typst-library/src/routines.rs +++ b/crates/typst-library/src/routines.rs @@ -5,6 +5,7 @@ use comemo::{Tracked, TrackedMut}; use typst_syntax::{Span, SyntaxMode}; use typst_utils::LazyHash; +use crate::World; use crate::diag::SourceResult; use crate::engine::{Engine, Route, Sink, Traced}; use crate::foundations::{ @@ -14,7 +15,6 @@ use crate::foundations::{ use crate::introspection::{Introspector, Locator, SplitLocator}; use crate::layout::{Frame, Region}; use crate::model::DocumentInfo; -use crate::World; /// Defines the `Routines` struct. macro_rules! routines { diff --git a/crates/typst-library/src/text/case.rs b/crates/typst-library/src/text/case.rs index 3b2ae450a..6451df766 100644 --- a/crates/typst-library/src/text/case.rs +++ b/crates/typst-library/src/text/case.rs @@ -1,4 +1,4 @@ -use crate::foundations::{cast, func, Cast, Content, Str}; +use crate::foundations::{Cast, Content, Str, cast, func}; use crate::text::TextElem; /// Converts a string or content to lowercase. diff --git a/crates/typst-library/src/text/deco.rs b/crates/typst-library/src/text/deco.rs index f7d5c33be..d7383f0f1 100644 --- a/crates/typst-library/src/text/deco.rs +++ b/crates/typst-library/src/text/deco.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content, Smart}; +use crate::foundations::{Content, Smart, elem}; use crate::layout::{Abs, Corners, Length, Rel, Sides}; use crate::text::{BottomEdge, BottomEdgeMetric, TopEdge, TopEdgeMetric}; use crate::visualize::{Color, FixedStroke, Paint, Stroke}; diff --git a/crates/typst-library/src/text/font/book.rs b/crates/typst-library/src/text/font/book.rs index 374b83908..db100d4f7 100644 --- a/crates/typst-library/src/text/font/book.rs +++ b/crates/typst-library/src/text/font/book.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use std::fmt::{self, Debug, Formatter}; use serde::{Deserialize, Serialize}; -use ttf_parser::{name_id, PlatformId, Tag}; +use ttf_parser::{PlatformId, Tag, name_id}; use unicode_segmentation::UnicodeSegmentation; use super::exceptions::find_exception; @@ -284,9 +284,10 @@ impl FontInfo { .raw_face() .table(Tag::from_bytes(b"OS/2")) .and_then(|os2| os2.get(32..45)) - && matches!(panose, [2, 2..=10, ..]) { - flags.insert(FontFlags::SERIF); - } + && matches!(panose, [2, 2..=10, ..]) + { + flags.insert(FontFlags::SERIF); + } Some(FontInfo { family, @@ -335,11 +336,7 @@ fn decode_mac_roman(coded: &[u8]) -> String { ]; fn char_from_mac_roman(code: u8) -> char { - if code < 128 { - code as char - } else { - TABLE[(code - 128) as usize] - } + if code < 128 { code as char } else { TABLE[(code - 128) as usize] } } coded.iter().copied().map(char_from_mac_roman).collect() @@ -396,9 +393,10 @@ fn typographic_family(mut family: &str) -> &str { // Also allow an extra modifier, but apply it only if it is separated it // from the text before it (to prevent false positives). if let Some(t) = MODIFIERS.iter().find_map(|s| t.strip_suffix(s)) - && let Some(stripped) = t.strip_suffix(SEPARATORS) { - trimmed = stripped; - } + && let Some(stripped) = t.strip_suffix(SEPARATORS) + { + trimmed = stripped; + } } // Apply style suffix trimming. diff --git a/crates/typst-library/src/text/font/variant.rs b/crates/typst-library/src/text/font/variant.rs index c7a00fb34..e2e6860c6 100644 --- a/crates/typst-library/src/text/font/variant.rs +++ b/crates/typst-library/src/text/font/variant.rs @@ -3,7 +3,7 @@ use std::fmt::{self, Debug, Formatter}; use ecow::EcoString; use serde::{Deserialize, Serialize}; -use crate::foundations::{cast, Cast, IntoValue, Repr}; +use crate::foundations::{Cast, IntoValue, Repr, cast}; use crate::layout::Ratio; /// Properties that distinguish a font from other fonts in the same family. diff --git a/crates/typst-library/src/text/item.rs b/crates/typst-library/src/text/item.rs index 518b082b9..2668aa54e 100644 --- a/crates/typst-library/src/text/item.rs +++ b/crates/typst-library/src/text/item.rs @@ -5,7 +5,7 @@ use ecow::EcoString; use typst_syntax::Span; use crate::layout::{Abs, Em}; -use crate::text::{is_default_ignorable, Font, Lang, Region}; +use crate::text::{Font, Lang, Region, is_default_ignorable}; use crate::visualize::{FixedStroke, Paint}; /// A run of shaped text. diff --git a/crates/typst-library/src/text/lang.rs b/crates/typst-library/src/text/lang.rs index d396eef8b..ed21ade17 100644 --- a/crates/typst-library/src/text/lang.rs +++ b/crates/typst-library/src/text/lang.rs @@ -1,10 +1,10 @@ use std::collections::HashMap; use std::str::FromStr; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use crate::diag::Hint; -use crate::foundations::{cast, StyleChain}; +use crate::foundations::{StyleChain, cast}; use crate::layout::Dir; use crate::text::TextElem; diff --git a/crates/typst-library/src/text/linebreak.rs b/crates/typst-library/src/text/linebreak.rs index 0519e1c4a..f4aeac7bb 100644 --- a/crates/typst-library/src/text/linebreak.rs +++ b/crates/typst-library/src/text/linebreak.rs @@ -1,6 +1,6 @@ use typst_utils::singleton; -use crate::foundations::{elem, Content, NativeElement}; +use crate::foundations::{Content, NativeElement, elem}; /// Inserts a line break. /// diff --git a/crates/typst-library/src/text/lorem.rs b/crates/typst-library/src/text/lorem.rs index 5d01a550d..8fc5c9cc0 100644 --- a/crates/typst-library/src/text/lorem.rs +++ b/crates/typst-library/src/text/lorem.rs @@ -1,4 +1,4 @@ -use crate::foundations::{func, Str}; +use crate::foundations::{Str, func}; /// Creates blind text. /// diff --git a/crates/typst-library/src/text/mod.rs b/crates/typst-library/src/text/mod.rs index 5f2330cbd..f2025f5b8 100644 --- a/crates/typst-library/src/text/mod.rs +++ b/crates/typst-library/src/text/mod.rs @@ -33,7 +33,7 @@ use std::hash::Hash; use std::str::FromStr; use std::sync::LazyLock; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use icu_properties::sets::CodePointSetData; use icu_provider::AsDeserializingBufferProvider; use icu_provider_blob::BlobDataProvider; @@ -43,17 +43,17 @@ use ttf_parser::Tag; use typst_syntax::Spanned; use typst_utils::singleton; -use crate::diag::{bail, warning, HintedStrResult, SourceResult, StrResult}; +use crate::World; +use crate::diag::{HintedStrResult, SourceResult, StrResult, bail, warning}; use crate::engine::Engine; use crate::foundations::{ - cast, dict, elem, Args, Array, Cast, Construct, Content, Dict, Fold, IntoValue, - NativeElement, Never, NoneValue, Packed, PlainText, Regex, Repr, Resolve, Scope, Set, - Smart, StyleChain, + Args, Array, Cast, Construct, Content, Dict, Fold, IntoValue, NativeElement, Never, + NoneValue, Packed, PlainText, Regex, Repr, Resolve, Scope, Set, Smart, StyleChain, + cast, dict, elem, }; use crate::layout::{Abs, Axis, Dir, Em, Length, Ratio, Rel}; use crate::math::{EquationElem, MathSize}; use crate::visualize::{Color, Paint, RelativeTo, Stroke}; -use crate::World; /// Hook up all `text` definitions. pub(super) fn define(global: &mut Scope) { diff --git a/crates/typst-library/src/text/raw.rs b/crates/typst-library/src/text/raw.rs index 1677d3d07..3d74ed0a6 100644 --- a/crates/typst-library/src/text/raw.rs +++ b/crates/typst-library/src/text/raw.rs @@ -6,25 +6,25 @@ use comemo::Tracked; use ecow::{EcoString, EcoVec}; use syntect::highlighting::{self as synt}; use syntect::parsing::{ParseSyntaxError, SyntaxDefinition, SyntaxSet, SyntaxSetBuilder}; -use typst_syntax::{split_newlines, LinkedNode, Span, Spanned}; +use typst_syntax::{LinkedNode, Span, Spanned, split_newlines}; use typst_utils::ManuallyHash; use unicode_segmentation::UnicodeSegmentation; use super::Lang; +use crate::World; use crate::diag::{ LineCol, LoadError, LoadResult, LoadedWithin, ReportPos, SourceResult, }; use crate::engine::Engine; use crate::foundations::{ - cast, elem, scope, Bytes, Content, Derived, OneOrMultiple, Packed, PlainText, - ShowSet, Smart, StyleChain, Styles, Synthesize, + Bytes, Content, Derived, OneOrMultiple, Packed, PlainText, ShowSet, Smart, + StyleChain, Styles, Synthesize, cast, elem, scope, }; use crate::layout::{Em, HAlignment}; use crate::loading::{DataSource, Load}; use crate::model::{Figurable, ParElem}; use crate::text::{FontFamily, FontList, LocalName, TextElem, TextSize}; use crate::visualize::Color; -use crate::World; /// Raw text with optional syntax highlighting. /// @@ -751,9 +751,10 @@ fn preprocess( span: Span, ) -> EcoVec<(EcoString, Span)> { if let RawContent::Lines(lines) = text - && lines.iter().all(|(s, _)| !s.contains('\t')) { - return lines.clone(); - } + && lines.iter().all(|(s, _)| !s.contains('\t')) + { + return lines.clone(); + } let mut text = text.get(); if text.contains('\t') { diff --git a/crates/typst-library/src/text/shift.rs b/crates/typst-library/src/text/shift.rs index 87ccae635..eb4c89e18 100644 --- a/crates/typst-library/src/text/shift.rs +++ b/crates/typst-library/src/text/shift.rs @@ -1,6 +1,6 @@ use ttf_parser::Tag; -use crate::foundations::{elem, Content, Smart}; +use crate::foundations::{Content, Smart, elem}; use crate::layout::{Em, Length}; use crate::text::{FontMetrics, ScriptMetrics, TextSize}; diff --git a/crates/typst-library/src/text/smallcaps.rs b/crates/typst-library/src/text/smallcaps.rs index 199222fed..9c4969eea 100644 --- a/crates/typst-library/src/text/smallcaps.rs +++ b/crates/typst-library/src/text/smallcaps.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Content}; +use crate::foundations::{Content, elem}; /// Displays text in small capitals. /// diff --git a/crates/typst-library/src/text/smartquote.rs b/crates/typst-library/src/text/smartquote.rs index 375b1cf09..d39703f6c 100644 --- a/crates/typst-library/src/text/smartquote.rs +++ b/crates/typst-library/src/text/smartquote.rs @@ -2,10 +2,10 @@ use ecow::EcoString; use typst_syntax::is_newline; use unicode_segmentation::UnicodeSegmentation; -use crate::diag::{bail, HintedStrResult, StrResult}; +use crate::diag::{HintedStrResult, StrResult, bail}; use crate::foundations::{ - array, cast, dict, elem, Array, Dict, FromValue, Packed, PlainText, Smart, Str, - StyleChain, + Array, Dict, FromValue, Packed, PlainText, Smart, Str, StyleChain, array, cast, dict, + elem, }; use crate::layout::Dir; use crate::text::{Lang, Region, TextElem}; @@ -297,20 +297,12 @@ impl<'s> SmartQuotes<'s> { /// The opening quote. pub fn open(&self, double: bool) -> &'s str { - if double { - self.double_open - } else { - self.single_open - } + if double { self.double_open } else { self.single_open } } /// The closing quote. pub fn close(&self, double: bool) -> &'s str { - if double { - self.double_close - } else { - self.single_close - } + if double { self.double_close } else { self.single_close } } } diff --git a/crates/typst-library/src/text/space.rs b/crates/typst-library/src/text/space.rs index 38a554823..143046fac 100644 --- a/crates/typst-library/src/text/space.rs +++ b/crates/typst-library/src/text/space.rs @@ -2,7 +2,7 @@ use ecow::EcoString; use typst_utils::singleton; use crate::foundations::{ - elem, Content, NativeElement, Packed, PlainText, Repr, Unlabellable, + Content, NativeElement, Packed, PlainText, Repr, Unlabellable, elem, }; /// A text space. diff --git a/crates/typst-library/src/visualize/color.rs b/crates/typst-library/src/visualize/color.rs index 9c8eacaf5..e57e74734 100644 --- a/crates/typst-library/src/visualize/color.rs +++ b/crates/typst-library/src/visualize/color.rs @@ -3,7 +3,7 @@ use std::hash::{Hash, Hasher}; use std::str::FromStr; use std::sync::LazyLock; -use ecow::{eco_format, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format}; use palette::encoding::{self, Linear}; use palette::{ Alpha, Darken, Desaturate, FromColor, Lighten, OklabHue, RgbHue, Saturate, ShiftHue, @@ -11,10 +11,10 @@ use palette::{ use qcms::Profile; use typst_syntax::{Span, Spanned}; -use crate::diag::{bail, At, SourceResult, StrResult}; +use crate::diag::{At, SourceResult, StrResult, bail}; use crate::foundations::{ - array, cast, func, repr, scope, ty, Args, Array, IntoValue, Module, Repr, Scope, Str, - Value, + Args, Array, IntoValue, Module, Repr, Scope, Str, Value, array, cast, func, repr, + scope, ty, }; use crate::layout::{Angle, Ratio}; @@ -1124,14 +1124,15 @@ impl Color { // Ensure that the hue circle is traversed in the short direction. if let Some(index) = space.hue_index() - && (c0[index] - c1[index]).abs() > 180.0 { - let (h0, h1) = if c0[index] < c1[index] { - (c0[index] + 360.0, c1[index]) - } else { - (c0[index], c1[index] + 360.0) - }; - m[index] = (w0 * h0 + w1 * h1) / (w0 + w1); - } + && (c0[index] - c1[index]).abs() > 180.0 + { + let (h0, h1) = if c0[index] < c1[index] { + (c0[index] + 360.0, c1[index]) + } else { + (c0[index], c1[index] + 360.0) + }; + m[index] = (w0 * h0 + w1 * h1) / (w0 + w1); + } m } else { diff --git a/crates/typst-library/src/visualize/curve.rs b/crates/typst-library/src/visualize/curve.rs index 15ae48c61..4bc5b45fb 100644 --- a/crates/typst-library/src/visualize/curve.rs +++ b/crates/typst-library/src/visualize/curve.rs @@ -1,9 +1,9 @@ use kurbo::ParamCurveExtrema; -use typst_macros::{scope, Cast}; +use typst_macros::{Cast, scope}; use typst_utils::Numeric; -use crate::diag::{bail, HintedStrResult, HintedString}; -use crate::foundations::{cast, elem, Content, Packed, Smart}; +use crate::diag::{HintedStrResult, HintedString, bail}; +use crate::foundations::{Content, Packed, Smart, cast, elem}; use crate::layout::{Abs, Axes, Length, Point, Rel, Size}; use crate::visualize::{FillRule, Paint, Stroke}; diff --git a/crates/typst-library/src/visualize/gradient.rs b/crates/typst-library/src/visualize/gradient.rs index 4917da68d..cb2ade2eb 100644 --- a/crates/typst-library/src/visualize/gradient.rs +++ b/crates/typst-library/src/visualize/gradient.rs @@ -7,9 +7,9 @@ use ecow::EcoString; use kurbo::Vec2; use typst_syntax::{Span, Spanned}; -use crate::diag::{bail, SourceResult}; +use crate::diag::{SourceResult, bail}; use crate::foundations::{ - array, cast, func, scope, ty, Args, Array, Cast, Func, IntoValue, Repr, Smart, + Args, Array, Cast, Func, IntoValue, Repr, Smart, array, cast, func, scope, ty, }; use crate::layout::{Angle, Axes, Dir, Quadrant, Ratio}; use crate::visualize::{Color, ColorSpace, WeightedColor}; @@ -893,11 +893,7 @@ impl Gradient { /// the special case of `auto`. pub fn unwrap_relative(&self, on_text: bool) -> RelativeTo { self.relative().unwrap_or_else(|| { - if on_text { - RelativeTo::Parent - } else { - RelativeTo::Self_ - } + if on_text { RelativeTo::Parent } else { RelativeTo::Self_ } }) } diff --git a/crates/typst-library/src/visualize/image/mod.rs b/crates/typst-library/src/visualize/image/mod.rs index f1fa6381b..d037145e7 100644 --- a/crates/typst-library/src/visualize/image/mod.rs +++ b/crates/typst-library/src/visualize/image/mod.rs @@ -16,16 +16,16 @@ use ecow::EcoString; use typst_syntax::{Span, Spanned}; use typst_utils::LazyHash; -use crate::diag::{warning, At, LoadedWithin, SourceResult, StrResult}; +use crate::diag::{At, LoadedWithin, SourceResult, StrResult, warning}; use crate::engine::Engine; use crate::foundations::{ - cast, elem, func, scope, Bytes, Cast, Content, Derived, NativeElement, Packed, Smart, - StyleChain, + Bytes, Cast, Content, Derived, NativeElement, Packed, Smart, StyleChain, cast, elem, + func, scope, }; use crate::layout::{Length, Rel, Sizing}; use crate::loading::{DataSource, Load, LoadSource, Loaded, Readable}; use crate::model::Figurable; -use crate::text::{families, LocalName}; +use crate::text::{LocalName, families}; /// A raster or vector graphic. /// diff --git a/crates/typst-library/src/visualize/image/raster.rs b/crates/typst-library/src/visualize/image/raster.rs index 54f832bae..63bbf0faa 100644 --- a/crates/typst-library/src/visualize/image/raster.rs +++ b/crates/typst-library/src/visualize/image/raster.rs @@ -3,15 +3,15 @@ use std::hash::{Hash, Hasher}; use std::io; use std::sync::Arc; -use crate::diag::{bail, StrResult}; -use crate::foundations::{cast, dict, Bytes, Cast, Dict, Smart, Value}; -use ecow::{eco_format, EcoString}; +use crate::diag::{StrResult, bail}; +use crate::foundations::{Bytes, Cast, Dict, Smart, Value, cast, dict}; +use ecow::{EcoString, eco_format}; use image::codecs::gif::GifDecoder; use image::codecs::jpeg::JpegDecoder; use image::codecs::png::PngDecoder; use image::codecs::webp::WebPDecoder; use image::{ - guess_format, DynamicImage, ImageBuffer, ImageDecoder, ImageResult, Limits, Pixel, + DynamicImage, ImageBuffer, ImageDecoder, ImageResult, Limits, Pixel, guess_format, }; /// A decoded raster image. diff --git a/crates/typst-library/src/visualize/image/svg.rs b/crates/typst-library/src/visualize/image/svg.rs index 1a3f6d474..11253c85a 100644 --- a/crates/typst-library/src/visualize/image/svg.rs +++ b/crates/typst-library/src/visualize/image/svg.rs @@ -5,13 +5,13 @@ use std::sync::{Arc, Mutex}; use comemo::Tracked; use siphasher::sip128::{Hasher128, SipHasher13}; -use crate::diag::{format_xml_like_error, LoadError, LoadResult, ReportPos}; +use crate::World; +use crate::diag::{LoadError, LoadResult, ReportPos, format_xml_like_error}; use crate::foundations::Bytes; use crate::layout::Axes; use crate::text::{ Font, FontBook, FontFlags, FontStretch, FontStyle, FontVariant, FontWeight, }; -use crate::World; /// A decoded SVG. #[derive(Clone, Hash)] diff --git a/crates/typst-library/src/visualize/paint.rs b/crates/typst-library/src/visualize/paint.rs index a618e5154..5769e3aa6 100644 --- a/crates/typst-library/src/visualize/paint.rs +++ b/crates/typst-library/src/visualize/paint.rs @@ -2,7 +2,7 @@ use std::fmt::{self, Debug, Formatter}; use ecow::EcoString; -use crate::foundations::{cast, Repr, Smart}; +use crate::foundations::{Repr, Smart, cast}; use crate::visualize::{Color, Gradient, RelativeTo, Tiling}; /// How a fill or stroke should be painted. diff --git a/crates/typst-library/src/visualize/path.rs b/crates/typst-library/src/visualize/path.rs index bd8aea02d..46ea7ec32 100644 --- a/crates/typst-library/src/visualize/path.rs +++ b/crates/typst-library/src/visualize/path.rs @@ -1,6 +1,6 @@ use self::PathVertex::{AllControlPoints, MirroredControlPoint, Vertex}; use crate::diag::bail; -use crate::foundations::{array, cast, elem, Array, Reflect, Smart}; +use crate::foundations::{Array, Reflect, Smart, array, cast, elem}; use crate::layout::{Axes, Length, Rel}; use crate::visualize::{FillRule, Paint, Stroke}; diff --git a/crates/typst-library/src/visualize/polygon.rs b/crates/typst-library/src/visualize/polygon.rs index db75a2670..d9b88f345 100644 --- a/crates/typst-library/src/visualize/polygon.rs +++ b/crates/typst-library/src/visualize/polygon.rs @@ -2,7 +2,7 @@ use std::f64::consts::PI; use typst_syntax::Span; -use crate::foundations::{elem, func, scope, Content, NativeElement, Smart}; +use crate::foundations::{Content, NativeElement, Smart, elem, func, scope}; use crate::layout::{Axes, Em, Length, Rel}; use crate::visualize::{FillRule, Paint, Stroke}; diff --git a/crates/typst-library/src/visualize/shape.rs b/crates/typst-library/src/visualize/shape.rs index fc7b8748e..d4382e6f0 100644 --- a/crates/typst-library/src/visualize/shape.rs +++ b/crates/typst-library/src/visualize/shape.rs @@ -1,4 +1,4 @@ -use crate::foundations::{elem, Cast, Content, Smart}; +use crate::foundations::{Cast, Content, Smart, elem}; use crate::layout::{Abs, Corners, Length, Point, Rel, Sides, Size, Sizing}; use crate::visualize::{Curve, FixedStroke, Paint, Stroke}; diff --git a/crates/typst-library/src/visualize/stroke.rs b/crates/typst-library/src/visualize/stroke.rs index a0830cf19..ca3d50f64 100644 --- a/crates/typst-library/src/visualize/stroke.rs +++ b/crates/typst-library/src/visualize/stroke.rs @@ -3,8 +3,8 @@ use typst_utils::{Numeric, Scalar}; use crate::diag::{HintedStrResult, SourceResult}; use crate::foundations::{ - cast, dict, func, scope, ty, Args, Cast, Dict, Fold, FromValue, NoneValue, Repr, - Resolve, Smart, StyleChain, Value, + Args, Cast, Dict, Fold, FromValue, NoneValue, Repr, Resolve, Smart, StyleChain, + Value, cast, dict, func, scope, ty, }; use crate::layout::{Abs, Length}; use crate::visualize::{Color, Gradient, Paint, Tiling}; diff --git a/crates/typst-library/src/visualize/tiling.rs b/crates/typst-library/src/visualize/tiling.rs index 98a71f927..dc4cf5859 100644 --- a/crates/typst-library/src/visualize/tiling.rs +++ b/crates/typst-library/src/visualize/tiling.rs @@ -1,17 +1,17 @@ use std::hash::Hash; use std::sync::Arc; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_syntax::{Span, Spanned}; use typst_utils::{LazyHash, Numeric}; -use crate::diag::{bail, SourceResult}; +use crate::World; +use crate::diag::{SourceResult, bail}; use crate::engine::Engine; -use crate::foundations::{func, repr, scope, ty, Content, Smart, StyleChain}; +use crate::foundations::{Content, Smart, StyleChain, func, repr, scope, ty}; use crate::introspection::Locator; use crate::layout::{Abs, Axes, Frame, Length, Region, Size}; use crate::visualize::RelativeTo; -use crate::World; /// A repeating tiling fill. /// @@ -259,11 +259,7 @@ impl Tiling { /// Returns the relative placement of the tiling. pub fn unwrap_relative(&self, on_text: bool) -> RelativeTo { self.0.relative.unwrap_or_else(|| { - if on_text { - RelativeTo::Parent - } else { - RelativeTo::Self_ - } + if on_text { RelativeTo::Parent } else { RelativeTo::Self_ } }) } } diff --git a/crates/typst-macros/src/elem.rs b/crates/typst-macros/src/elem.rs index e1c901d8a..bc3def45f 100644 --- a/crates/typst-macros/src/elem.rs +++ b/crates/typst-macros/src/elem.rs @@ -6,8 +6,8 @@ use syn::punctuated::Punctuated; use syn::{Ident, Result, Token}; use crate::util::{ - determine_name_and_title, documentation, foundations, has_attr, kw, parse_attr, - parse_flag, parse_string, parse_string_array, validate_attrs, BlockWithReturn, + BlockWithReturn, determine_name_and_title, documentation, foundations, has_attr, kw, + parse_attr, parse_flag, parse_string, parse_string_array, validate_attrs, }; /// Expand the `#[elem]` macro. diff --git a/crates/typst-macros/src/func.rs b/crates/typst-macros/src/func.rs index e953dc374..79bb7f58a 100644 --- a/crates/typst-macros/src/func.rs +++ b/crates/typst-macros/src/func.rs @@ -2,7 +2,7 @@ use heck::ToKebabCase; use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; -use syn::{parse_quote, Ident, Result}; +use syn::{Ident, Result, parse_quote}; use crate::util::{ determine_name_and_title, documentation, foundations, has_attr, kw, parse_attr, diff --git a/crates/typst-macros/src/scope.rs b/crates/typst-macros/src/scope.rs index 2eac76b53..4df4f2487 100644 --- a/crates/typst-macros/src/scope.rs +++ b/crates/typst-macros/src/scope.rs @@ -1,9 +1,9 @@ use heck::ToKebabCase; use proc_macro2::TokenStream; use quote::quote; -use syn::{parse_quote, Result}; +use syn::{Result, parse_quote}; -use crate::util::{foundations, BareType}; +use crate::util::{BareType, foundations}; /// Expand the `#[scope]` macro. pub fn scope(_: TokenStream, item: syn::Item) -> Result { @@ -16,10 +16,11 @@ pub fn scope(_: TokenStream, item: syn::Item) -> Result { let mut primitive_ident_ext = None; if let syn::Type::Path(syn::TypePath { path, .. }) = self_ty.as_ref() && let Some(ident) = path.get_ident() - && is_primitive(ident) { - let ident_ext = quote::format_ident!("{ident}Ext"); - primitive_ident_ext = Some(ident_ext); - } + && is_primitive(ident) + { + let ident_ext = quote::format_ident!("{ident}Ext"); + primitive_ident_ext = Some(ident_ext); + } let self_ty_expr = match &primitive_ident_ext { None => quote! { #self_ty }, diff --git a/crates/typst-macros/src/time.rs b/crates/typst-macros/src/time.rs index 94fa4e5be..abd548dd9 100644 --- a/crates/typst-macros/src/time.rs +++ b/crates/typst-macros/src/time.rs @@ -1,7 +1,7 @@ use proc_macro2::TokenStream; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::parse::{Parse, ParseStream}; -use syn::{parse_quote, Result}; +use syn::{Result, parse_quote}; use crate::util::{kw, parse_key_value, parse_string}; diff --git a/crates/typst-macros/src/ty.rs b/crates/typst-macros/src/ty.rs index 662849044..fd0aec7f1 100644 --- a/crates/typst-macros/src/ty.rs +++ b/crates/typst-macros/src/ty.rs @@ -4,8 +4,8 @@ use syn::parse::{Parse, ParseStream}; use syn::{Attribute, Ident, Result}; use crate::util::{ - determine_name_and_title, documentation, foundations, kw, parse_flag, parse_string, - parse_string_array, BareType, + BareType, determine_name_and_title, documentation, foundations, kw, parse_flag, + parse_string, parse_string_array, }; /// Expand the `#[ty]` macro. diff --git a/crates/typst-macros/src/util.rs b/crates/typst-macros/src/util.rs index 87e398c97..108ee3828 100644 --- a/crates/typst-macros/src/util.rs +++ b/crates/typst-macros/src/util.rs @@ -1,6 +1,6 @@ use heck::{ToKebabCase, ToTitleCase}; use proc_macro2::TokenStream; -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::parse::{Parse, ParseStream}; use syn::token::Token; use syn::{Attribute, Ident, Result, Token}; @@ -29,13 +29,14 @@ pub fn documentation(attrs: &[syn::Attribute]) -> String { for attr in attrs { if let syn::Meta::NameValue(meta) = &attr.meta && meta.path.is_ident("doc") - && let syn::Expr::Lit(lit) = &meta.value - && let syn::Lit::Str(string) = &lit.lit { - let full = string.value(); - let line = full.strip_prefix(' ').unwrap_or(&full); - doc.push_str(line); - doc.push('\n'); - } + && let syn::Expr::Lit(lit) = &meta.value + && let syn::Lit::Str(string) = &lit.lit + { + let full = string.value(); + let line = full.strip_prefix(' ').unwrap_or(&full); + doc.push_str(line); + doc.push('\n'); + } } doc.trim().into() diff --git a/crates/typst-pdf/src/convert.rs b/crates/typst-pdf/src/convert.rs index 9e2aa87b7..058658156 100644 --- a/crates/typst-pdf/src/convert.rs +++ b/crates/typst-pdf/src/convert.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::num::NonZeroU64; -use ecow::{eco_format, EcoVec}; +use ecow::{EcoVec, eco_format}; use krilla::annotation::Annotation; use krilla::configure::{Configuration, ValidationError, Validator}; use krilla::destination::{NamedDestination, XyzDestination}; @@ -12,7 +12,7 @@ use krilla::page::{PageLabel, PageSettings}; use krilla::surface::Surface; use krilla::{Document, SerializeSettings}; use krilla_svg::render_svg_glyph; -use typst_library::diag::{bail, error, SourceDiagnostic, SourceResult}; +use typst_library::diag::{SourceDiagnostic, SourceResult, bail, error}; use typst_library::foundations::{NativeElement, Repr}; use typst_library::introspection::Location; use typst_library::layout::{ @@ -23,6 +23,7 @@ use typst_library::text::{Font, Lang}; use typst_library::visualize::{Geometry, Paint}; use typst_syntax::Span; +use crate::PdfOptions; use crate::embed::embed_files; use crate::image::handle_image; use crate::link::handle_link; @@ -31,8 +32,7 @@ use crate::outline::build_outline; use crate::page::PageLabelExt; use crate::shape::handle_shape; use crate::text::handle_text; -use crate::util::{convert_path, display_font, AbsExt, TransformExt}; -use crate::PdfOptions; +use crate::util::{AbsExt, TransformExt, convert_path, display_font}; #[typst_macros::time(name = "convert document")] pub fn convert( diff --git a/crates/typst-pdf/src/embed.rs b/crates/typst-pdf/src/embed.rs index c62178cf2..b50f4a56d 100644 --- a/crates/typst-pdf/src/embed.rs +++ b/crates/typst-pdf/src/embed.rs @@ -1,8 +1,8 @@ use std::sync::Arc; -use krilla::embed::{AssociationKind, EmbeddedFile}; use krilla::Document; -use typst_library::diag::{bail, SourceResult}; +use krilla::embed::{AssociationKind, EmbeddedFile}; +use typst_library::diag::{SourceResult, bail}; use typst_library::foundations::{NativeElement, StyleChain}; use typst_library::layout::PagedDocument; use typst_library::pdf::{EmbedElem, EmbeddedFileRelationship}; diff --git a/crates/typst-pdf/src/image.rs b/crates/typst-pdf/src/image.rs index 93bdb1950..39a6e602c 100644 --- a/crates/typst-pdf/src/image.rs +++ b/crates/typst-pdf/src/image.rs @@ -5,7 +5,7 @@ use image::{DynamicImage, EncodableLayout, GenericImageView, Rgba}; use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace}; use krilla::surface::Surface; use krilla_svg::{SurfaceExt, SvgSettings}; -use typst_library::diag::{bail, SourceResult}; +use typst_library::diag::{SourceResult, bail}; use typst_library::foundations::Smart; use typst_library::layout::{Abs, Angle, Ratio, Size, Transform}; use typst_library::visualize::{ diff --git a/crates/typst-pdf/src/lib.rs b/crates/typst-pdf/src/lib.rs index 88c6ee552..96bbac591 100644 --- a/crates/typst-pdf/src/lib.rs +++ b/crates/typst-pdf/src/lib.rs @@ -18,7 +18,7 @@ use std::fmt::{self, Debug, Formatter}; use ecow::eco_format; use serde::{Deserialize, Serialize}; -use typst_library::diag::{bail, SourceResult, StrResult}; +use typst_library::diag::{SourceResult, StrResult, bail}; use typst_library::foundations::Smart; use typst_library::layout::{PageRanges, PagedDocument}; diff --git a/crates/typst-pdf/src/outline.rs b/crates/typst-pdf/src/outline.rs index e95bf67fb..7228f0f32 100644 --- a/crates/typst-pdf/src/outline.rs +++ b/crates/typst-pdf/src/outline.rs @@ -24,10 +24,10 @@ pub(crate) fn build_outline(gc: &GlobalContext) -> Outline { if let Some(page_ranges) = &gc.options.page_ranges && !page_ranges .includes_page(gc.document.introspector.page(elem.location().unwrap())) - { - // Don't bookmark headings in non-exported pages. - continue; - } + { + // Don't bookmark headings in non-exported pages. + continue; + } let heading = elem.to_packed::().unwrap(); let leaf = HeadingNode::leaf(heading); diff --git a/crates/typst-pdf/src/paint.rs b/crates/typst-pdf/src/paint.rs index 5224464ab..e03d0e945 100644 --- a/crates/typst-pdf/src/paint.rs +++ b/crates/typst-pdf/src/paint.rs @@ -15,7 +15,7 @@ use typst_library::visualize::{ }; use typst_utils::Numeric; -use crate::convert::{handle_frame, FrameContext, GlobalContext, State}; +use crate::convert::{FrameContext, GlobalContext, State, handle_frame}; use crate::util::{AbsExt, FillRuleExt, LineCapExt, LineJoinExt, TransformExt}; pub(crate) fn convert_fill( diff --git a/crates/typst-pdf/src/shape.rs b/crates/typst-pdf/src/shape.rs index 5b9232dbe..5dc23563b 100644 --- a/crates/typst-pdf/src/shape.rs +++ b/crates/typst-pdf/src/shape.rs @@ -6,7 +6,7 @@ use typst_syntax::Span; use crate::convert::{FrameContext, GlobalContext}; use crate::paint; -use crate::util::{convert_path, AbsExt, TransformExt}; +use crate::util::{AbsExt, TransformExt, convert_path}; #[typst_macros::time(name = "handle shape")] pub(crate) fn handle_shape( @@ -35,11 +35,7 @@ pub(crate) fn handle_shape( }; let stroke = shape.stroke.as_ref().and_then(|stroke| { - if stroke.thickness.to_f32() > 0.0 { - Some(stroke) - } else { - None - } + if stroke.thickness.to_f32() > 0.0 { Some(stroke) } else { None } }); let stroke = if let Some(stroke) = &stroke { diff --git a/crates/typst-pdf/src/text.rs b/crates/typst-pdf/src/text.rs index 9876927d0..8bce738ce 100644 --- a/crates/typst-pdf/src/text.rs +++ b/crates/typst-pdf/src/text.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use bytemuck::TransparentWrapper; use krilla::surface::{Location, Surface}; use krilla::text::GlyphId; -use typst_library::diag::{bail, SourceResult}; +use typst_library::diag::{SourceResult, bail}; use typst_library::layout::Size; use typst_library::text::{Font, Glyph, TextItem}; use typst_library::visualize::FillRule; @@ -12,7 +12,7 @@ use typst_syntax::Span; use crate::convert::{FrameContext, GlobalContext}; use crate::paint; -use crate::util::{display_font, AbsExt, TransformExt}; +use crate::util::{AbsExt, TransformExt, display_font}; #[typst_macros::time(name = "handle text")] pub(crate) fn handle_text( diff --git a/crates/typst-realize/src/lib.rs b/crates/typst-realize/src/lib.rs index cbb3ac21d..abdecb079 100644 --- a/crates/typst-realize/src/lib.rs +++ b/crates/typst-realize/src/lib.rs @@ -11,7 +11,7 @@ use arrayvec::ArrayVec; use bumpalo::collections::{String as BumpString, Vec as BumpVec}; use comemo::Track; use ecow::EcoString; -use typst_library::diag::{bail, At, SourceResult}; +use typst_library::diag::{At, SourceResult, bail}; use typst_library::engine::Engine; use typst_library::foundations::{ Content, Context, ContextElem, Element, NativeElement, NativeShowRule, Recipe, @@ -308,10 +308,11 @@ fn visit_kind_rules<'a>( return Ok(true); } } else if let Some(elem) = content.to_packed::() - && let Some(m) = find_regex_match_in_str(&elem.text, styles) { - visit_regex_match(s, &[(content, styles)], m)?; - return Ok(true); - } + && let Some(m) = find_regex_match_in_str(&elem.text, styles) + { + visit_regex_match(s, &[(content, styles)], m)?; + return Ok(true); + } } else { // Transparently wrap mathy content into equations. if content.can::() && !content.is::() { @@ -1091,10 +1092,9 @@ fn find_regex_match_in_elems<'a>( } let linebreak = content.is::(); - if linebreak - && let SpaceState::Space(_) = space { - buf.pop(); - } + if linebreak && let SpaceState::Space(_) = space { + buf.pop(); + } if styles != current && !buf.is_empty() { leftmost = find_regex_match_in_str(&buf, current); diff --git a/crates/typst-render/src/lib.rs b/crates/typst-render/src/lib.rs index 5a993dbb9..2b717b3bc 100644 --- a/crates/typst-render/src/lib.rs +++ b/crates/typst-render/src/lib.rs @@ -130,11 +130,7 @@ impl State<'_> { /// Sets the current mask. fn with_mask(self, mask: Option<&sk::Mask>) -> State<'_> { // Ensure that we're using the parent's mask if we don't have one. - if mask.is_some() { - State { mask, ..self } - } else { - State { mask: None, ..self } - } + if mask.is_some() { State { mask, ..self } } else { State { mask: None, ..self } } } /// Sets the size of the first hard frame in the hierarchy. @@ -196,36 +192,36 @@ fn render_group(canvas: &mut sk::Pixmap, state: State, pos: Point, group: &Group if let Some(clip_curve) = group.clip.as_ref() && let Some(path) = shape::convert_curve(clip_curve) .and_then(|path| path.transform(state.transform)) - { - if let Some(mask) = mask { - let mut mask = mask.clone(); - mask.intersect_path( - &path, - sk::FillRule::default(), - true, - sk::Transform::default(), - ); - storage = mask; - } else { - let pxw = canvas.width(); - let pxh = canvas.height(); - let Some(mut mask) = sk::Mask::new(pxw, pxh) else { - // Fails if clipping rect is empty. In that case we just - // clip everything by returning. - return; - }; - - mask.fill_path( - &path, - sk::FillRule::default(), - true, - sk::Transform::default(), - ); - storage = mask; + { + if let Some(mask) = mask { + let mut mask = mask.clone(); + mask.intersect_path( + &path, + sk::FillRule::default(), + true, + sk::Transform::default(), + ); + storage = mask; + } else { + let pxw = canvas.width(); + let pxh = canvas.height(); + let Some(mut mask) = sk::Mask::new(pxw, pxh) else { + // Fails if clipping rect is empty. In that case we just + // clip everything by returning. + return; }; - mask = Some(&storage); - } + mask.fill_path( + &path, + sk::FillRule::default(), + true, + sk::Transform::default(), + ); + storage = mask; + }; + + mask = Some(&storage); + } render_frame(canvas, state.with_mask(mask), &group.frame); } diff --git a/crates/typst-render/src/shape.rs b/crates/typst-render/src/shape.rs index 9b50d5f1f..bf55c8b5e 100644 --- a/crates/typst-render/src/shape.rs +++ b/crates/typst-render/src/shape.rs @@ -5,7 +5,7 @@ use typst_library::visualize::{ Shape, }; -use crate::{paint, AbsExt, State}; +use crate::{AbsExt, State, paint}; /// Render a geometrical shape into the canvas. pub fn render_shape(canvas: &mut sk::Pixmap, state: State, shape: &Shape) -> Option<()> { diff --git a/crates/typst-render/src/text.rs b/crates/typst-render/src/text.rs index a56528220..c411d7ae7 100644 --- a/crates/typst-render/src/text.rs +++ b/crates/typst-render/src/text.rs @@ -9,7 +9,7 @@ use typst_library::text::{Font, TextItem}; use typst_library::visualize::{FixedStroke, Paint}; use crate::paint::{self, GradientSampler, PaintSampler, TilingSampler}; -use crate::{shape, AbsExt, State}; +use crate::{AbsExt, State, shape}; /// Render a text run into the canvas. pub fn render_text(canvas: &mut sk::Pixmap, state: State, text: &TextItem) { @@ -87,28 +87,29 @@ fn render_outline_glyph( if let Some(FixedStroke { paint, thickness, cap, join, dash, miter_limit }) = &text.stroke - && thickness.to_f32() > 0.0 { - let dash = dash.as_ref().and_then(shape::to_sk_dash_pattern); + && thickness.to_f32() > 0.0 + { + let dash = dash.as_ref().and_then(shape::to_sk_dash_pattern); - let paint = paint::to_sk_paint( - paint, - state_ts, - Size::zero(), - true, - None, - &mut pixmap, - None, - ); - let stroke = sk::Stroke { - width: thickness.to_f32() / scale, // When we scale the path, we need to scale the stroke width, too. - line_cap: shape::to_sk_line_cap(*cap), - line_join: shape::to_sk_line_join(*join), - dash, - miter_limit: miter_limit.get() as f32, - }; + let paint = paint::to_sk_paint( + paint, + state_ts, + Size::zero(), + true, + None, + &mut pixmap, + None, + ); + let stroke = sk::Stroke { + width: thickness.to_f32() / scale, // When we scale the path, we need to scale the stroke width, too. + line_cap: shape::to_sk_line_cap(*cap), + line_join: shape::to_sk_line_join(*join), + dash, + miter_limit: miter_limit.get() as f32, + }; - canvas.stroke_path(&path, &paint, &stroke, ts, state.mask); - } + canvas.stroke_path(&path, &paint, &stroke, ts, state.mask); + } return Some(()); } diff --git a/crates/typst-svg/src/image.rs b/crates/typst-svg/src/image.rs index fd4aecd4f..58f0227b6 100644 --- a/crates/typst-svg/src/image.rs +++ b/crates/typst-svg/src/image.rs @@ -1,6 +1,6 @@ use base64::Engine; -use ecow::{eco_format, EcoString}; -use image::{codecs::png::PngEncoder, ImageEncoder}; +use ecow::{EcoString, eco_format}; +use image::{ImageEncoder, codecs::png::PngEncoder}; use typst_library::foundations::Smart; use typst_library::layout::{Abs, Axes}; use typst_library::visualize::{ diff --git a/crates/typst-svg/src/lib.rs b/crates/typst-svg/src/lib.rs index 85bd5d7cb..c33747b31 100644 --- a/crates/typst-svg/src/lib.rs +++ b/crates/typst-svg/src/lib.rs @@ -341,10 +341,11 @@ impl<'a> SVGRenderer<'a> { // TODO: Location links on the same page could also be supported // outside of HTML. if let Some(introspector) = self.introspector - && let Some(id) = introspector.html_id(*loc) { - self.xml.write_attribute_fmt("href", format_args!("#{id}")); - self.xml.write_attribute_fmt("xlink:href", format_args!("#{id}")); - } + && let Some(id) = introspector.html_id(*loc) + { + self.xml.write_attribute_fmt("href", format_args!("#{id}")); + self.xml.write_attribute_fmt("xlink:href", format_args!("#{id}")); + } } Destination::Position(_) => { // TODO: Links on the same page could be supported. diff --git a/crates/typst-svg/src/paint.rs b/crates/typst-svg/src/paint.rs index 1a9acaecf..a955a4d16 100644 --- a/crates/typst-svg/src/paint.rs +++ b/crates/typst-svg/src/paint.rs @@ -1,6 +1,6 @@ use std::f32::consts::TAU; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use ttf_parser::OutlineBuilder; use typst_library::foundations::Repr; use typst_library::layout::{Angle, Axes, Frame, Quadrant, Ratio, Size, Transform}; diff --git a/crates/typst-syntax/src/ast.rs b/crates/typst-syntax/src/ast.rs index 547d53cd8..d629f24d7 100644 --- a/crates/typst-syntax/src/ast.rs +++ b/crates/typst-syntax/src/ast.rs @@ -86,7 +86,7 @@ use ecow::EcoString; use unscanny::Scanner; use crate::package::PackageSpec; -use crate::{is_ident, is_newline, Span, SyntaxKind, SyntaxNode}; +use crate::{Span, SyntaxKind, SyntaxNode, is_ident, is_newline}; /// A typed AST node. pub trait AstNode<'a>: Sized { diff --git a/crates/typst-syntax/src/file.rs b/crates/typst-syntax/src/file.rs index 380ca2346..0fcea91c2 100644 --- a/crates/typst-syntax/src/file.rs +++ b/crates/typst-syntax/src/file.rs @@ -5,8 +5,8 @@ use std::fmt::{self, Debug, Formatter}; use std::num::NonZeroU16; use std::sync::{LazyLock, RwLock}; -use crate::package::PackageSpec; use crate::VirtualPath; +use crate::package::PackageSpec; /// The global package-path interner. static INTERNER: LazyLock> = LazyLock::new(|| { diff --git a/crates/typst-syntax/src/highlight.rs b/crates/typst-syntax/src/highlight.rs index 9754312b3..0cd83105a 100644 --- a/crates/typst-syntax/src/highlight.rs +++ b/crates/typst-syntax/src/highlight.rs @@ -1,4 +1,4 @@ -use crate::{ast, LinkedNode, SyntaxKind, SyntaxNode}; +use crate::{LinkedNode, SyntaxKind, SyntaxNode, ast}; /// A syntax highlighting tag. #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] @@ -302,16 +302,13 @@ fn highlight_ident(node: &LinkedNode) -> Option { let next_leaf = node.next_leaf(); if let Some(next) = &next_leaf && node.range().end == next.offset() - && ((next.kind() == SyntaxKind::LeftParen - && matches!( - next.parent_kind(), - Some(SyntaxKind::Args | SyntaxKind::Params) - )) - || (next.kind() == SyntaxKind::LeftBracket - && next.parent_kind() == Some(SyntaxKind::ContentBlock))) - { - return Some(Tag::Function); - } + && ((next.kind() == SyntaxKind::LeftParen + && matches!(next.parent_kind(), Some(SyntaxKind::Args | SyntaxKind::Params))) + || (next.kind() == SyntaxKind::LeftBracket + && next.parent_kind() == Some(SyntaxKind::ContentBlock))) + { + return Some(Tag::Function); + } // Are we in math? if node.kind() == SyntaxKind::MathIdent { @@ -379,12 +376,13 @@ pub fn highlight_html(root: &SyntaxNode) -> String { fn highlight_html_impl(html: &mut String, node: &LinkedNode) { let mut span = false; if let Some(tag) = highlight(node) - && tag != Tag::Error { - span = true; - html.push_str(""); - } + && tag != Tag::Error + { + span = true; + html.push_str(""); + } let text = node.text(); if !text.is_empty() { diff --git a/crates/typst-syntax/src/lexer.rs b/crates/typst-syntax/src/lexer.rs index 9da45958f..40b1e2994 100644 --- a/crates/typst-syntax/src/lexer.rs +++ b/crates/typst-syntax/src/lexer.rs @@ -1,4 +1,4 @@ -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use unicode_ident::{is_xid_continue, is_xid_start}; use unicode_script::{Script, UnicodeScript}; use unicode_segmentation::UnicodeSegmentation; @@ -205,11 +205,7 @@ impl Lexer<'_> { ':' => SyntaxKind::Colon, '=' => { self.s.eat_while('='); - if self.space_or_end() { - SyntaxKind::HeadingMarker - } else { - self.text() - } + if self.space_or_end() { SyntaxKind::HeadingMarker } else { self.text() } } '-' if self.space_or_end() => SyntaxKind::ListMarker, '+' if self.space_or_end() => SyntaxKind::EnumMarker, @@ -784,15 +780,12 @@ impl Lexer<'_> { let prev = self.s.get(0..start); if (!prev.ends_with(['.', '@']) || prev.ends_with("..")) - && let Some(keyword) = keyword(ident) { - return keyword; - } - - if ident == "_" { - SyntaxKind::Underscore - } else { - SyntaxKind::Ident + && let Some(keyword) = keyword(ident) + { + return keyword; } + + if ident == "_" { SyntaxKind::Underscore } else { SyntaxKind::Ident } } fn number(&mut self, start: usize, first_c: char) -> SyntaxKind { diff --git a/crates/typst-syntax/src/lib.rs b/crates/typst-syntax/src/lib.rs index 4741506c5..40e85bdad 100644 --- a/crates/typst-syntax/src/lib.rs +++ b/crates/typst-syntax/src/lib.rs @@ -17,7 +17,7 @@ mod source; mod span; pub use self::file::FileId; -pub use self::highlight::{highlight, highlight_html, Tag}; +pub use self::highlight::{Tag, highlight, highlight_html}; pub use self::kind::SyntaxKind; pub use self::lexer::{ is_id_continue, is_id_start, is_ident, is_newline, is_valid_label_literal_id, diff --git a/crates/typst-syntax/src/node.rs b/crates/typst-syntax/src/node.rs index 15c96b08f..b983f1bdb 100644 --- a/crates/typst-syntax/src/node.rs +++ b/crates/typst-syntax/src/node.rs @@ -3,7 +3,7 @@ use std::ops::{Deref, Range}; use std::rc::Rc; use std::sync::Arc; -use ecow::{eco_format, eco_vec, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format, eco_vec}; use crate::{FileId, Span, SyntaxKind}; @@ -733,9 +733,10 @@ impl<'a> LinkedNode<'a> { if children .peek() .is_none_or(|next| next.span().number() > span.number()) - && let Some(found) = child.find(span) { - return Some(found); - } + && let Some(found) = child.find(span) + { + return Some(found); + } } } @@ -757,11 +758,7 @@ impl LinkedNode<'_> { let node = parent.node.children().nth(index)?; let offset = self.offset - node.len(); let prev = Self { node, parent: self.parent.clone(), index, offset }; - if prev.kind().is_trivia() { - prev.prev_sibling() - } else { - Some(prev) - } + if prev.kind().is_trivia() { prev.prev_sibling() } else { Some(prev) } } /// Get the next non-trivia sibling node. @@ -771,11 +768,7 @@ impl LinkedNode<'_> { let node = parent.node.children().nth(index)?; let offset = self.offset + self.node.len(); let next = Self { node, parent: self.parent.clone(), index, offset }; - if next.kind().is_trivia() { - next.next_sibling() - } else { - Some(next) - } + if next.kind().is_trivia() { next.next_sibling() } else { Some(next) } } /// Get the kind of this node's parent. diff --git a/crates/typst-syntax/src/package.rs b/crates/typst-syntax/src/package.rs index aa537863d..fe3577a3b 100644 --- a/crates/typst-syntax/src/package.rs +++ b/crates/typst-syntax/src/package.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use std::fmt::{self, Debug, Display, Formatter}; use std::str::FromStr; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use serde::de::IgnoredAny; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use unscanny::Scanner; @@ -562,8 +562,9 @@ mod tests { fn tool_section() { // NOTE: tool section must be table of tables, but we can't easily // compare the error structurally - assert!(toml::from_str::( - r#" + assert!( + toml::from_str::( + r#" [package] name = "package" version = "0.1.0" @@ -572,8 +573,9 @@ mod tests { [tool] not-table = "str" "# - ) - .is_err()); + ) + .is_err() + ); #[derive(Debug, PartialEq, Serialize, Deserialize)] struct MyTool { diff --git a/crates/typst-syntax/src/parser.rs b/crates/typst-syntax/src/parser.rs index 22f073601..5b354e9cd 100644 --- a/crates/typst-syntax/src/parser.rs +++ b/crates/typst-syntax/src/parser.rs @@ -2,12 +2,12 @@ use std::collections::{HashMap, HashSet}; use std::mem; use std::ops::{Index, IndexMut, Range}; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_utils::default_math_class; use unicode_math_class::MathClass; -use crate::set::{syntax_set, SyntaxSet}; -use crate::{ast, set, Lexer, SyntaxError, SyntaxKind, SyntaxMode, SyntaxNode}; +use crate::set::{SyntaxSet, syntax_set}; +use crate::{Lexer, SyntaxError, SyntaxKind, SyntaxMode, SyntaxNode, ast, set}; /// Parses a source file as top-level markup. pub fn parse(text: &str) -> SyntaxNode { @@ -443,12 +443,14 @@ fn math_unparen(p: &mut Parser, m: Marker) { } if let [first, .., last] = node.children_mut() - && first.text() == "(" && last.text() == ")" { - first.convert_to_kind(SyntaxKind::LeftParen); - last.convert_to_kind(SyntaxKind::RightParen); - // Only convert if we did have regular parens. - node.convert_to_kind(SyntaxKind::Math); - } + && first.text() == "(" + && last.text() == ")" + { + first.convert_to_kind(SyntaxKind::LeftParen); + last.convert_to_kind(SyntaxKind::RightParen); + // Only convert if we did have regular parens. + node.convert_to_kind(SyntaxKind::Math); + } } /// The unicode math class of a string. Only returns `Some` if `text` has @@ -1198,10 +1200,10 @@ fn array_or_dict_item(p: &mut Parser, state: &mut GroupState) { Some(ast::Expr::Ident(ident)) => Some(ident.get().clone()), Some(ast::Expr::Str(s)) => Some(s.get()), _ => None, + } && !state.seen.insert(key.clone()) + { + node.convert_to_error(eco_format!("duplicate key: {key}")); } - && !state.seen.insert(key.clone()) { - node.convert_to_error(eco_format!("duplicate key: {key}")); - } p.wrap(m, pair_kind); state.maybe_just_parens = false; @@ -1854,15 +1856,16 @@ impl<'s> Parser<'s> { func(self); self.nl_mode = previous; if let Some(newline) = self.token.newline - && mode != previous { - // Restore our actual token's kind or insert a fake end. - let actual_kind = self.token.node.kind(); - if self.nl_mode.stop_at(newline, actual_kind) { - self.token.kind = SyntaxKind::End; - } else { - self.token.kind = actual_kind; - } + && mode != previous + { + // Restore our actual token's kind or insert a fake end. + let actual_kind = self.token.node.kind(); + if self.nl_mode.stop_at(newline, actual_kind) { + self.token.kind = SyntaxKind::End; + } else { + self.token.kind = actual_kind; } + } } /// Move the lexer forward and prepare the current token. In Code, this diff --git a/crates/typst-syntax/src/reparser.rs b/crates/typst-syntax/src/reparser.rs index 2df606310..e0bc2214a 100644 --- a/crates/typst-syntax/src/reparser.rs +++ b/crates/typst-syntax/src/reparser.rs @@ -1,7 +1,7 @@ use std::ops::Range; use crate::{ - is_newline, parse, reparse_block, reparse_markup, Span, SyntaxKind, SyntaxNode, + Span, SyntaxKind, SyntaxNode, is_newline, parse, reparse_block, reparse_markup, }; /// Refresh the given syntax node with as little parsing as possible. @@ -71,12 +71,13 @@ fn try_reparse( // If the child is a block, try to reparse the block. if child.kind().is_block() - && let Some(newborn) = reparse_block(text, new_range.clone()) { - return node - .replace_children(i..i + 1, vec![newborn]) - .is_ok() - .then_some(new_range); - } + && let Some(newborn) = reparse_block(text, new_range.clone()) + { + return node + .replace_children(i..i + 1, vec![newborn]) + .is_ok() + .then_some(new_range); + } } // Does the child overlap with the edit? @@ -239,7 +240,7 @@ fn next_nesting(node: &SyntaxNode, nesting: &mut usize) { mod tests { use std::ops::Range; - use crate::{parse, Source, Span}; + use crate::{Source, Span, parse}; #[track_caller] fn test(prev: &str, range: Range, with: &str, incremental: bool) { diff --git a/crates/typst-syntax/src/source.rs b/crates/typst-syntax/src/source.rs index abde1f981..05cfd62db 100644 --- a/crates/typst-syntax/src/source.rs +++ b/crates/typst-syntax/src/source.rs @@ -9,7 +9,7 @@ use typst_utils::LazyHash; use crate::lines::Lines; use crate::reparser::reparse; -use crate::{parse, FileId, LinkedNode, Span, SyntaxNode, VirtualPath}; +use crate::{FileId, LinkedNode, Span, SyntaxNode, VirtualPath, parse}; /// A source file. /// diff --git a/crates/typst-syntax/src/span.rs b/crates/typst-syntax/src/span.rs index b383ec27f..ff596c3a2 100644 --- a/crates/typst-syntax/src/span.rs +++ b/crates/typst-syntax/src/span.rs @@ -155,11 +155,7 @@ impl Span { /// Return `other` if `self` is detached and `self` otherwise. pub fn or(self, other: Self) -> Self { - if self.is_detached() { - other - } else { - self - } + if self.is_detached() { other } else { self } } /// Find the first non-detached span in the iterator. diff --git a/crates/typst-utils/src/fat.rs b/crates/typst-utils/src/fat.rs index 40751532b..d0d8c9cdb 100644 --- a/crates/typst-utils/src/fat.rs +++ b/crates/typst-utils/src/fat.rs @@ -16,11 +16,13 @@ use std::ptr::NonNull; /// to a value whose type implements the trait of `T` and the `vtable` must have /// been extracted with [`vtable`]. #[track_caller] -pub unsafe fn from_raw_parts(data: *const (), vtable: *const ()) -> *const T { unsafe { - let fat = FatPointer { data, vtable }; - debug_assert_eq!(Layout::new::<*const T>(), Layout::new::()); - mem::transmute_copy::(&fat) -}} +pub unsafe fn from_raw_parts(data: *const (), vtable: *const ()) -> *const T { + unsafe { + let fat = FatPointer { data, vtable }; + debug_assert_eq!(Layout::new::<*const T>(), Layout::new::()); + mem::transmute_copy::(&fat) + } +} /// Create a mutable fat pointer from a data address and a vtable address. /// @@ -29,23 +31,27 @@ pub unsafe fn from_raw_parts(data: *const (), vtable: *const ()) -> * /// to a value whose type implements the trait of `T` and the `vtable` must have /// been extracted with [`vtable`]. #[track_caller] -pub unsafe fn from_raw_parts_mut(data: *mut (), vtable: *const ()) -> *mut T { unsafe { - let fat = FatPointer { data, vtable }; - debug_assert_eq!(Layout::new::<*mut T>(), Layout::new::()); - mem::transmute_copy::(&fat) -}} +pub unsafe fn from_raw_parts_mut(data: *mut (), vtable: *const ()) -> *mut T { + unsafe { + let fat = FatPointer { data, vtable }; + debug_assert_eq!(Layout::new::<*mut T>(), Layout::new::()); + mem::transmute_copy::(&fat) + } +} /// Extract the address to a trait object's vtable. /// /// # Safety /// Must only be called when `T` is a `dyn Trait`. #[track_caller] -pub unsafe fn vtable(ptr: *const T) -> NonNull<()> { unsafe { - debug_assert_eq!(Layout::new::<*const T>(), Layout::new::()); - NonNull::new_unchecked( - mem::transmute_copy::<*const T, FatPointer>(&ptr).vtable as *mut (), - ) -}} +pub unsafe fn vtable(ptr: *const T) -> NonNull<()> { + unsafe { + debug_assert_eq!(Layout::new::<*const T>(), Layout::new::()); + NonNull::new_unchecked( + mem::transmute_copy::<*const T, FatPointer>(&ptr).vtable as *mut (), + ) + } +} /// The memory representation of a trait object pointer. /// diff --git a/crates/typst-utils/src/pico.rs b/crates/typst-utils/src/pico.rs index 5f17a2672..b6f269af8 100644 --- a/crates/typst-utils/src/pico.rs +++ b/crates/typst-utils/src/pico.rs @@ -330,11 +330,7 @@ mod exceptions { /// Determine the minimum of two integers. const fn min(a: usize, b: usize) -> usize { - if a < b { - a - } else { - b - } + if a < b { a } else { b } } } diff --git a/crates/typst/src/lib.rs b/crates/typst/src/lib.rs index 8b4e60eee..47e5531fd 100644 --- a/crates/typst/src/lib.rs +++ b/crates/typst/src/lib.rs @@ -42,10 +42,10 @@ use std::collections::HashSet; use std::sync::LazyLock; use comemo::{Track, Tracked, Validate}; -use ecow::{eco_format, eco_vec, EcoString, EcoVec}; +use ecow::{EcoString, EcoVec, eco_format, eco_vec}; use typst_html::HtmlDocument; use typst_library::diag::{ - bail, warning, FileError, SourceDiagnostic, SourceResult, Warned, + FileError, SourceDiagnostic, SourceResult, Warned, bail, warning, }; use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::foundations::{NativeRuleMap, StyleChain, Styles, Value}; @@ -53,7 +53,7 @@ use typst_library::introspection::Introspector; use typst_library::layout::PagedDocument; use typst_library::routines::Routines; use typst_syntax::{FileId, Span}; -use typst_timing::{timed, TimingScope}; +use typst_timing::{TimingScope, timed}; use crate::foundations::{Target, TargetElem}; use crate::model::DocumentInfo; diff --git a/docs/src/html.rs b/docs/src/html.rs index 9c02f08e9..f1c175bb7 100644 --- a/docs/src/html.rs +++ b/docs/src/html.rs @@ -16,7 +16,7 @@ use typst::{Library, World}; use unscanny::Scanner; use yaml_front_matter::YamlFrontMatter; -use crate::{contributors, OutlineItem, Resolver, FONTS, LIBRARY}; +use crate::{FONTS, LIBRARY, OutlineItem, Resolver, contributors}; /// HTML documentation. #[derive(Serialize)] @@ -84,14 +84,16 @@ impl Html { md::Parser::new_with_broken_link_callback(text, options, Some(&mut link)) .peekable(); - let iter = std::iter::from_fn(|| loop { - let mut event = events.next()?; - handler.peeked = events.peek().and_then(|event| match event { - md::Event::Text(text) => Some(text.clone()), - _ => None, - }); - if handler.handle(&mut event) { - return Some(event); + let iter = std::iter::from_fn(|| { + loop { + let mut event = events.next()?; + handler.peeked = events.peek().and_then(|event| match event { + md::Event::Text(text) => Some(text.clone()), + _ => None, + }); + if handler.handle(&mut event) { + return Some(event); + } } }); diff --git a/docs/src/lib.rs b/docs/src/lib.rs index 155ffb827..352b90dec 100644 --- a/docs/src/lib.rs +++ b/docs/src/lib.rs @@ -11,12 +11,12 @@ pub use self::model::*; use std::collections::HashSet; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use heck::ToTitleCase; use serde::Deserialize; use serde_yaml as yaml; use std::sync::LazyLock; -use typst::diag::{bail, StrResult}; +use typst::diag::{StrResult, bail}; use typst::foundations::{ AutoValue, Binding, Bytes, CastInfo, Func, Module, NoneValue, ParamInfo, Repr, Scope, Smart, Type, Value, @@ -103,7 +103,7 @@ pub trait Resolver { /// Produce HTML for an example. fn example(&self, hash: u128, source: Option, document: &PagedDocument) - -> Html; + -> Html; /// Determine the commits between two tags. fn commits(&self, from: &str, to: &str) -> Vec; diff --git a/docs/src/link.rs b/docs/src/link.rs index b883399e5..2c2fce21c 100644 --- a/docs/src/link.rs +++ b/docs/src/link.rs @@ -1,7 +1,7 @@ -use typst::diag::{bail, StrResult}; +use typst::diag::{StrResult, bail}; use typst::foundations::{Binding, Func}; -use crate::{get_module, GROUPS, LIBRARY}; +use crate::{GROUPS, LIBRARY, get_module}; /// Resolve an intra-doc link. pub fn resolve(link: &str, base: &str) -> StrResult { @@ -97,10 +97,11 @@ fn resolve_definition(head: &str, base: &str) -> StrResult { route.push_str("/#definitions-"); route.push_str(next); if let Some(next) = parts.next() - && field.cast::().is_ok_and(|func| func.param(next).is_some()) { - route.push('-'); - route.push_str(next); - } + && field.cast::().is_ok_and(|func| func.param(next).is_some()) + { + route.push('-'); + route.push_str(next); + } } else if value .clone() .cast::() diff --git a/docs/src/main.rs b/docs/src/main.rs index d14c1347a..707cd7da2 100644 --- a/docs/src/main.rs +++ b/docs/src/main.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use clap::Parser; use typst::layout::PagedDocument; -use typst_docs::{provide, Html, Resolver}; +use typst_docs::{Html, Resolver, provide}; use typst_render::render; #[derive(Debug)] diff --git a/tests/fuzz/src/compile.rs b/tests/fuzz/src/compile.rs index 1bc85fd62..3f1015339 100644 --- a/tests/fuzz/src/compile.rs +++ b/tests/fuzz/src/compile.rs @@ -67,8 +67,9 @@ impl World for FuzzWorld { fuzz_target!(|text: &str| { let world = FuzzWorld::new(text); if let Ok(document) = typst::compile::(&world).output - && let Some(page) = document.pages.first() { - std::hint::black_box(typst_render::render(page, 1.0)); - } + && let Some(page) = document.pages.first() + { + std::hint::black_box(typst_render::render(page, 1.0)); + } comemo::evict(10); }); diff --git a/tests/src/collect.rs b/tests/src/collect.rs index 173488b01..d1b59cb9b 100644 --- a/tests/src/collect.rs +++ b/tests/src/collect.rs @@ -5,10 +5,10 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::LazyLock; -use ecow::{eco_format, EcoString}; +use ecow::{EcoString, eco_format}; use typst_syntax::package::PackageVersion; use typst_syntax::{ - is_id_continue, is_ident, is_newline, FileId, Lines, Source, VirtualPath, + FileId, Lines, Source, VirtualPath, is_id_continue, is_ident, is_newline, }; use unscanny::Scanner; @@ -528,11 +528,7 @@ fn selected(name: &str, abs: PathBuf) -> bool { let patterns = &crate::ARGS.pattern; patterns.is_empty() || patterns.iter().any(|pattern: ®ex::Regex| { - if exact { - name == pattern.as_str() - } else { - pattern.is_match(name) - } + if exact { name == pattern.as_str() } else { pattern.is_match(name) } }) } diff --git a/tests/src/custom.rs b/tests/src/custom.rs index 965312abc..139d35f0c 100644 --- a/tests/src/custom.rs +++ b/tests/src/custom.rs @@ -1,9 +1,9 @@ use std::fmt::Write; +use typst::World; use typst::foundations::Smart; use typst::layout::PagedDocument; use typst::model::DocumentInfo; -use typst::World; use crate::collect::Test; use crate::world::TestWorld; diff --git a/tests/src/run.rs b/tests/src/run.rs index 9af5c7899..913f9dd0b 100644 --- a/tests/src/run.rs +++ b/tests/src/run.rs @@ -14,7 +14,7 @@ use typst_syntax::{FileId, Lines}; use crate::collect::{Attr, FileSize, NoteKind, Test}; use crate::logger::TestResult; -use crate::world::{system_path, TestWorld}; +use crate::world::{TestWorld, system_path}; /// Runs a single test. /// @@ -189,8 +189,14 @@ impl<'a> Runner<'a> { log!(self, "reference output would exceed maximum size"); log!(self, " maximum | {}", FileSize(crate::REF_LIMIT)); log!(self, " size | {}", FileSize(ref_data.len())); - log!(self, "please try to minimize the size of the test (smaller pages, less text, etc.)"); - log!(self, "if you think the test cannot be reasonably minimized, mark it as `large`"); + log!( + self, + "please try to minimize the size of the test (smaller pages, less text, etc.)" + ); + log!( + self, + "if you think the test cannot be reasonably minimized, mark it as `large`" + ); return; } std::fs::write(&ref_path, &ref_data).unwrap(); @@ -337,11 +343,7 @@ impl<'a> Runner<'a> { return "oob".into(); }; - if line == 1 { - format!("{col}") - } else { - format!("{line}:{col}") - } + if line == 1 { format!("{col}") } else { format!("{line}:{col}") } } #[track_caller] diff --git a/tests/src/world.rs b/tests/src/world.rs index 4b6cf5a34..85969700d 100644 --- a/tests/src/world.rs +++ b/tests/src/world.rs @@ -8,16 +8,16 @@ use std::sync::OnceLock; use comemo::Tracked; use parking_lot::Mutex; -use typst::diag::{bail, At, FileError, FileResult, SourceResult, StrResult}; +use typst::diag::{At, FileError, FileResult, SourceResult, StrResult, bail}; use typst::engine::Engine; use typst::foundations::{ - func, Array, Bytes, Context, Datetime, IntoValue, NoneValue, Repr, Smart, Value, + Array, Bytes, Context, Datetime, IntoValue, NoneValue, Repr, Smart, Value, func, }; use typst::layout::{Abs, Margin, PageElem}; use typst::model::{Numbering, NumberingPattern}; use typst::syntax::{FileId, Source, Span}; use typst::text::{Font, FontBook, TextElem, TextSize}; -use typst::utils::{singleton, LazyHash}; +use typst::utils::{LazyHash, singleton}; use typst::visualize::Color; use typst::{Feature, Library, LibraryExt, World}; use typst_syntax::Lines;