From 55dad028870329a5d78d7d62fe45844acc10f943 Mon Sep 17 00:00:00 2001 From: pog102 <85764555+pog102@users.noreply.github.com> Date: Mon, 21 Jul 2025 13:57:40 +0300 Subject: [PATCH 01/11] Add Lithuanian translations (#6587) --- crates/typst-library/src/text/lang.rs | 2 ++ crates/typst-library/translations/lt.txt | 8 ++++++++ 2 files changed, 10 insertions(+) create mode 100644 crates/typst-library/translations/lt.txt diff --git a/crates/typst-library/src/text/lang.rs b/crates/typst-library/src/text/lang.rs index 530b1f004..4f8d1e93f 100644 --- a/crates/typst-library/src/text/lang.rs +++ b/crates/typst-library/src/text/lang.rs @@ -37,6 +37,7 @@ const TRANSLATIONS: &[(&str, &str)] = &[ translation!("it"), translation!("ja"), translation!("la"), + translation!("lt"), translation!("lv"), translation!("nb"), translation!("nl"), @@ -90,6 +91,7 @@ impl Lang { pub const JAPANESE: Self = Self(*b"ja ", 2); pub const LATIN: Self = Self(*b"la ", 2); pub const LATVIAN: Self = Self(*b"lv ", 2); + pub const LITHUANIAN: Self = Self(*b"lt ", 2); pub const LOWER_SORBIAN: Self = Self(*b"dsb", 3); pub const NYNORSK: Self = Self(*b"nn ", 2); pub const POLISH: Self = Self(*b"pl ", 2); diff --git a/crates/typst-library/translations/lt.txt b/crates/typst-library/translations/lt.txt new file mode 100644 index 000000000..1df3ca91b --- /dev/null +++ b/crates/typst-library/translations/lt.txt @@ -0,0 +1,8 @@ +figure = Pav. +table = Lent. +equation = Lygt. +bibliography = Literatūra +heading = Skyrius +outline = Turinys +raw = Kodo fragmentas +page = Psl. From a43b7e785c3df87e8d2116d911923a9b6a000378 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 21 Jul 2025 13:48:48 +0200 Subject: [PATCH 02/11] Bump CI Rust to 1.88 --- .github/workflows/ci.yml | 4 ++-- .github/workflows/release.yml | 2 +- flake.lock | 6 +++--- flake.nix | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70518860e..369a2d5ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,7 +40,7 @@ jobs: sudo dpkg --add-architecture i386 sudo apt update sudo apt install -y gcc-multilib libssl-dev:i386 pkg-config:i386 - - uses: dtolnay/rust-toolchain@1.87.0 + - uses: dtolnay/rust-toolchain@1.88.0 with: targets: ${{ matrix.bits == 32 && 'i686-unknown-linux-gnu' || '' }} - uses: Swatinem/rust-cache@v2 @@ -73,7 +73,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@1.87.0 + - uses: dtolnay/rust-toolchain@1.88.0 with: components: clippy, rustfmt - uses: Swatinem/rust-cache@v2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ca317abd0..566fc5808 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,7 +44,7 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@1.87.0 + - uses: dtolnay/rust-toolchain@1.88.0 with: target: ${{ matrix.target }} diff --git a/flake.lock b/flake.lock index dedfbb4e0..df8b752ba 100644 --- a/flake.lock +++ b/flake.lock @@ -112,13 +112,13 @@ "rust-manifest": { "flake": false, "locked": { - "narHash": "sha256-BwfxWd/E8gpnXoKsucFXhMbevMlVgw3l0becLkIcWCU=", + "narHash": "sha256-YZfjbpqCYQFG1qLl2zMyFq2nFwmB2aFo5DSOCaBtGLY=", "type": "file", - "url": "https://static.rust-lang.org/dist/channel-rust-1.87.0.toml" + "url": "https://static.rust-lang.org/dist/channel-rust-1.88.0.toml" }, "original": { "type": "file", - "url": "https://static.rust-lang.org/dist/channel-rust-1.87.0.toml" + "url": "https://static.rust-lang.org/dist/channel-rust-1.88.0.toml" } }, "systems": { diff --git a/flake.nix b/flake.nix index cc5f96273..5afb5a846 100644 --- a/flake.nix +++ b/flake.nix @@ -10,7 +10,7 @@ inputs.nixpkgs.follows = "nixpkgs"; }; rust-manifest = { - url = "https://static.rust-lang.org/dist/channel-rust-1.87.0.toml"; + url = "https://static.rust-lang.org/dist/channel-rust-1.88.0.toml"; flake = false; }; }; From eed75ca4d6d547d2a5844dfb8ce3e7df5e065a58 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 21 Jul 2025 13:49:01 +0200 Subject: [PATCH 03/11] Bump MSRV to 1.88 --- .github/workflows/ci.yml | 6 +++--- Cargo.toml | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 369a2d5ee..7180dcad9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -88,7 +88,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@1.83.0 + - uses: dtolnay/rust-toolchain@1.88.0 - uses: Swatinem/rust-cache@v2 - run: cargo check --workspace @@ -99,7 +99,7 @@ jobs: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: - toolchain: nightly-2024-10-29 + toolchain: nightly-2025-05-10 - uses: Swatinem/rust-cache@v2 - run: cargo install --locked cargo-fuzz@0.12.0 - run: cd tests/fuzz && cargo fuzz build --dev @@ -112,6 +112,6 @@ jobs: - uses: dtolnay/rust-toolchain@master with: components: miri - toolchain: nightly-2024-10-29 + toolchain: nightly-2025-05-10 - uses: Swatinem/rust-cache@v2 - run: cargo miri test -p typst-library test_miri diff --git a/Cargo.toml b/Cargo.toml index 63ea32b94..0a6678a6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ resolver = "2" [workspace.package] version = "0.13.1" -rust-version = "1.83" # also change in ci.yml +rust-version = "1.88" # also change in ci.yml authors = ["The Typst Project Developers"] edition = "2021" homepage = "https://typst.app" From 4bbd4e195bf9e6672c0d53205adebca884a98e77 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 21 Jul 2025 14:19:24 +0200 Subject: [PATCH 04/11] Migrate to 2024 edition --- Cargo.toml | 2 +- crates/typst-ide/src/jump.rs | 4 ++-- crates/typst-layout/src/grid/layouter.rs | 2 +- crates/typst-layout/src/math/lr.rs | 4 ++-- crates/typst-layout/src/math/stretch.rs | 2 +- crates/typst-library/src/engine.rs | 2 +- .../typst-library/src/introspection/introspector.rs | 2 +- crates/typst-pdf/src/metadata.rs | 2 +- crates/typst-utils/src/fat.rs | 12 ++++++------ 9 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0a6678a6a..43a077ddb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ resolver = "2" version = "0.13.1" rust-version = "1.88" # also change in ci.yml authors = ["The Typst Project Developers"] -edition = "2021" +edition = "2024" homepage = "https://typst.app" repository = "https://github.com/typst/typst" license = "Apache-2.0" diff --git a/crates/typst-ide/src/jump.rs b/crates/typst-ide/src/jump.rs index b29bc4a48..c9a53547a 100644 --- a/crates/typst-ide/src/jump.rs +++ b/crates/typst-ide/src/jump.rs @@ -50,7 +50,7 @@ pub fn jump_from_click( } // If there's no link, search for a jump target. - for (mut pos, item) in frame.items().rev() { + for &(mut pos, ref item) in frame.items().rev() { match item { FrameItem::Group(group) => { let pos = click - pos; @@ -177,7 +177,7 @@ pub fn jump_from_cursor( /// Find the position of a span in a frame. fn find_in_frame(frame: &Frame, span: Span) -> Option { - for (mut pos, item) in frame.items() { + for &(mut pos, ref item) in frame.items() { if let FrameItem::Group(group) = item { if let Some(point) = find_in_frame(&group.frame, span) { return Some(pos + point.transform(group.transform)); diff --git a/crates/typst-layout/src/grid/layouter.rs b/crates/typst-layout/src/grid/layouter.rs index d4f11f470..a5803f830 100644 --- a/crates/typst-layout/src/grid/layouter.rs +++ b/crates/typst-layout/src/grid/layouter.rs @@ -1228,7 +1228,7 @@ impl<'a> GridLayouter<'a> { .skip(parent.y) .take(rowspan) .rev() - .find(|(_, &row)| row == Sizing::Auto) + .find(|&(_, &row)| row == Sizing::Auto) .map(|(y, _)| y); if last_spanned_auto_row != Some(y) { diff --git a/crates/typst-layout/src/math/lr.rs b/crates/typst-layout/src/math/lr.rs index 2348025e8..cba794935 100644 --- a/crates/typst-layout/src/math/lr.rs +++ b/crates/typst-layout/src/math/lr.rs @@ -55,7 +55,7 @@ pub fn layout_lr( // Handle MathFragment::Glyph fragments that should be scaled up. for fragment in inner_fragments.iter_mut() { - if let MathFragment::Glyph(ref mut glyph) = fragment { + if let MathFragment::Glyph(glyph) = fragment { if glyph.mid_stretched == Some(false) { glyph.mid_stretched = Some(true); scale(ctx, fragment, relative_to, height); @@ -95,7 +95,7 @@ pub fn layout_mid( let mut fragments = ctx.layout_into_fragments(&elem.body, styles)?; for fragment in &mut fragments { - if let MathFragment::Glyph(ref mut glyph) = fragment { + if let MathFragment::Glyph(glyph) = fragment { glyph.mid_stretched = Some(false); glyph.class = MathClass::Relation; } diff --git a/crates/typst-layout/src/math/stretch.rs b/crates/typst-layout/src/math/stretch.rs index f1a22a814..b9a6b15ae 100644 --- a/crates/typst-layout/src/math/stretch.rs +++ b/crates/typst-layout/src/math/stretch.rs @@ -37,7 +37,7 @@ pub fn stretch_fragment( ) { let size = fragment.size(); - let MathFragment::Glyph(ref mut glyph) = fragment else { return }; + let MathFragment::Glyph(glyph) = fragment else { return }; // Return if we attempt to stretch along an axis which isn't stretchable, // so that the original fragment isn't modified. diff --git a/crates/typst-library/src/engine.rs b/crates/typst-library/src/engine.rs index 43a7b4671..a85fc8ca2 100644 --- a/crates/typst-library/src/engine.rs +++ b/crates/typst-library/src/engine.rs @@ -47,7 +47,7 @@ impl Engine<'_> { } /// Runs tasks on the engine in parallel. - pub fn parallelize(&mut self, iter: P, f: F) -> impl Iterator + pub fn parallelize(&mut self, iter: P, f: F) -> impl Iterator + use where P: IntoIterator, I: Iterator, diff --git a/crates/typst-library/src/introspection/introspector.rs b/crates/typst-library/src/introspection/introspector.rs index 000fbd202..76a0faa35 100644 --- a/crates/typst-library/src/introspection/introspector.rs +++ b/crates/typst-library/src/introspection/introspector.rs @@ -327,7 +327,7 @@ where self.0.entry(key).or_default().push(value); } - fn take(&mut self, key: &K) -> Option> { + fn take(&mut self, key: &K) -> Option + use> { self.0.remove(key).map(|vec| vec.into_iter()) } } diff --git a/crates/typst-pdf/src/metadata.rs b/crates/typst-pdf/src/metadata.rs index 7c546b237..d51cb5335 100644 --- a/crates/typst-pdf/src/metadata.rs +++ b/crates/typst-pdf/src/metadata.rs @@ -9,7 +9,7 @@ use crate::convert::GlobalContext; pub(crate) fn build_metadata(gc: &GlobalContext) -> Metadata { let creator = format!("Typst {}", env!("CARGO_PKG_VERSION")); - let lang = gc.languages.iter().max_by_key(|(_, &count)| count).map(|(&l, _)| l); + let lang = gc.languages.iter().max_by_key(|&(_, &count)| count).map(|(&l, _)| l); let dir = if lang.map(Lang::dir) == Some(Dir::RTL) { TextDirection::RightToLeft diff --git a/crates/typst-utils/src/fat.rs b/crates/typst-utils/src/fat.rs index b31a2bb1e..40751532b 100644 --- a/crates/typst-utils/src/fat.rs +++ b/crates/typst-utils/src/fat.rs @@ -16,11 +16,11 @@ 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 { +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 +29,23 @@ 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 { +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<()> { +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. /// From c9c2315ad3a5fb7253a6abd8f4efbcb55f16b642 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 21 Jul 2025 14:55:27 +0200 Subject: [PATCH 05/11] Fix 2024 clippy warnings --- crates/typst-cli/src/server.rs | 2 +- crates/typst-cli/src/world.rs | 10 +++--- crates/typst-eval/src/access.rs | 5 ++- crates/typst-eval/src/import.rs | 10 +++--- crates/typst-eval/src/ops.rs | 5 ++- crates/typst-eval/src/rules.rs | 5 ++- crates/typst-html/src/rules.rs | 8 ++--- crates/typst-ide/src/analyze.rs | 10 +++--- crates/typst-ide/src/complete.rs | 5 ++- crates/typst-ide/src/jump.rs | 15 ++++----- crates/typst-ide/src/matchers.rs | 17 +++++----- crates/typst-ide/src/tooltip.rs | 10 +++--- crates/typst-layout/src/flow/block.rs | 5 ++- crates/typst-layout/src/flow/collect.rs | 5 ++- crates/typst-layout/src/grid/layouter.rs | 28 ++++++----------- crates/typst-layout/src/grid/lines.rs | 10 +++--- crates/typst-layout/src/grid/repeated.rs | 5 ++- crates/typst-layout/src/grid/rowspans.rs | 10 +++--- crates/typst-layout/src/inline/collect.rs | 5 ++- crates/typst-layout/src/inline/line.rs | 31 +++++++------------ crates/typst-layout/src/inline/linebreak.rs | 5 ++- crates/typst-layout/src/math/fragment.rs | 4 +-- crates/typst-layout/src/math/lr.rs | 10 +++--- crates/typst-layout/src/math/mod.rs | 5 ++- crates/typst-layout/src/math/run.rs | 15 ++++----- crates/typst-library/src/diag.rs | 5 ++- crates/typst-library/src/foundations/cast.rs | 5 ++- .../src/foundations/content/mod.rs | 5 ++- crates/typst-library/src/layout/corners.rs | 5 ++- .../typst-library/src/layout/grid/resolve.rs | 5 ++- crates/typst-library/src/layout/page.rs | 5 ++- crates/typst-library/src/layout/sides.rs | 5 ++- .../typst-library/src/model/bibliography.rs | 5 ++- crates/typst-library/src/model/reference.rs | 5 ++- crates/typst-library/src/text/font/book.rs | 9 ++---- crates/typst-library/src/text/lang.rs | 8 ++--- crates/typst-library/src/text/mod.rs | 5 ++- crates/typst-library/src/text/raw.rs | 5 ++- crates/typst-library/src/visualize/color.rs | 5 ++- crates/typst-macros/src/scope.rs | 8 ++--- crates/typst-macros/src/util.rs | 11 +++---- crates/typst-pdf/src/outline.rs | 5 ++- crates/typst-realize/src/lib.rs | 10 +++--- crates/typst-render/src/lib.rs | 5 ++- crates/typst-render/src/text.rs | 4 +-- crates/typst-svg/src/lib.rs | 5 ++- crates/typst-syntax/src/highlight.rs | 10 +++--- crates/typst-syntax/src/lexer.rs | 5 ++- crates/typst-syntax/src/node.rs | 4 +-- crates/typst-syntax/src/parser.rs | 15 ++++----- crates/typst-syntax/src/reparser.rs | 5 ++- docs/src/link.rs | 5 ++- tests/fuzz/src/compile.rs | 5 ++- 53 files changed, 162 insertions(+), 252 deletions(-) diff --git a/crates/typst-cli/src/server.rs b/crates/typst-cli/src/server.rs index 8910e0323..11c564e8d 100644 --- a/crates/typst-cli/src/server.rs +++ b/crates/typst-cli/src/server.rs @@ -162,7 +162,7 @@ impl Bucket { } /// Retrieves the current data in the bucket. - fn get(&self) -> MutexGuard { + fn get(&self) -> MutexGuard<'_, T> { self.mutex.lock() } diff --git a/crates/typst-cli/src/world.rs b/crates/typst-cli/src/world.rs index 8ad766b14..900199354 100644 --- a/crates/typst-cli/src/world.rs +++ b/crates/typst-cli/src/world.rs @@ -361,22 +361,20 @@ impl SlotCell { f: impl FnOnce(Vec, Option) -> FileResult, ) -> FileResult { // If we accessed the file already in this compilation, retrieve it. - if mem::replace(&mut self.accessed, true) { - if let Some(data) = &self.data { + if mem::replace(&mut self.accessed, true) + && let Some(data) = &self.data { return data.clone(); } - } // Read and hash the file. let result = timed!("loading file", load()); let fingerprint = timed!("hashing file", typst::utils::hash128(&result)); // If the file contents didn't change, yield the old processed data. - if mem::replace(&mut self.fingerprint, fingerprint) == fingerprint { - if let Some(data) = &self.data { + if mem::replace(&mut self.fingerprint, fingerprint) == fingerprint + && 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 22a6b7f3d..ddcc8b98b 100644 --- a/crates/typst-eval/src/access.rs +++ b/crates/typst-eval/src/access.rs @@ -29,11 +29,10 @@ impl Access for ast::Expr<'_> { 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) { - if let Ok(binding) = vm.scopes.get(&self) { + if vm.inspected == Some(span) + && 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/import.rs b/crates/typst-eval/src/import.rs index 1b1641487..138d7ccfe 100644 --- a/crates/typst-eval/src/import.rs +++ b/crates/typst-eval/src/import.rs @@ -46,15 +46,14 @@ impl Eval for ast::ModuleImport<'_> { // If there is a rename, import the source itself under that name. let new_name = self.new_name(); if let Some(new_name) = new_name { - if let ast::Expr::Ident(ident) = self.source() { - if ident.as_str() == new_name.as_str() { + 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", )); } - } // Define renamed module on the scope. vm.define(new_name, source.clone()); @@ -142,8 +141,8 @@ impl Eval for ast::ModuleImport<'_> { // it. // Warn on `import ...: x as x` - if let ast::ImportItem::Renamed(renamed_item) = &item { - if renamed_item.original_name().as_str() + 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!( @@ -151,7 +150,6 @@ impl Eval for ast::ModuleImport<'_> { "unnecessary import rename to same name", )); } - } vm.bind(item.bound_name(), binding.clone()); } diff --git a/crates/typst-eval/src/ops.rs b/crates/typst-eval/src/ops.rs index ebbd67430..9a8eb5239 100644 --- a/crates/typst-eval/src/ops.rs +++ b/crates/typst-eval/src/ops.rs @@ -76,13 +76,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 { - if let ast::Expr::FieldAccess(access) = lhs { + 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 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 eb6a1e6da..36fde561c 100644 --- a/crates/typst-eval/src/rules.rs +++ b/crates/typst-eval/src/rules.rs @@ -12,11 +12,10 @@ impl Eval for ast::SetRule<'_> { type Output = Styles; fn eval(self, vm: &mut Vm) -> SourceResult { - if let Some(condition) = self.condition() { - if !condition.eval(vm)?.cast::().at(condition.span())? { + if let Some(condition) = self.condition() + && !condition.eval(vm)?.cast::().at(condition.span())? { return Ok(Styles::new()); } - } let target = self.target(); let target = target diff --git a/crates/typst-html/src/rules.rs b/crates/typst-html/src/rules.rs index 3d215d56e..14885bd36 100644 --- a/crates/typst-html/src/rules.rs +++ b/crates/typst-html/src/rules.rs @@ -238,14 +238,12 @@ const QUOTE_RULE: ShowFn = |elem, _, styles| { if block { let mut blockquote = HtmlElem::new(tag::blockquote).with_body(Some(realized)); - if let Some(Attribution::Content(attribution)) = attribution { - if let Some(link) = attribution.to_packed::() { - if let LinkTarget::Dest(Destination::Url(url)) = &link.dest { + 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()); } - } - } realized = blockquote.pack().spanned(span); diff --git a/crates/typst-ide/src/analyze.rs b/crates/typst-ide/src/analyze.rs index e9fb8a7d7..e7fd8af8e 100644 --- a/crates/typst-ide/src/analyze.rs +++ b/crates/typst-ide/src/analyze.rs @@ -27,17 +27,15 @@ pub fn analyze_expr( ast::Expr::Numeric(v) => Value::numeric(v.get()), ast::Expr::Str(v) => Value::Str(v.get().into()), _ => { - if node.kind() == SyntaxKind::Contextual { - if let Some(child) = node.children().next_back() { + if node.kind() == SyntaxKind::Contextual + && let Some(child) = node.children().next_back() { return analyze_expr(world, &child); } - } - if let Some(parent) = node.parent() { - if parent.kind() == SyntaxKind::FieldAccess && node.index() > 0 { + if let Some(parent) = node.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 5b6d6fd97..6cde69f3c 100644 --- a/crates/typst-ide/src/complete.rs +++ b/crates/typst-ide/src/complete.rs @@ -1382,11 +1382,10 @@ impl<'a> CompletionContext<'a> { } } else if at { apply = Some(eco_format!("at(\"{label}\")")); - } else if label.starts_with('"') && self.after.starts_with('"') { - if let Some(trimmed) = label.strip_suffix('"') { + } 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 { diff --git a/crates/typst-ide/src/jump.rs b/crates/typst-ide/src/jump.rs index c9a53547a..f0035163b 100644 --- a/crates/typst-ide/src/jump.rs +++ b/crates/typst-ide/src/jump.rs @@ -36,8 +36,8 @@ pub fn jump_from_click( ) -> Option { // Try to find a link first. for (pos, item) in frame.items() { - if let FrameItem::Link(dest, size) = item { - if is_in_rect(*pos, *size, click) { + 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), @@ -46,7 +46,6 @@ pub fn jump_from_click( } }); } - } } // If there's no link, search for a jump target. @@ -54,11 +53,10 @@ pub fn jump_from_click( match item { FrameItem::Group(group) => { let pos = click - pos; - if let Some(clip) = &group.clip { - if !clip.contains(FillRule::NonZero, pos) { + if let Some(clip) = &group.clip + && !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. @@ -178,11 +176,10 @@ pub fn jump_from_cursor( /// Find the position of a span in a frame. fn find_in_frame(frame: &Frame, span: Span) -> Option { for &(mut pos, ref item) in frame.items() { - if let FrameItem::Group(group) = item { - if let Some(point) = find_in_frame(&group.frame, span) { + if let FrameItem::Group(group) = item + && 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 { diff --git a/crates/typst-ide/src/matchers.rs b/crates/typst-ide/src/matchers.rs index 93fdc5dd5..709d1d156 100644 --- a/crates/typst-ide/src/matchers.rs +++ b/crates/typst-ide/src/matchers.rs @@ -59,11 +59,10 @@ pub fn named_items( }; // Seeing the module itself. - if let Some((name, span)) = name_and_span { - if let Some(res) = recv(NamedItem::Module(&name, span, module)) { + if let Some((name, span)) = name_and_span + && let Some(res) = recv(NamedItem::Module(&name, span, module)) { return Some(res); } - } // Seeing the imported items. match imports { @@ -124,8 +123,8 @@ pub fn named_items( } if let Some(parent) = node.parent() { - if let Some(v) = parent.cast::() { - if node.prev_sibling_kind() != Some(SyntaxKind::In) { + 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)) { @@ -133,7 +132,6 @@ pub fn named_items( } } } - } if let Some(v) = parent.cast::().filter(|v| { // Check if the node is in the body of the closure. @@ -155,11 +153,10 @@ pub fn named_items( } } ast::Param::Spread(s) => { - if let Some(sink_ident) = s.sink_ident() { - if let Some(t) = recv(NamedItem::Var(sink_ident)) { + if let Some(sink_ident) = s.sink_ident() + && let Some(t) = recv(NamedItem::Var(sink_ident)) { return Some(t); } - } } } } @@ -216,7 +213,7 @@ impl<'a> NamedItem<'a> { /// Categorize an expression into common classes IDE functionality can operate /// on. -pub fn deref_target(node: LinkedNode) -> Option> { +pub fn deref_target(node: LinkedNode<'_>) -> Option> { // Move to the first ancestor that is an expression. let mut ancestor = node; while !ancestor.is::() { diff --git a/crates/typst-ide/src/tooltip.rs b/crates/typst-ide/src/tooltip.rs index e0d66a89b..700414637 100644 --- a/crates/typst-ide/src/tooltip.rs +++ b/crates/typst-ide/src/tooltip.rs @@ -66,11 +66,10 @@ fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { return Some(Tooltip::Text(plain_docs_sentence(docs))); } - if let &Value::Length(length) = value { - if let Some(tooltip) = length_tooltip(length) { + if let &Value::Length(length) = value + && let Some(tooltip) = length_tooltip(length) { return Some(tooltip); } - } } if expr.is_literal() { @@ -93,11 +92,10 @@ fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { last = Some((value, 1)); } - if let Some((_, count)) = last { - if count > 1 { + if let Some((_, count)) = last + && count > 1 { write!(pieces.last_mut().unwrap(), " (×{count})").unwrap(); } - } if iter.next().is_some() { pieces.push("...".into()); diff --git a/crates/typst-layout/src/flow/block.rs b/crates/typst-layout/src/flow/block.rs index d6cfe3a9e..11096dc7a 100644 --- a/crates/typst-layout/src/flow/block.rs +++ b/crates/typst-layout/src/flow/block.rs @@ -407,11 +407,10 @@ fn distribute<'a>( // If there is still something remaining, apply it to the // last region (it will overflow, but there's nothing else // we can do). - if !remaining.approx_empty() { - if let Some(last) = buf.last_mut() { + if !remaining.approx_empty() + && 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 76268b590..561b578bb 100644 --- a/crates/typst-layout/src/flow/collect.rs +++ b/crates/typst-layout/src/flow/collect.rs @@ -684,11 +684,10 @@ impl CachedCell { let input_hash = typst_utils::hash128(&input); let mut slot = self.0.borrow_mut(); - if let Some((hash, output)) = &*slot { - if *hash == input_hash { + if let Some((hash, output)) = &*slot + && *hash == input_hash { return output.clone(); } - } let output = f(input); *slot = Some((input_hash, output.clone())); diff --git a/crates/typst-layout/src/grid/layouter.rs b/crates/typst-layout/src/grid/layouter.rs index a5803f830..ee613f8f2 100644 --- a/crates/typst-layout/src/grid/layouter.rs +++ b/crates/typst-layout/src/grid/layouter.rs @@ -274,32 +274,29 @@ impl<'a> GridLayouter<'a> { pub fn layout(mut self, engine: &mut Engine) -> SourceResult { self.measure_columns(engine)?; - if let Some(footer) = &self.grid.footer { - if footer.repeated { + 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; } - } 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) - { - if next_header.range.contains(&y) { + && 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; } - } - if let Some(footer) = &self.grid.footer { - if footer.repeated && y >= footer.start { + 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(); @@ -307,7 +304,6 @@ impl<'a> GridLayouter<'a> { y = footer.end; continue; } - } self.layout_row(y, engine, 0)?; @@ -1283,15 +1279,13 @@ impl<'a> GridLayouter<'a> { // remeasure. if let Some([first, rest @ ..]) = frames.get(measurement_data.frames_in_previous_regions..) - { - if can_skip + && can_skip && 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 @@ -1529,8 +1523,8 @@ impl<'a> GridLayouter<'a> { // The latest rows have orphan prevention (headers) and no other rows // 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() { - if !last { + 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); @@ -1540,7 +1534,6 @@ impl<'a> GridLayouter<'a> { self.current.last_repeated_header_end = 0; } } - } if self .current @@ -1571,8 +1564,8 @@ impl<'a> GridLayouter<'a> { && self.current.could_progress_at_top; let mut laid_out_footer_start = None; - if !footer_would_be_widow { - if let Some(footer) = &self.grid.footer { + 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). @@ -1587,7 +1580,6 @@ impl<'a> GridLayouter<'a> { 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 d5da7e263..0b823c07d 100644 --- a/crates/typst-layout/src/grid/lines.rs +++ b/crates/typst-layout/src/grid/lines.rs @@ -291,13 +291,12 @@ pub fn vline_stroke_at_row( // We would then analyze the cell one column after (if at a gutter // 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) { - if parent.x < x { + 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; } - } } let (left_cell_stroke, left_cell_prioritized) = x @@ -416,8 +415,8 @@ pub fn hline_stroke_at_column( // We would then analyze the cell one column after (if at a gutter // 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) { - if parent.y < y { + 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 @@ -437,7 +436,6 @@ pub fn hline_stroke_at_column( 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/repeated.rs b/crates/typst-layout/src/grid/repeated.rs index 8db33df5e..573ef1a47 100644 --- a/crates/typst-layout/src/grid/repeated.rs +++ b/crates/typst-layout/src/grid/repeated.rs @@ -240,8 +240,8 @@ impl<'a> GridLayouter<'a> { self.current.initial_after_repeats = self.regions.size.y; } - if let Some(footer) = &self.grid.footer { - if footer.repeated && skipped_region { + 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; @@ -250,7 +250,6 @@ impl<'a> GridLayouter<'a> { .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 02ea14813..c31bfcb28 100644 --- a/crates/typst-layout/src/grid/rowspans.rs +++ b/crates/typst-layout/src/grid/rowspans.rs @@ -238,8 +238,8 @@ impl GridLayouter<'_> { // current row is dynamic and depends on the amount of upcoming // unbreakable cells (with or without a rowspan setting). let mut amount_unbreakable_rows = None; - if let Some(footer) = &self.grid.footer { - if !footer.repeated && current_row >= footer.start { + 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 @@ -247,7 +247,6 @@ impl GridLayouter<'_> { // have widow prevention. amount_unbreakable_rows = Some(self.grid.rows.len() - footer.start); } - } let row_group = self.simulate_unbreakable_row_group( current_row, @@ -1268,9 +1267,8 @@ fn subtract_end_sizes(sizes: &mut Vec, mut subtract: Abs) { while subtract > Abs::zero() && sizes.last().is_some_and(|&size| size <= subtract) { subtract -= sizes.pop().unwrap(); } - if subtract > Abs::zero() { - if let Some(last_size) = sizes.last_mut() { + if subtract > Abs::zero() + && 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 2744b31e0..1856cb13d 100644 --- a/crates/typst-layout/src/inline/collect.rs +++ b/crates/typst-layout/src/inline/collect.rs @@ -274,12 +274,11 @@ impl<'a> Collector<'a> { let segment_len = self.full.len() - prev; // Merge adjacent text segments with the same styles. - if let Some(Segment::Text(last_len, last_styles)) = self.segments.last_mut() { - if *last_styles == styles { + if let Some(Segment::Text(last_len, last_styles)) = self.segments.last_mut() + && *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 58162d12b..2d921b394 100644 --- a/crates/typst-layout/src/inline/line.rs +++ b/crates/typst-layout/src/inline/line.rs @@ -155,18 +155,16 @@ pub fn line<'a>( let mut items = collect_items(engine, p, range, trim); // 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)) { - if let Some(shaped) = items.first_text_mut() { + 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); } - } // Add a hyphen at the line end, if we ended on a soft hyphen. - if dash == Some(Dash::Soft) { - if let Some(shaped) = items.last_text_mut() { + if dash == Some(Dash::Soft) + && 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); @@ -218,11 +216,10 @@ fn collect_items<'a>( } // Add fallback text to expand the line height, if necessary. - if !items.iter().any(|item| matches!(item, Item::Text(_))) { - if let Some(fallback) = fallback { + if !items.iter().any(|item| matches!(item, Item::Text(_))) + && let Some(fallback) = fallback { items.push(fallback, usize::MAX); } - } items } @@ -461,9 +458,9 @@ pub fn commit( } // Handle hanging punctuation to the left. - if let Some(Item::Text(text)) = line.items.first() { - if let Some(glyph) = text.glyphs.first() { - if !text.dir.is_positive() + 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) { @@ -471,21 +468,17 @@ pub fn commit( offset -= amount; remaining += amount; } - } - } // Handle hanging punctuation to the right. - if let Some(Item::Text(text)) = line.items.last() { - if let Some(glyph) = text.glyphs.last() { - if text.dir.is_positive() + 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; } - } - } // 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 955360df1..e40027edb 100644 --- a/crates/typst-layout/src/inline/linebreak.rs +++ b/crates/typst-layout/src/inline/linebreak.rs @@ -136,13 +136,12 @@ fn linebreak_simple<'a>( // If the line doesn't fit anymore, we push the last fitting attempt // 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) { - if let Some((last_attempt, last_end)) = last.take() { + 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()); } - } // 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 diff --git a/crates/typst-layout/src/math/fragment.rs b/crates/typst-layout/src/math/fragment.rs index 758dd401f..877158100 100644 --- a/crates/typst-layout/src/math/fragment.rs +++ b/crates/typst-layout/src/math/fragment.rs @@ -681,7 +681,7 @@ 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 +810,7 @@ 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 cba794935..59dac03af 100644 --- a/crates/typst-layout/src/math/lr.rs +++ b/crates/typst-layout/src/math/lr.rs @@ -21,11 +21,10 @@ pub fn layout_lr( } // Extract implicit LrElem. - if let Some(lr) = body.to_packed::() { - if lr.size.get(styles).is_one() { + if let Some(lr) = body.to_packed::() + && lr.size.get(styles).is_one() { body = &lr.body; } - } let mut fragments = ctx.layout_into_fragments(body, styles)?; @@ -55,12 +54,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 { - if glyph.mid_stretched == Some(false) { + if let MathFragment::Glyph(glyph) = fragment + && 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/mod.rs b/crates/typst-layout/src/math/mod.rs index 390835067..5ee3e14a8 100644 --- a/crates/typst-layout/src/math/mod.rs +++ b/crates/typst-layout/src/math/mod.rs @@ -603,14 +603,13 @@ fn layout_h( ctx: &mut MathContext, styles: StyleChain, ) -> SourceResult<()> { - if let Spacing::Rel(rel) = elem.amount { - if rel.rel.is_zero() { + if let Spacing::Rel(rel) = elem.amount + && 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/run.rs b/crates/typst-layout/src/math/run.rs index 161fa1062..fb206dc2e 100644 --- a/crates/typst-layout/src/math/run.rs +++ b/crates/typst-layout/src/math/run.rs @@ -87,11 +87,10 @@ impl MathRun { // Insert spacing between the last and this non-ignorant item. if !fragment.is_ignorant() { - if let Some(i) = last { - if let Some(s) = spacing(&resolved[i], space.take(), &fragment) { + if let Some(i) = last + && let Some(s) = spacing(&resolved[i], space.take(), &fragment) { resolved.insert(i + 1, s); } - } last = Some(resolved.len()); } @@ -123,11 +122,10 @@ impl MathRun { 1 + self.0.iter().filter(|f| matches!(f, MathFragment::Linebreak)).count(); // A linebreak at the very end does not introduce an extra row. - if let Some(f) = self.0.last() { - if matches!(f, MathFragment::Linebreak) { + if let Some(f) = self.0.last() + && matches!(f, MathFragment::Linebreak) { count -= 1 } - } count } @@ -344,11 +342,10 @@ impl MathRun { descent = Abs::zero(); space_is_visible = true; - if let Some(f_next) = iter.peek() { - if !is_space(f_next) { + if let Some(f_next) = iter.peek() + && !is_space(f_next) { items.push(InlineItem::Space(Abs::zero(), true)); } - } } else { space_is_visible = false; } diff --git a/crates/typst-library/src/diag.rs b/crates/typst-library/src/diag.rs index 41b92ed65..611ec6338 100644 --- a/crates/typst-library/src/diag.rs +++ b/crates/typst-library/src/diag.rs @@ -296,14 +296,13 @@ impl Trace for SourceResult { let Some(trace_range) = world.range(span) else { return errors }; for error in errors.make_mut().iter_mut() { // Skip traces that surround the error. - if let Some(error_range) = world.range(error.span) { - if error.span.id() == span.id() + 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; } - } error.trace.push(Spanned::new(make_point(), span)); } diff --git a/crates/typst-library/src/foundations/cast.rs b/crates/typst-library/src/foundations/cast.rs index 5e0ba688e..17d194e1a 100644 --- a/crates/typst-library/src/foundations/cast.rs +++ b/crates/typst-library/src/foundations/cast.rs @@ -347,14 +347,13 @@ impl CastInfo { msg.hint(eco_format!("use `label({})` to create a label", s.repr())); } } - } else if let Value::Decimal(_) = found { - if !matching_type && parts.iter().any(|p| p == "float") { + } 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 \ decimal to a float with `float(value)`" )); } - } msg } diff --git a/crates/typst-library/src/foundations/content/mod.rs b/crates/typst-library/src/foundations/content/mod.rs index 7ba790d88..f5e8314d8 100644 --- a/crates/typst-library/src/foundations/content/mod.rs +++ b/crates/typst-library/src/foundations/content/mod.rs @@ -174,11 +174,10 @@ impl Content { id: u8, styles: Option, ) -> Result { - if id == 255 { - if let Some(label) = self.label() { + if id == 255 + && 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/layout/corners.rs b/crates/typst-library/src/layout/corners.rs index fe69126a4..e47fee1e7 100644 --- a/crates/typst-library/src/layout/corners.rs +++ b/crates/typst-library/src/layout/corners.rs @@ -150,11 +150,10 @@ where T: PartialEq + IntoValue, { fn into_value(self) -> Value { - if self.is_uniform() { - if let Some(top_left) = self.top_left { + if self.is_uniform() + && 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/grid/resolve.rs b/crates/typst-library/src/layout/grid/resolve.rs index f3004088e..edf50cdd2 100644 --- a/crates/typst-library/src/layout/grid/resolve.rs +++ b/crates/typst-library/src/layout/grid/resolve.rs @@ -2098,14 +2098,13 @@ fn check_for_conflicting_cell_row( ); } - if let Some((_, _, footer)) = footer { - if cell_y < footer.end && cell_y + rowspan > footer.start { + 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" ); } - } Ok(()) } diff --git a/crates/typst-library/src/layout/page.rs b/crates/typst-library/src/layout/page.rs index a0b1c6fec..ab8cc8ea4 100644 --- a/crates/typst-library/src/layout/page.rs +++ b/crates/typst-library/src/layout/page.rs @@ -530,11 +530,10 @@ cast! { Margin, self => { let two_sided = self.two_sided.unwrap_or(false); - if !two_sided && self.sides.is_uniform() { - if let Some(left) = self.sides.left { + if !two_sided && self.sides.is_uniform() + && let Some(left) = self.sides.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/sides.rs b/crates/typst-library/src/layout/sides.rs index e04b63d98..1147eeb77 100644 --- a/crates/typst-library/src/layout/sides.rs +++ b/crates/typst-library/src/layout/sides.rs @@ -184,11 +184,10 @@ where T: PartialEq + IntoValue, { fn into_value(self) -> Value { - if self.is_uniform() { - if let Some(left) = self.left { + if self.is_uniform() + && 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/model/bibliography.rs b/crates/typst-library/src/model/bibliography.rs index 188af4da1..ef7e69273 100644 --- a/crates/typst-library/src/model/bibliography.rs +++ b/crates/typst-library/src/model/bibliography.rs @@ -927,12 +927,11 @@ impl ElemRenderer<'_> { _ => {} } - if let Some(hayagriva::ElemMeta::Entry(i)) = elem.meta { - if let Some(location) = (self.link)(i) { + if let Some(hayagriva::ElemMeta::Entry(i)) = elem.meta + && 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/reference.rs b/crates/typst-library/src/model/reference.rs index f7922ef3e..cf1b43da0 100644 --- a/crates/typst-library/src/model/reference.rs +++ b/crates/typst-library/src/model/reference.rs @@ -210,12 +210,11 @@ impl Synthesize for Packed { elem.citation = Some(Some(citation)); elem.element = Some(None); - if !BibliographyElem::has(engine, elem.target) { - if let Ok(found) = engine.introspector.query_label(elem.target).cloned() { + if !BibliographyElem::has(engine, elem.target) + && 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/text/font/book.rs b/crates/typst-library/src/text/font/book.rs index d0c821b39..374b83908 100644 --- a/crates/typst-library/src/text/font/book.rs +++ b/crates/typst-library/src/text/font/book.rs @@ -284,11 +284,9 @@ impl FontInfo { .raw_face() .table(Tag::from_bytes(b"OS/2")) .and_then(|os2| os2.get(32..45)) - { - if matches!(panose, [2, 2..=10, ..]) { + && matches!(panose, [2, 2..=10, ..]) { flags.insert(FontFlags::SERIF); } - } Some(FontInfo { family, @@ -397,11 +395,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)) { - if let Some(stripped) = t.strip_suffix(SEPARATORS) { + if let Some(t) = MODIFIERS.iter().find_map(|s| t.strip_suffix(s)) + && let Some(stripped) = t.strip_suffix(SEPARATORS) { trimmed = stripped; } - } } // Apply style suffix trimming. diff --git a/crates/typst-library/src/text/lang.rs b/crates/typst-library/src/text/lang.rs index 4f8d1e93f..d396eef8b 100644 --- a/crates/typst-library/src/text/lang.rs +++ b/crates/typst-library/src/text/lang.rs @@ -144,17 +144,15 @@ cast! { self => self.as_str().into_value(), string: EcoString => { let result = Self::from_str(&string); - if result.is_err() { - if let Some((lang, region)) = string.split_once('-') { - if Lang::from_str(lang).is_ok() && Region::from_str(region).is_ok() { + if result.is_err() + && let Some((lang, region)) = string.split_once('-') + && Lang::from_str(lang).is_ok() && Region::from_str(region).is_ok() { return result .hint(eco_format!( "you should leave only \"{}\" in the `lang` parameter and specify \"{}\" in the `region` parameter", lang, region, )); } - } - } result? } diff --git a/crates/typst-library/src/text/mod.rs b/crates/typst-library/src/text/mod.rs index c2efe210b..5f2330cbd 100644 --- a/crates/typst-library/src/text/mod.rs +++ b/crates/typst-library/src/text/mod.rs @@ -270,15 +270,14 @@ pub struct TextElem { /// ``` #[parse({ let paint: Option> = args.named_or_find("fill")?; - if let Some(paint) = &paint { - if paint.v.relative() == Smart::Custom(RelativeTo::Self_) { + if let Some(paint) = &paint + && paint.v.relative() == Smart::Custom(RelativeTo::Self_) { bail!( paint.span, "gradients and tilings on text must be relative to the parent"; hint: "make sure to set `relative: auto` on your text fill" ); } - } paint.map(|paint| paint.v) })] #[default(Color::BLACK.into())] diff --git a/crates/typst-library/src/text/raw.rs b/crates/typst-library/src/text/raw.rs index 0e61a8ef1..1677d3d07 100644 --- a/crates/typst-library/src/text/raw.rs +++ b/crates/typst-library/src/text/raw.rs @@ -750,11 +750,10 @@ fn preprocess( styles: StyleChain, span: Span, ) -> EcoVec<(EcoString, Span)> { - if let RawContent::Lines(lines) = text { - if lines.iter().all(|(s, _)| !s.contains('\t')) { + if let RawContent::Lines(lines) = text + && 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/visualize/color.rs b/crates/typst-library/src/visualize/color.rs index dd0287d4b..9c8eacaf5 100644 --- a/crates/typst-library/src/visualize/color.rs +++ b/crates/typst-library/src/visualize/color.rs @@ -1123,8 +1123,8 @@ impl Color { } // Ensure that the hue circle is traversed in the short direction. - if let Some(index) = space.hue_index() { - if (c0[index] - c1[index]).abs() > 180.0 { + 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 { @@ -1132,7 +1132,6 @@ impl Color { }; m[index] = (w0 * h0 + w1 * h1) / (w0 + w1); } - } m } else { diff --git a/crates/typst-macros/src/scope.rs b/crates/typst-macros/src/scope.rs index 392ab1a53..2eac76b53 100644 --- a/crates/typst-macros/src/scope.rs +++ b/crates/typst-macros/src/scope.rs @@ -14,14 +14,12 @@ pub fn scope(_: TokenStream, item: syn::Item) -> Result { let self_ty = &item.self_ty; let mut primitive_ident_ext = None; - if let syn::Type::Path(syn::TypePath { path, .. }) = self_ty.as_ref() { - if let Some(ident) = path.get_ident() { - if is_primitive(ident) { + 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); } - } - } let self_ty_expr = match &primitive_ident_ext { None => quote! { #self_ty }, diff --git a/crates/typst-macros/src/util.rs b/crates/typst-macros/src/util.rs index e8c0910b6..87e398c97 100644 --- a/crates/typst-macros/src/util.rs +++ b/crates/typst-macros/src/util.rs @@ -27,18 +27,15 @@ pub fn documentation(attrs: &[syn::Attribute]) -> String { // Parse doc comments. for attr in attrs { - if let syn::Meta::NameValue(meta) = &attr.meta { - if meta.path.is_ident("doc") { - if let syn::Expr::Lit(lit) = &meta.value { - if let syn::Lit::Str(string) = &lit.lit { + 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'); } - } - } - } } doc.trim().into() diff --git a/crates/typst-pdf/src/outline.rs b/crates/typst-pdf/src/outline.rs index f73822c4b..e95bf67fb 100644 --- a/crates/typst-pdf/src/outline.rs +++ b/crates/typst-pdf/src/outline.rs @@ -21,14 +21,13 @@ pub(crate) fn build_outline(gc: &GlobalContext) -> Outline { let elements = &gc.document.introspector.query(&HeadingElem::ELEM.select()); for elem in elements.iter() { - if let Some(page_ranges) = &gc.options.page_ranges { - if !page_ranges + 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; } - } let heading = elem.to_packed::().unwrap(); let leaf = HeadingNode::leaf(heading); diff --git a/crates/typst-realize/src/lib.rs b/crates/typst-realize/src/lib.rs index f3f071505..cbb3ac21d 100644 --- a/crates/typst-realize/src/lib.rs +++ b/crates/typst-realize/src/lib.rs @@ -307,12 +307,11 @@ fn visit_kind_rules<'a>( visit_regex_match(s, &[(content, styles)], m)?; return Ok(true); } - } else if let Some(elem) = content.to_packed::() { - if let Some(m) = find_regex_match_in_str(&elem.text, styles) { + } 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); } - } } else { // Transparently wrap mathy content into equations. if content.can::() && !content.is::() { @@ -1092,11 +1091,10 @@ fn find_regex_match_in_elems<'a>( } let linebreak = content.is::(); - if linebreak { - if let SpaceState::Space(_) = space { + 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 2c57fe2db..5a993dbb9 100644 --- a/crates/typst-render/src/lib.rs +++ b/crates/typst-render/src/lib.rs @@ -193,8 +193,8 @@ fn render_group(canvas: &mut sk::Pixmap, state: State, pos: Point, group: &Group let mut mask = state.mask; let storage; - if let Some(clip_curve) = group.clip.as_ref() { - if let Some(path) = shape::convert_curve(clip_curve) + 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 { @@ -226,7 +226,6 @@ fn render_group(canvas: &mut sk::Pixmap, state: State, pos: Point, group: &Group mask = Some(&storage); } - } render_frame(canvas, state.with_mask(mask), &group.frame); } diff --git a/crates/typst-render/src/text.rs b/crates/typst-render/src/text.rs index 55fe04b51..a56528220 100644 --- a/crates/typst-render/src/text.rs +++ b/crates/typst-render/src/text.rs @@ -87,8 +87,7 @@ fn render_outline_glyph( if let Some(FixedStroke { paint, thickness, cap, join, dash, miter_limit }) = &text.stroke - { - if thickness.to_f32() > 0.0 { + && thickness.to_f32() > 0.0 { let dash = dash.as_ref().and_then(shape::to_sk_dash_pattern); let paint = paint::to_sk_paint( @@ -110,7 +109,6 @@ fn render_outline_glyph( canvas.stroke_path(&path, &paint, &stroke, ts, state.mask); } - } return Some(()); } diff --git a/crates/typst-svg/src/lib.rs b/crates/typst-svg/src/lib.rs index 5b6db69da..85bd5d7cb 100644 --- a/crates/typst-svg/src/lib.rs +++ b/crates/typst-svg/src/lib.rs @@ -340,12 +340,11 @@ impl<'a> SVGRenderer<'a> { Destination::Location(loc) => { // TODO: Location links on the same page could also be supported // outside of HTML. - if let Some(introspector) = self.introspector { - if let Some(id) = introspector.html_id(*loc) { + 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}")); } - } } Destination::Position(_) => { // TODO: Links on the same page could be supported. diff --git a/crates/typst-syntax/src/highlight.rs b/crates/typst-syntax/src/highlight.rs index cd815694d..9754312b3 100644 --- a/crates/typst-syntax/src/highlight.rs +++ b/crates/typst-syntax/src/highlight.rs @@ -300,8 +300,8 @@ pub fn highlight(node: &LinkedNode) -> Option { fn highlight_ident(node: &LinkedNode) -> Option { // Are we directly before an argument list? let next_leaf = node.next_leaf(); - if let Some(next) = &next_leaf { - if node.range().end == next.offset() + if let Some(next) = &next_leaf + && node.range().end == next.offset() && ((next.kind() == SyntaxKind::LeftParen && matches!( next.parent_kind(), @@ -312,7 +312,6 @@ fn highlight_ident(node: &LinkedNode) -> Option { { return Some(Tag::Function); } - } // Are we in math? if node.kind() == SyntaxKind::MathIdent { @@ -379,14 +378,13 @@ pub fn highlight_html(root: &SyntaxNode) -> String { /// Highlight one source node, emitting HTML. fn highlight_html_impl(html: &mut String, node: &LinkedNode) { let mut span = false; - if let Some(tag) = highlight(node) { - if tag != Tag::Error { + if let Some(tag) = highlight(node) + && 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 82f65cd36..9da45958f 100644 --- a/crates/typst-syntax/src/lexer.rs +++ b/crates/typst-syntax/src/lexer.rs @@ -783,11 +783,10 @@ impl Lexer<'_> { let ident = self.s.from(start); let prev = self.s.get(0..start); - if !prev.ends_with(['.', '@']) || prev.ends_with("..") { - if let Some(keyword) = keyword(ident) { + if (!prev.ends_with(['.', '@']) || prev.ends_with("..")) + && let Some(keyword) = keyword(ident) { return keyword; } - } if ident == "_" { SyntaxKind::Underscore diff --git a/crates/typst-syntax/src/node.rs b/crates/typst-syntax/src/node.rs index 948657ca4..15c96b08f 100644 --- a/crates/typst-syntax/src/node.rs +++ b/crates/typst-syntax/src/node.rs @@ -733,11 +733,9 @@ impl<'a> LinkedNode<'a> { if children .peek() .is_none_or(|next| next.span().number() > span.number()) - { - if let Some(found) = child.find(span) { + && let Some(found) = child.find(span) { return Some(found); } - } } } diff --git a/crates/typst-syntax/src/parser.rs b/crates/typst-syntax/src/parser.rs index b452c2c09..22f073601 100644 --- a/crates/typst-syntax/src/parser.rs +++ b/crates/typst-syntax/src/parser.rs @@ -442,14 +442,13 @@ fn math_unparen(p: &mut Parser, m: Marker) { return; } - if let [first, .., last] = node.children_mut() { - if first.text() == "(" && last.text() == ")" { + 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); } - } } /// The unicode math class of a string. Only returns `Some` if `text` has @@ -1199,11 +1198,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, - } { - if !state.seen.insert(key.clone()) { + } + && !state.seen.insert(key.clone()) { node.convert_to_error(eco_format!("duplicate key: {key}")); } - } p.wrap(m, pair_kind); state.maybe_just_parens = false; @@ -1855,8 +1853,8 @@ impl<'s> Parser<'s> { self.nl_mode = mode; func(self); self.nl_mode = previous; - if let Some(newline) = self.token.newline { - if 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) { @@ -1865,7 +1863,6 @@ impl<'s> Parser<'s> { 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 55555c96e..2df606310 100644 --- a/crates/typst-syntax/src/reparser.rs +++ b/crates/typst-syntax/src/reparser.rs @@ -70,14 +70,13 @@ fn try_reparse( } // If the child is a block, try to reparse the block. - if child.kind().is_block() { - if let Some(newborn) = reparse_block(text, new_range.clone()) { + 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); } - } } // Does the child overlap with the edit? diff --git a/docs/src/link.rs b/docs/src/link.rs index 2e836b6ce..b883399e5 100644 --- a/docs/src/link.rs +++ b/docs/src/link.rs @@ -96,12 +96,11 @@ fn resolve_definition(head: &str, base: &str) -> StrResult { if let Ok(field) = value.field(next, ()) { route.push_str("/#definitions-"); route.push_str(next); - if let Some(next) = parts.next() { - if field.cast::().is_ok_and(|func| func.param(next).is_some()) { + if let Some(next) = parts.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/tests/fuzz/src/compile.rs b/tests/fuzz/src/compile.rs index 945e9fce8..1bc85fd62 100644 --- a/tests/fuzz/src/compile.rs +++ b/tests/fuzz/src/compile.rs @@ -66,10 +66,9 @@ impl World for FuzzWorld { fuzz_target!(|text: &str| { let world = FuzzWorld::new(text); - if let Ok(document) = typst::compile::(&world).output { - if let Some(page) = document.pages.first() { + if let Ok(document) = typst::compile::(&world).output + && let Some(page) = document.pages.first() { std::hint::black_box(typst_render::render(page, 1.0)); } - } comemo::evict(10); }); From e81a5a6ef205403c4271d2a9503a1f0b70e1cc2d Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 21 Jul 2025 15:11:36 +0200 Subject: [PATCH 06/11] Yeet `if_chain` macro --- Cargo.lock | 8 -- Cargo.toml | 1 - crates/typst-eval/Cargo.toml | 1 - crates/typst-eval/src/code.rs | 15 ++- crates/typst-eval/src/rules.rs | 12 +-- crates/typst-ide/Cargo.toml | 1 - crates/typst-ide/src/complete.rs | 169 +++++++++++++------------------ crates/typst-ide/src/tooltip.rs | 82 +++++++-------- 8 files changed, 118 insertions(+), 171 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index dcd154367..49a7c2b63 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1198,12 +1198,6 @@ dependencies = [ "icu_properties", ] -[[package]] -name = "if_chain" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" - [[package]] name = "image" version = "0.25.5" @@ -2943,7 +2937,6 @@ version = "0.13.1" dependencies = [ "comemo", "ecow", - "if_chain", "indexmap 2.7.1", "stacker", "toml", @@ -2991,7 +2984,6 @@ version = "0.13.1" dependencies = [ "comemo", "ecow", - "if_chain", "once_cell", "pathdiff", "serde", diff --git a/Cargo.toml b/Cargo.toml index 43a077ddb..08c6a8c8b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,7 +68,6 @@ icu_provider = { version = "1.4", features = ["sync"] } icu_provider_adapters = "1.4" icu_provider_blob = "1.4" icu_segmenter = { version = "1.4", features = ["serde"] } -if_chain = "1" image = { version = "0.25.5", default-features = false, features = ["png", "jpeg", "gif", "webp"] } indexmap = { version = "2", features = ["serde"] } infer = { version = "0.19.0", default-features = false } diff --git a/crates/typst-eval/Cargo.toml b/crates/typst-eval/Cargo.toml index 12a6a6a46..b39382ffe 100644 --- a/crates/typst-eval/Cargo.toml +++ b/crates/typst-eval/Cargo.toml @@ -20,7 +20,6 @@ typst-timing = { workspace = true } typst-utils = { workspace = true } comemo = { workspace = true } ecow = { workspace = true } -if_chain = { workspace = true } indexmap = { workspace = true } toml = { workspace = true } unicode-segmentation = { workspace = true } diff --git a/crates/typst-eval/src/code.rs b/crates/typst-eval/src/code.rs index 9078418e4..1930ebc48 100644 --- a/crates/typst-eval/src/code.rs +++ b/crates/typst-eval/src/code.rs @@ -324,22 +324,19 @@ impl Eval for ast::FieldAccess<'_> { }; // Check whether this is a get rule field access. - if_chain::if_chain! { - if let Value::Func(func) = &value; - if let Some(element) = func.element(); - if let Some(id) = element.field_id(&field); - let styles = vm.context.styles().at(field.span()); - if let Ok(value) = element.field_from_styles( + 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(), - ); - then { + ) { // 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/rules.rs b/crates/typst-eval/src/rules.rs index 36fde561c..bf4a80780 100644 --- a/crates/typst-eval/src/rules.rs +++ b/crates/typst-eval/src/rules.rs @@ -57,12 +57,11 @@ 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_chain::if_chain! { - if let Some(Selector::Elem(elem, _)) = recipe.selector(); - if *elem == Element::of::(); - if let Transformation::Style(styles) = recipe.transform(); - if styles.has(BlockElem::above) || styles.has(BlockElem::below); - then { + 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"; @@ -70,5 +69,4 @@ fn check_show_par_set_block(vm: &mut Vm, recipe: &Recipe) { hint: "this is specific to paragraphs as they are not considered blocks anymore" )) } - } } diff --git a/crates/typst-ide/Cargo.toml b/crates/typst-ide/Cargo.toml index 20162e836..e7918e634 100644 --- a/crates/typst-ide/Cargo.toml +++ b/crates/typst-ide/Cargo.toml @@ -17,7 +17,6 @@ typst = { workspace = true } typst-eval = { workspace = true } comemo = { workspace = true } ecow = { workspace = true } -if_chain = { workspace = true } pathdiff = { workspace = true } serde = { workspace = true } unscanny = { workspace = true } diff --git a/crates/typst-ide/src/complete.rs b/crates/typst-ide/src/complete.rs index 6cde69f3c..a974eb313 100644 --- a/crates/typst-ide/src/complete.rs +++ b/crates/typst-ide/src/complete.rs @@ -3,7 +3,6 @@ use std::collections::{BTreeMap, HashSet}; use std::ffi::OsStr; use ecow::{eco_format, EcoString}; -use if_chain::if_chain; use serde::{Deserialize, Serialize}; use typst::foundations::{ fields_on, repr, AutoValue, CastInfo, Func, Label, NoneValue, ParamInfo, Repr, @@ -145,27 +144,23 @@ fn complete_markup(ctx: &mut CompletionContext) -> bool { } // Behind a half-completed binding: "#let x = |". - if_chain! { - if let Some(prev) = ctx.leaf.prev_leaf(); - if prev.kind() == SyntaxKind::Eq; - if prev.parent_kind() == Some(SyntaxKind::LetBinding); - then { + 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; } - } // Behind a half-completed context block: "#context |". - if_chain! { - if let Some(prev) = ctx.leaf.prev_leaf(); - if prev.kind() == SyntaxKind::Context; - then { + if let Some(prev) = ctx.leaf.prev_leaf() + && prev.kind() == SyntaxKind::Context + { ctx.from = ctx.cursor; code_completions(ctx, false); return true; } - } // Directly after a raw block. let mut s = Scanner::new(ctx.text); @@ -373,38 +368,34 @@ fn complete_field_accesses(ctx: &mut CompletionContext) -> bool { ); // Behind an expression plus dot: "emoji.|". - if_chain! { - if ctx.leaf.kind() == SyntaxKind::Dot + if (ctx.leaf.kind() == SyntaxKind::Dot || (matches!(ctx.leaf.kind(), SyntaxKind::Text | SyntaxKind::MathText) - && ctx.leaf.text() == "."); - if ctx.leaf.range().end == ctx.cursor; - if let Some(prev) = ctx.leaf.prev_sibling(); - if !in_markup || prev.range().end == ctx.leaf.range().start; - if prev.is::(); - if prev.parent_kind() != Some(SyntaxKind::Markup) || - prev.prev_sibling_kind() == Some(SyntaxKind::Hash); - if let Some((value, styles)) = analyze_expr(ctx.world, &prev).into_iter().next(); - then { + && 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)) + && let Some((value, styles)) = analyze_expr(ctx.world, &prev).into_iter().next() + { ctx.from = ctx.cursor; field_access_completions(ctx, &value, &styles); return true; } - } // Behind a started field access: "emoji.fa|". - if_chain! { - if ctx.leaf.kind() == SyntaxKind::Ident; - if let Some(prev) = ctx.leaf.prev_sibling(); - if prev.kind() == SyntaxKind::Dot; - if let Some(prev_prev) = prev.prev_sibling(); - if prev_prev.is::(); - if let Some((value, styles)) = analyze_expr(ctx.world, &prev_prev).into_iter().next(); - then { + 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; } - } false } @@ -507,14 +498,10 @@ 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_chain! { - if matches!( - ctx.leaf.parent_kind(), - Some(SyntaxKind::ModuleImport | SyntaxKind::ModuleInclude) - ); - if let Some(ast::Expr::Str(str)) = ctx.leaf.cast(); - let value = str.get(); - then { + 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(':'); @@ -524,41 +511,36 @@ fn complete_imports(ctx: &mut CompletionContext) -> bool { } return true; } - } // Behind an import list: // "#import "path.typ": |", // "#import "path.typ": a, b, |". - if_chain! { - if let Some(prev) = ctx.leaf.prev_sibling(); - if let Some(ast::Expr::ModuleImport(import)) = prev.get().cast(); - if let Some(ast::Imports::Items(items)) = import.imports(); - if let Some(source) = prev.children().find(|child| child.is::()); - then { + 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; } - } // Behind a half-started identifier in an import list: // "#import "path.typ": thi|", - if_chain! { - if ctx.leaf.kind() == SyntaxKind::Ident; - if let Some(parent) = ctx.leaf.parent(); - if parent.kind() == SyntaxKind::ImportItemPath; - if let Some(grand) = parent.parent(); - if grand.kind() == SyntaxKind::ImportItems; - if let Some(great) = grand.parent(); - if let Some(ast::Expr::ModuleImport(import)) = great.get().cast(); - if let Some(ast::Imports::Items(items)) = import.imports(); - if let Some(source) = great.children().find(|child| child.is::()); - then { + if ctx.leaf.kind() == SyntaxKind::Ident + && let Some(parent) = ctx.leaf.parent() + && parent.kind() == SyntaxKind::ImportItemPath + && let Some(grand) = parent.parent() + && grand.kind() == SyntaxKind::ImportItems + && let Some(great) = grand.parent() + && 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; } - } false } @@ -607,16 +589,14 @@ fn complete_rules(ctx: &mut CompletionContext) -> bool { } // Behind a half-completed show rule: "show strong: |". - if_chain! { - if let Some(prev) = ctx.leaf.prev_leaf(); - if matches!(prev.kind(), SyntaxKind::Colon); - if matches!(prev.parent_kind(), Some(SyntaxKind::ShowRule)); - then { + 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; } - } false } @@ -682,27 +662,26 @@ 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_chain! { - if let Some(parent) = ctx.leaf.parent(); - if let Some(parent) = match parent.kind() { + 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), - }; - if let Some(args) = parent.get().cast::(); - if let Some(grand) = parent.parent(); - if let Some(expr) = grand.get().cast::(); - let set = matches!(expr, ast::Expr::SetRule(_)); - if let Some(callee) = match expr { + } + && let Some(args) = parent.get().cast::() + && let Some(grand) = parent.parent() + && let Some(expr) = grand.get().cast::() + && let set = matches!(expr, ast::Expr::SetRule(_)) + && let Some(callee) = match expr { ast::Expr::FuncCall(call) => Some(call.callee()), ast::Expr::SetRule(set) => Some(set.target()), _ => None, - }; - then { + } + { (callee, set, args, parent) } else { return false; - } - }; + }; // Find the piece of syntax that decides what we're completing. let mut deciding = ctx.leaf.clone(); @@ -718,11 +697,10 @@ fn complete_params(ctx: &mut CompletionContext) -> bool { } // Parameter values: "func(param:|)", "func(param: |)". - if_chain! { - if deciding.kind() == SyntaxKind::Colon; - if let Some(prev) = deciding.prev_leaf(); - if let Some(param) = prev.get().cast::(); - then { + 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()); } @@ -730,13 +708,11 @@ fn complete_params(ctx: &mut CompletionContext) -> bool { named_param_value_completions(ctx, callee, ¶m); return true; } - } // Parameters: "func(|)", "func(hi|)", "func(12,|)". - if_chain! { - if matches!(deciding.kind(), SyntaxKind::LeftParen | SyntaxKind::Comma); - if deciding.kind() != SyntaxKind::Comma || deciding.range().end < ctx.cursor; - then { + 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()); } @@ -744,7 +720,6 @@ fn complete_params(ctx: &mut CompletionContext) -> bool { param_completions(ctx, callee, set, args, args_linked); return true; } - } false } @@ -1104,15 +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_chain! { - if let Some(expr) = parent.get().cast::(); - if let ast::Expr::ShowRule(show) = expr; - if let Some(ast::Expr::FieldAccess(field)) = show.selector(); - if field.field().as_str() == "equation"; - then { + 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; } - } node = parent; } false diff --git a/crates/typst-ide/src/tooltip.rs b/crates/typst-ide/src/tooltip.rs index 700414637..078465206 100644 --- a/crates/typst-ide/src/tooltip.rs +++ b/crates/typst-ide/src/tooltip.rs @@ -1,7 +1,6 @@ use std::fmt::Write; use ecow::{eco_format, EcoString}; -use if_chain::if_chain; use typst::engine::Sink; use typst::foundations::{repr, Binding, Capturer, CastInfo, Repr, Value}; use typst::layout::{Length, PagedDocument}; @@ -107,20 +106,18 @@ fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { /// Tooltips for imports. fn import_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { - if_chain! { - if leaf.kind() == SyntaxKind::Star; - if let Some(parent) = leaf.parent(); - if let Some(import) = parent.cast::(); - if let Some(node) = parent.find(import.source().span()); - if let Some(value) = analyze_import(world, &node); - if let Some(scope) = value.scope(); - then { + 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}"))); } - } None } @@ -188,51 +185,46 @@ fn label_tooltip(document: &PagedDocument, leaf: &LinkedNode) -> Option /// Tooltips for components of a named parameter. fn named_param_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { - let (func, named) = if_chain! { + let (func, named) = // Ensure that we are in a named pair in the arguments to a function // call or set rule. - if let Some(parent) = leaf.parent(); - if let Some(named) = parent.cast::(); - if let Some(grand) = parent.parent(); - if matches!(grand.kind(), SyntaxKind::Args); - if let Some(grand_grand) = grand.parent(); - if let Some(expr) = grand_grand.cast::(); - if let Some(ast::Expr::Ident(callee)) = match expr { + if let Some(parent) = leaf.parent() + && let Some(named) = parent.cast::() + && let Some(grand) = parent.parent() + && matches!(grand.kind(), SyntaxKind::Args) + && let Some(grand_grand) = grand.parent() + && let Some(expr) = grand_grand.cast::() + && let Some(ast::Expr::Ident(callee)) = match expr { ast::Expr::FuncCall(call) => Some(call.callee()), ast::Expr::SetRule(set) => Some(set.target()), _ => None, - }; + } // Find metadata about the function. - if let Some(Value::Func(func)) = world + && let Some(Value::Func(func)) = world .library() .global .scope() .get(&callee) - .map(Binding::read); - then { (func, named) } - else { return None; } - }; + .map(Binding::read) + { (func, named) } + else { return None; }; // Hovering over the parameter name. - if_chain! { - if leaf.index() == 0; - if let Some(ident) = leaf.cast::(); - if let Some(param) = func.param(&ident); - then { + if leaf.index() == 0 + && let Some(ident) = leaf.cast::() + && let Some(param) = func.param(&ident) + { return Some(Tooltip::Text(plain_docs_sentence(param.docs))); } - } // Hovering over a string parameter value. - if_chain! { - if let Some(string) = leaf.cast::(); - if let Some(param) = func.param(&named.name()); - if let Some(docs) = find_string_doc(¶m.input, &string.get()); - then { + 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())); } - } None } @@ -250,27 +242,25 @@ fn find_string_doc(info: &CastInfo, string: &str) -> Option<&'static str> { /// Tooltip for font. fn font_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option { - if_chain! { // Ensure that we are on top of a string. - if let Some(string) = leaf.cast::(); - let lower = string.get().to_lowercase(); + if let Some(string) = leaf.cast::() + && let lower = string.get().to_lowercase() // Ensure that we are in the arguments to the text function. - if let Some(parent) = leaf.parent(); - if let Some(named) = parent.cast::(); - if named.name().as_str() == "font"; + && let Some(parent) = leaf.parent() + && let Some(named) = parent.cast::() + && named.name().as_str() == "font" // Find the font family. - if let Some((_, iter)) = world + && let Some((_, iter)) = world .book() .families() - .find(|&(family, _)| family.to_lowercase().as_str() == lower.as_str()); + .find(|&(family, _)| family.to_lowercase().as_str() == lower.as_str()) - then { + { let detail = summarize_font_family(iter.collect()); return Some(Tooltip::Text(detail)); } - }; None } From b036fd97ab2c1cdc003b50eea7850279a1a7601f Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 21 Jul 2025 15:13:34 +0200 Subject: [PATCH 07/11] 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; From af2253ba16dfdc731e787e3a43a6f6a63ea65e0a Mon Sep 17 00:00:00 2001 From: Laurenz Stampfl <47084093+LaurenzV@users.noreply.github.com> Date: Tue, 22 Jul 2025 13:06:44 +0200 Subject: [PATCH 08/11] Add support for PDF embedding (#6623) Co-authored-by: Laurenz --- Cargo.lock | 124 ++++++++++++++---- Cargo.toml | 10 +- crates/typst-library/Cargo.toml | 1 + .../typst-library/src/visualize/image/mod.rs | 76 ++++++++++- .../typst-library/src/visualize/image/pdf.rs | 98 ++++++++++++++ crates/typst-pdf/src/convert.rs | 48 ++++++- crates/typst-pdf/src/image.rs | 21 ++- crates/typst-pdf/src/link.rs | 3 - crates/typst-render/Cargo.toml | 2 + crates/typst-render/src/image.rs | 61 ++++++++- crates/typst-svg/Cargo.toml | 2 + crates/typst-svg/src/image.rs | 66 +++++++++- docs/guides/guide-for-latex-users.md | 9 -- tests/ref/image-pdf-multiple-pages.png | Bin 0 -> 7618 bytes tests/ref/image-pdf.png | Bin 0 -> 3987 bytes tests/suite/visualize/image.typ | 15 ++- 16 files changed, 473 insertions(+), 63 deletions(-) create mode 100644 crates/typst-library/src/visualize/image/pdf.rs create mode 100644 tests/ref/image-pdf-multiple-pages.png create mode 100644 tests/ref/image-pdf.png diff --git a/Cargo.lock b/Cargo.lock index 49a7c2b63..3e5fb87ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -181,9 +181,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.8.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" +checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" dependencies = [ "serde", ] @@ -214,9 +214,9 @@ checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" [[package]] name = "bytemuck" -version = "1.21.0" +version = "1.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef657dfab802224e671f5818e9a4935f9b1957ed18e58292690cc39e7a4092a3" +checksum = "5c76a5792e44e4abe34d3abf15636779261d45a7450612059293d1d2cfc63422" dependencies = [ "bytemuck_derive", ] @@ -964,6 +964,69 @@ dependencies = [ "url", ] +[[package]] +name = "hayro" +version = "0.1.0" +source = "git+https://github.com/LaurenzV/hayro?rev=e701f95#e701f9569157a2fe4ade68930dc9e9283782dcca" +dependencies = [ + "bytemuck", + "hayro-interpret", + "image", + "kurbo", + "rustc-hash", + "smallvec", +] + +[[package]] +name = "hayro-font" +version = "0.1.0" +source = "git+https://github.com/LaurenzV/hayro?rev=e701f95#e701f9569157a2fe4ade68930dc9e9283782dcca" +dependencies = [ + "log", + "phf", +] + +[[package]] +name = "hayro-interpret" +version = "0.1.0" +source = "git+https://github.com/LaurenzV/hayro?rev=e701f95#e701f9569157a2fe4ade68930dc9e9283782dcca" +dependencies = [ + "bitflags 2.9.1", + "hayro-font", + "hayro-syntax", + "kurbo", + "log", + "phf", + "qcms", + "skrifa", + "smallvec", + "yoke 0.8.0", +] + +[[package]] +name = "hayro-syntax" +version = "0.0.1" +source = "git+https://github.com/LaurenzV/hayro?rev=e701f95#e701f9569157a2fe4ade68930dc9e9283782dcca" +dependencies = [ + "flate2", + "kurbo", + "log", + "rustc-hash", + "smallvec", + "zune-jpeg", +] + +[[package]] +name = "hayro-write" +version = "0.1.0" +source = "git+https://github.com/LaurenzV/hayro?rev=e701f95#e701f9569157a2fe4ade68930dc9e9283782dcca" +dependencies = [ + "flate2", + "hayro-syntax", + "log", + "pdf-writer", +] + [[package]] name = "heck" version = "0.5.0" @@ -1200,9 +1263,9 @@ dependencies = [ [[package]] name = "image" -version = "0.25.5" +version = "0.25.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd6f44aed642f18953a158afeb30206f4d50da59fbc66ecb53c66488de73563b" +checksum = "db35664ce6b9810857a38a906215e75a9c879f0696556a39f59c62829710251a" dependencies = [ "bytemuck", "byteorder-lite", @@ -1265,7 +1328,7 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f37dccff2791ab604f9babef0ba14fbe0be30bd368dc541e2b08d07c8aa908f3" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "inotify-sys", "libc", ] @@ -1361,7 +1424,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.4.0" -source = "git+https://github.com/LaurenzV/krilla?rev=20c14fe#20c14fefee5002566b3d6668b338bbe2168784e7" +source = "git+https://github.com/LaurenzV/krilla?rev=37b9a00#37b9a00bfac87ed0b347b7cf8e9d37a6f68fcccd" dependencies = [ "base64", "bumpalo", @@ -1370,6 +1433,7 @@ dependencies = [ "float-cmp 0.10.0", "fxhash", "gif", + "hayro-write", "image-webp", "imagesize", "once_cell", @@ -1379,6 +1443,7 @@ dependencies = [ "rustybuzz", "siphasher", "skrifa", + "smallvec", "subsetter", "tiny-skia-path", "xmp-writer", @@ -1389,7 +1454,7 @@ dependencies = [ [[package]] name = "krilla-svg" version = "0.1.0" -source = "git+https://github.com/LaurenzV/krilla?rev=20c14fe#20c14fefee5002566b3d6668b338bbe2168784e7" +source = "git+https://github.com/LaurenzV/krilla?rev=37b9a00#37b9a00bfac87ed0b347b7cf8e9d37a6f68fcccd" dependencies = [ "flate2", "fontdb", @@ -1402,9 +1467,9 @@ dependencies = [ [[package]] name = "kurbo" -version = "0.11.1" +version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89234b2cc610a7dd927ebde6b41dd1a5d4214cffaef4cf1fb2195d592f92518f" +checksum = "1077d333efea6170d9ccb96d3c3026f300ca0773da4938cc4c811daa6df68b0c" dependencies = [ "arrayvec", "smallvec", @@ -1456,7 +1521,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "libc", "redox_syscall", ] @@ -1622,7 +1687,7 @@ version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fee8403b3d66ac7b26aee6e40a897d85dc5ce26f44da36b8b73e987cc52e943" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "filetime", "fsevent-sys", "inotify", @@ -1704,7 +1769,7 @@ version = "0.10.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fedfea7d58a1f73118430a55da6a286e7b044961736ce96a16a17068ea25e5da" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "cfg-if", "foreign-types", "libc", @@ -1841,7 +1906,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ea27c5015ab81753fc61e49f8cde74999346605ee148bb20008ef3d3150e0dc" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "itoa", "memchr", "ryu", @@ -1999,7 +2064,7 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57206b407293d2bcd3af849ce869d52068623f19e1b5ff8e8778e3309439682b" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "getopts", "memchr", "unicase", @@ -2112,7 +2177,7 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", ] [[package]] @@ -2215,7 +2280,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "errno", "libc", "linux-raw-sys", @@ -2234,7 +2299,7 @@ version = "0.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "bytemuck", "core_maths", "log", @@ -2282,7 +2347,7 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "core-foundation", "core-foundation-sys", "libc", @@ -2445,9 +2510,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.13.2" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "spin" @@ -2855,7 +2920,7 @@ dependencies = [ [[package]] name = "typst-assets" version = "0.13.1" -source = "git+https://github.com/typst/typst-assets?rev=edf0d64#edf0d648376e29738a05a933af9ea99bb81557b1" +source = "git+https://github.com/typst/typst-assets?rev=fbf00f9#fbf00f9539fdb0825bef4d39fb57d5986c51b756" [[package]] name = "typst-cli" @@ -2905,7 +2970,7 @@ dependencies = [ [[package]] name = "typst-dev-assets" version = "0.13.1" -source = "git+https://github.com/typst/typst-dev-assets?rev=bfa947f#bfa947f3433d7d13a995168c40ae788a2ebfe648" +source = "git+https://github.com/typst/typst-dev-assets?rev=c6c2acf#c6c2acf6cdc31f99a23a478d3d614f8bf806a4f5" [[package]] name = "typst-docs" @@ -3055,7 +3120,7 @@ name = "typst-library" version = "0.13.1" dependencies = [ "az", - "bitflags 2.8.0", + "bitflags 2.9.1", "bumpalo", "chinese-number", "ciborium", @@ -3067,6 +3132,7 @@ dependencies = [ "fontdb", "glidesort", "hayagriva", + "hayro-syntax", "icu_properties", "icu_provider", "icu_provider_blob", @@ -3165,11 +3231,13 @@ version = "0.13.1" dependencies = [ "bytemuck", "comemo", + "hayro", "image", "pixglyph", "resvg", "tiny-skia", "ttf-parser", + "typst-assets", "typst-library", "typst-macros", "typst-timing", @@ -3183,8 +3251,10 @@ dependencies = [ "comemo", "ecow", "flate2", + "hayro", "image", "ttf-parser", + "typst-assets", "typst-library", "typst-macros", "typst-timing", @@ -3581,7 +3651,7 @@ version = "0.221.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9845c470a2e10b61dd42c385839cdd6496363ed63b5c9e420b5488b77bd22083" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", "indexmap 2.7.1", ] @@ -3716,7 +3786,7 @@ version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" dependencies = [ - "bitflags 2.8.0", + "bitflags 2.9.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 08c6a8c8b..500d116a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,8 +32,8 @@ typst-svg = { path = "crates/typst-svg", version = "0.13.1" } typst-syntax = { path = "crates/typst-syntax", version = "0.13.1" } typst-timing = { path = "crates/typst-timing", version = "0.13.1" } typst-utils = { path = "crates/typst-utils", version = "0.13.1" } -typst-assets = { git = "https://github.com/typst/typst-assets", rev = "edf0d64" } -typst-dev-assets = { git = "https://github.com/typst/typst-dev-assets", rev = "bfa947f" } +typst-assets = { git = "https://github.com/typst/typst-assets", rev = "fbf00f9" } +typst-dev-assets = { git = "https://github.com/typst/typst-dev-assets", rev = "c6c2acf" } arrayvec = "0.7.4" az = "1.2" base64 = "0.22" @@ -61,6 +61,8 @@ fontdb = { version = "0.23", default-features = false } fs_extra = "1.3" glidesort = "0.1.2" hayagriva = "0.8.1" +hayro-syntax = { git = "https://github.com/LaurenzV/hayro", rev = "e701f95" } +hayro = { git = "https://github.com/LaurenzV/hayro", rev = "e701f95" } heck = "0.5" hypher = "0.1.4" icu_properties = { version = "1.4", features = ["serde"] } @@ -72,8 +74,8 @@ image = { version = "0.25.5", default-features = false, features = ["png", "jpeg indexmap = { version = "2", features = ["serde"] } infer = { version = "0.19.0", default-features = false } kamadak-exif = "0.6" -krilla = { git = "https://github.com/LaurenzV/krilla", rev = "20c14fe", default-features = false, features = ["raster-images", "comemo", "rayon"] } -krilla-svg = { git = "https://github.com/LaurenzV/krilla", rev = "20c14fe" } +krilla = { git = "https://github.com/LaurenzV/krilla", rev = "37b9a00", default-features = false, features = ["raster-images", "comemo", "rayon", "pdf"] } +krilla-svg = { git = "https://github.com/LaurenzV/krilla", rev = "37b9a00"} kurbo = "0.11" libfuzzer-sys = "0.4" lipsum = "0.9" diff --git a/crates/typst-library/Cargo.toml b/crates/typst-library/Cargo.toml index f4b219882..2297f7ca7 100644 --- a/crates/typst-library/Cargo.toml +++ b/crates/typst-library/Cargo.toml @@ -31,6 +31,7 @@ flate2 = { workspace = true } fontdb = { workspace = true } glidesort = { workspace = true } hayagriva = { workspace = true } +hayro-syntax = { workspace = true } icu_properties = { workspace = true } icu_provider = { workspace = true } icu_provider_blob = { workspace = true } diff --git a/crates/typst-library/src/visualize/image/mod.rs b/crates/typst-library/src/visualize/image/mod.rs index d037145e7..1a0e1e97a 100644 --- a/crates/typst-library/src/visualize/image/mod.rs +++ b/crates/typst-library/src/visualize/image/mod.rs @@ -1,8 +1,10 @@ //! Image handling. +mod pdf; mod raster; mod svg; +pub use self::pdf::PdfImage; pub use self::raster::{ ExchangeFormat, PixelEncoding, PixelFormat, RasterFormat, RasterImage, }; @@ -10,13 +12,15 @@ pub use self::svg::SvgImage; use std::ffi::OsStr; use std::fmt::{self, Debug, Formatter}; +use std::num::NonZeroUsize; use std::sync::Arc; use ecow::EcoString; +use hayro_syntax::LoadPdfError; use typst_syntax::{Span, Spanned}; -use typst_utils::LazyHash; +use typst_utils::{LazyHash, NonZeroExt}; -use crate::diag::{At, LoadedWithin, SourceResult, StrResult, warning}; +use crate::diag::{At, LoadedWithin, SourceResult, StrResult, bail, warning}; use crate::engine::Engine; use crate::foundations::{ Bytes, Cast, Content, Derived, NativeElement, Packed, Smart, StyleChain, cast, elem, @@ -26,6 +30,7 @@ use crate::layout::{Length, Rel, Sizing}; use crate::loading::{DataSource, Load, LoadSource, Loaded, Readable}; use crate::model::Figurable; use crate::text::{LocalName, families}; +use crate::visualize::image::pdf::PdfDocument; /// A raster or vector graphic. /// @@ -79,8 +84,7 @@ pub struct ImageElem { /// format automatically, but that's not always possible). /// /// Supported formats are `{"png"}`, `{"jpg"}`, `{"gif"}`, `{"svg"}`, - /// `{"webp"}` as well as raw pixel data. Embedding PDFs as images is - /// [not currently supported](https://github.com/typst/typst/issues/145). + /// `{"pdf"}`, `{"webp"}` as well as raw pixel data. /// /// When providing raw pixel data as the `source`, you must specify a /// dictionary with the following keys as the `format`: @@ -126,6 +130,11 @@ pub struct ImageElem { /// A text describing the image. pub alt: Option, + /// The page number that should be embedded as an image. This attribute only + /// has an effect for PDF files. + #[default(NonZeroUsize::ONE)] + pub page: NonZeroUsize, + /// How the image should adjust itself to a given area (the area is defined /// by the `width` and `height` fields). Note that `fit` doesn't visually /// change anything if the area's aspect ratio is the same as the image's @@ -261,6 +270,45 @@ impl Packed { ) .within(loaded)?, ), + ImageFormat::Vector(VectorFormat::Pdf) => { + let document = match PdfDocument::new(loaded.data.clone()) { + Ok(doc) => doc, + Err(e) => match e { + LoadPdfError::Encryption => { + bail!( + span, + "the PDF is encrypted or password-protected"; + hint: "such PDFs are currently not supported"; + hint: "preprocess the PDF to remove the encryption" + ); + } + LoadPdfError::Invalid => { + bail!( + span, + "the PDF could not be loaded"; + hint: "perhaps the PDF file is malformed" + ); + } + }, + }; + + // The user provides the page number start from 1, but further + // down the pipeline, page numbers are 0-based. + let page_num = self.page.get(styles).get(); + let page_idx = page_num - 1; + let num_pages = document.num_pages(); + + let Some(pdf_image) = PdfImage::new(document, page_idx) else { + let s = if num_pages == 1 { "" } else { "s" }; + bail!( + span, + "page {page_num} does not exist"; + hint: "the document only has {num_pages} page{s}" + ); + }; + + ImageKind::Pdf(pdf_image) + } }; Ok(Image::new(kind, self.alt.get_cloned(styles), self.scaling.get(styles))) @@ -286,6 +334,7 @@ impl Packed { "jpg" | "jpeg" => return Ok(ExchangeFormat::Jpg.into()), "gif" => return Ok(ExchangeFormat::Gif.into()), "svg" | "svgz" => return Ok(VectorFormat::Svg.into()), + "pdf" => return Ok(VectorFormat::Pdf.into()), "webp" => return Ok(ExchangeFormat::Webp.into()), _ => {} } @@ -373,6 +422,7 @@ impl Image { match &self.0.kind { ImageKind::Raster(raster) => raster.format().into(), ImageKind::Svg(_) => VectorFormat::Svg.into(), + ImageKind::Pdf(_) => VectorFormat::Pdf.into(), } } @@ -381,6 +431,7 @@ impl Image { match &self.0.kind { ImageKind::Raster(raster) => raster.width() as f64, ImageKind::Svg(svg) => svg.width(), + ImageKind::Pdf(pdf) => pdf.width() as f64, } } @@ -389,6 +440,7 @@ impl Image { match &self.0.kind { ImageKind::Raster(raster) => raster.height() as f64, ImageKind::Svg(svg) => svg.height(), + ImageKind::Pdf(pdf) => pdf.height() as f64, } } @@ -397,6 +449,7 @@ impl Image { match &self.0.kind { ImageKind::Raster(raster) => raster.dpi(), ImageKind::Svg(_) => Some(Image::USVG_DEFAULT_DPI), + ImageKind::Pdf(_) => Some(Image::DEFAULT_DPI), } } @@ -435,6 +488,8 @@ pub enum ImageKind { Raster(RasterImage), /// An SVG image. Svg(SvgImage), + /// A PDF image. + Pdf(PdfImage), } impl From for ImageKind { @@ -469,10 +524,20 @@ impl ImageFormat { return Some(Self::Vector(VectorFormat::Svg)); } + if is_pdf(data) { + return Some(Self::Vector(VectorFormat::Pdf)); + } + None } } +/// Checks whether the data looks like a PDF file. +fn is_pdf(data: &[u8]) -> bool { + let head = &data[..data.len().min(2048)]; + memchr::memmem::find(head, b"%PDF-").is_some() +} + /// Checks whether the data looks like an SVG or a compressed SVG. fn is_svg(data: &[u8]) -> bool { // Check for the gzip magic bytes. This check is perhaps a bit too @@ -493,6 +558,9 @@ fn is_svg(data: &[u8]) -> bool { pub enum VectorFormat { /// The vector graphics format of the web. Svg, + /// High-fidelity document and graphics format, with focus on exact + /// reproduction in print. + Pdf, } impl From for ImageFormat diff --git a/crates/typst-library/src/visualize/image/pdf.rs b/crates/typst-library/src/visualize/image/pdf.rs new file mode 100644 index 000000000..3ab0b8f7f --- /dev/null +++ b/crates/typst-library/src/visualize/image/pdf.rs @@ -0,0 +1,98 @@ +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use hayro_syntax::page::Page; +use hayro_syntax::{LoadPdfError, Pdf}; + +use crate::foundations::Bytes; + +/// A PDF document. +#[derive(Clone, Hash)] +pub struct PdfDocument(Arc); + +/// The internal representation of a `PdfDocument`. +struct DocumentRepr { + pdf: Arc, + data: Bytes, +} + +impl PdfDocument { + /// Loads a PDF document. + #[comemo::memoize] + #[typst_macros::time(name = "load pdf document")] + pub fn new(data: Bytes) -> Result { + let pdf = Arc::new(Pdf::new(Arc::new(data.clone()))?); + Ok(Self(Arc::new(DocumentRepr { data, pdf }))) + } + + /// Returns the underlying PDF document. + pub fn pdf(&self) -> &Arc { + &self.0.pdf + } + + /// Return the number of pages in the PDF. + pub fn num_pages(&self) -> usize { + self.0.pdf.pages().len() + } +} + +impl Hash for DocumentRepr { + fn hash(&self, state: &mut H) { + self.data.hash(state); + } +} + +/// A specific page of a PDF acting as an image. +#[derive(Clone, Hash)] +pub struct PdfImage(Arc); + +/// The internal representation of a `PdfImage`. +struct ImageRepr { + document: PdfDocument, + page_index: usize, + width: f32, + height: f32, +} + +impl PdfImage { + /// Creates a new PDF image. + /// + /// Returns `None` if the page index is not valid. + #[comemo::memoize] + pub fn new(document: PdfDocument, page_index: usize) -> Option { + let (width, height) = document.0.pdf.pages().get(page_index)?.render_dimensions(); + Some(Self(Arc::new(ImageRepr { document, page_index, width, height }))) + } + + /// Returns the underlying Typst PDF document. + pub fn document(&self) -> &PdfDocument { + &self.0.document + } + + /// Returns the PDF page of the image. + pub fn page(&self) -> &Page { + &self.document().pdf().pages()[self.0.page_index] + } + + /// Returns the width of the image. + pub fn width(&self) -> f32 { + self.0.width + } + + /// Returns the height of the image. + pub fn height(&self) -> f32 { + self.0.height + } + + /// Returns the page index of the image. + pub fn page_index(&self) -> usize { + self.0.page_index + } +} + +impl Hash for ImageRepr { + fn hash(&self, state: &mut H) { + self.document.hash(state); + self.page_index.hash(state); + } +} diff --git a/crates/typst-pdf/src/convert.rs b/crates/typst-pdf/src/convert.rs index 058658156..12d1a78eb 100644 --- a/crates/typst-pdf/src/convert.rs +++ b/crates/typst-pdf/src/convert.rs @@ -9,6 +9,7 @@ use krilla::embed::EmbedError; use krilla::error::KrillaError; use krilla::geom::PathBuilder; use krilla::page::{PageLabel, PageSettings}; +use krilla::pdf::PdfError; use krilla::surface::Surface; use krilla::{Document, SerializeSettings}; use krilla_svg::render_svg_glyph; @@ -363,6 +364,42 @@ fn finish( hint: "convert the image to 8 bit instead" ) } + KrillaError::Pdf(_, e, loc) => { + let span = to_span(loc); + match e { + // We already validated in `typst-library` that the page index is valid. + PdfError::InvalidPage(_) => bail!( + span, + "invalid page number for PDF file"; + hint: "please report this as a bug" + ), + PdfError::VersionMismatch(v) => { + let pdf_ver = v.as_str(); + let config_ver = configuration.version(); + let cur_ver = config_ver.as_str(); + bail!(span, + "the version of the PDF is too high"; + hint: "the current export target is {cur_ver}, while the PDF has version {pdf_ver}"; + hint: "raise the export target to {pdf_ver} or higher"; + hint: "or preprocess the PDF to convert it to a lower version" + ); + } + } + } + KrillaError::DuplicateTagId(_, loc) => { + let span = to_span(loc); + bail!(span, + "duplicate tag id"; + hint: "please report this as a bug" + ); + } + KrillaError::UnknownTagId(_, loc) => { + let span = to_span(loc); + bail!(span, + "unknown tag id"; + hint: "please report this as a bug" + ); + } }, } } @@ -535,12 +572,12 @@ fn convert_error( } // The below errors cannot occur yet, only once Typst supports full PDF/A // and PDF/UA. But let's still add a message just to be on the safe side. - ValidationError::MissingAnnotationAltText => error!( + ValidationError::MissingAnnotationAltText(_) => error!( Span::detached(), "{prefix} missing annotation alt text"; hint: "please report this as a bug" ), - ValidationError::MissingAltText => error!( + ValidationError::MissingAltText(_) => error!( Span::detached(), "{prefix} missing alt text"; hint: "make sure your images and equations have alt text" @@ -576,6 +613,13 @@ fn convert_error( "{prefix} missing document date"; hint: "set the date of the document" ), + ValidationError::EmbeddedPDF(loc) => { + error!( + to_span(*loc), + "embedding PDFs is currently not supported in this export mode"; + hint: "try converting the PDF to an SVG before embedding it" + ) + } } } diff --git a/crates/typst-pdf/src/image.rs b/crates/typst-pdf/src/image.rs index 39a6e602c..b846d1799 100644 --- a/crates/typst-pdf/src/image.rs +++ b/crates/typst-pdf/src/image.rs @@ -3,13 +3,14 @@ use std::sync::{Arc, OnceLock}; use image::{DynamicImage, EncodableLayout, GenericImageView, Rgba}; use krilla::image::{BitsPerComponent, CustomImage, ImageColorspace}; +use krilla::pdf::PdfDocument; use krilla::surface::Surface; use krilla_svg::{SurfaceExt, SvgSettings}; use typst_library::diag::{SourceResult, bail}; use typst_library::foundations::Smart; use typst_library::layout::{Abs, Angle, Ratio, Size, Transform}; use typst_library::visualize::{ - ExchangeFormat, Image, ImageKind, ImageScaling, RasterFormat, RasterImage, + ExchangeFormat, Image, ImageKind, ImageScaling, PdfImage, RasterFormat, RasterImage, }; use typst_syntax::Span; @@ -60,6 +61,9 @@ pub(crate) fn handle_image( SvgSettings { embed_text: true, ..Default::default() }, ); } + ImageKind::Pdf(pdf) => { + surface.draw_pdf_page(&convert_pdf(pdf), size.to_krilla(), pdf.page_index()) + } } if image.alt().is_some() { @@ -85,9 +89,9 @@ struct Repr { /// A wrapper around `RasterImage` so that we can implement `CustomImage`. #[derive(Clone)] -struct PdfImage(Arc); +struct PdfRasterImage(Arc); -impl PdfImage { +impl PdfRasterImage { pub fn new(raster: RasterImage) -> Self { Self(Arc::new(Repr { raster, @@ -97,7 +101,7 @@ impl PdfImage { } } -impl Hash for PdfImage { +impl Hash for PdfRasterImage { fn hash(&self, state: &mut H) { // `alpha_channel` and `actual_dynamic` are generated from the underlying `RasterImage`, // so this is enough. Since `raster` is prehashed, this is also very cheap. @@ -105,7 +109,7 @@ impl Hash for PdfImage { } } -impl CustomImage for PdfImage { +impl CustomImage for PdfRasterImage { fn color_channel(&self) -> &[u8] { self.0 .actual_dynamic @@ -196,10 +200,15 @@ fn convert_raster( interpolate, ) } else { - krilla::image::Image::from_custom(PdfImage::new(raster), interpolate) + krilla::image::Image::from_custom(PdfRasterImage::new(raster), interpolate) } } +#[comemo::memoize] +fn convert_pdf(pdf: &PdfImage) -> PdfDocument { + PdfDocument::new(pdf.document().pdf().clone()) +} + fn exif_transform(image: &RasterImage, size: Size) -> (Transform, Size) { let base = |hp: bool, vp: bool, mut base_ts: Transform, size: Size| { if hp { diff --git a/crates/typst-pdf/src/link.rs b/crates/typst-pdf/src/link.rs index 64cb8f0a2..2133be82c 100644 --- a/crates/typst-pdf/src/link.rs +++ b/crates/typst-pdf/src/link.rs @@ -49,7 +49,6 @@ pub(crate) fn handle_link( fc.push_annotation( LinkAnnotation::new( rect, - None, Target::Action(Action::Link(LinkAction::new(u.to_string()))), ) .into(), @@ -64,7 +63,6 @@ pub(crate) fn handle_link( fc.push_annotation( LinkAnnotation::new( rect, - None, Target::Destination(krilla::destination::Destination::Named( nd.clone(), )), @@ -83,7 +81,6 @@ pub(crate) fn handle_link( fc.push_annotation( LinkAnnotation::new( rect, - None, Target::Destination(krilla::destination::Destination::Xyz( XyzDestination::new(index, pos.point.to_krilla()), )), diff --git a/crates/typst-render/Cargo.toml b/crates/typst-render/Cargo.toml index 7d01d7e38..497343510 100644 --- a/crates/typst-render/Cargo.toml +++ b/crates/typst-render/Cargo.toml @@ -13,11 +13,13 @@ keywords = { workspace = true } readme = { workspace = true } [dependencies] +typst-assets = { workspace = true } typst-library = { workspace = true } typst-macros = { workspace = true } typst-timing = { workspace = true } bytemuck = { workspace = true } comemo = { workspace = true } +hayro = { workspace = true } image = { workspace = true } pixglyph = { workspace = true } resvg = { workspace = true } diff --git a/crates/typst-render/src/image.rs b/crates/typst-render/src/image.rs index 7425bdd2f..03347d5dd 100644 --- a/crates/typst-render/src/image.rs +++ b/crates/typst-render/src/image.rs @@ -1,11 +1,12 @@ -use std::sync::Arc; - +use hayro::{FontData, FontQuery, InterpreterSettings, RenderSettings, StandardFont}; use image::imageops::FilterType; use image::{GenericImageView, Rgba}; +use std::sync::Arc; use tiny_skia as sk; +use tiny_skia::IntSize; use typst_library::foundations::Smart; use typst_library::layout::Size; -use typst_library::visualize::{Image, ImageKind, ImageScaling}; +use typst_library::visualize::{Image, ImageKind, ImageScaling, PdfImage}; use crate::{AbsExt, State}; @@ -59,9 +60,9 @@ pub fn render_image( /// Prepare a texture for an image at a scaled size. #[comemo::memoize] fn build_texture(image: &Image, w: u32, h: u32) -> Option> { - let mut texture = sk::Pixmap::new(w, h)?; - match image.kind() { + let texture = match image.kind() { ImageKind::Raster(raster) => { + let mut texture = sk::Pixmap::new(w, h)?; let w = texture.width(); let h = texture.height(); @@ -85,15 +86,63 @@ fn build_texture(image: &Image, w: u32, h: u32) -> Option> { let Rgba([r, g, b, a]) = src; *dest = sk::ColorU8::from_rgba(r, g, b, a).premultiply(); } + + texture } ImageKind::Svg(svg) => { + let mut texture = sk::Pixmap::new(w, h)?; let tree = svg.tree(); let ts = tiny_skia::Transform::from_scale( w as f32 / tree.size().width(), h as f32 / tree.size().height(), ); resvg::render(tree, ts, &mut texture.as_mut()); + texture } - } + ImageKind::Pdf(pdf) => build_pdf_texture(pdf, w, h)?, + }; + Some(Arc::new(texture)) } + +// Keep this in sync with `typst-svg`! +fn build_pdf_texture(pdf: &PdfImage, w: u32, h: u32) -> Option { + let select_standard_font = move |font: StandardFont| -> Option<(FontData, u32)> { + let bytes = match font { + StandardFont::Helvetica => typst_assets::pdf::SANS, + StandardFont::HelveticaBold => typst_assets::pdf::SANS_BOLD, + StandardFont::HelveticaOblique => typst_assets::pdf::SANS_ITALIC, + StandardFont::HelveticaBoldOblique => typst_assets::pdf::SANS_BOLD_ITALIC, + StandardFont::Courier => typst_assets::pdf::FIXED, + StandardFont::CourierBold => typst_assets::pdf::FIXED_BOLD, + StandardFont::CourierOblique => typst_assets::pdf::FIXED_ITALIC, + StandardFont::CourierBoldOblique => typst_assets::pdf::FIXED_BOLD_ITALIC, + StandardFont::TimesRoman => typst_assets::pdf::SERIF, + StandardFont::TimesBold => typst_assets::pdf::SERIF_BOLD, + StandardFont::TimesItalic => typst_assets::pdf::SERIF_ITALIC, + StandardFont::TimesBoldItalic => typst_assets::pdf::SERIF_BOLD_ITALIC, + StandardFont::ZapfDingBats => typst_assets::pdf::DING_BATS, + StandardFont::Symbol => typst_assets::pdf::SYMBOL, + }; + Some((Arc::new(bytes), 0)) + }; + + let interpreter_settings = InterpreterSettings { + font_resolver: Arc::new(move |query| match query { + FontQuery::Standard(s) => select_standard_font(*s), + FontQuery::Fallback(f) => select_standard_font(f.pick_standard_font()), + }), + warning_sink: Arc::new(|_| {}), + }; + + let render_settings = RenderSettings { + x_scale: w as f32 / pdf.width(), + y_scale: h as f32 / pdf.height(), + width: Some(w as u16), + height: Some(h as u16), + }; + + let hayro_pix = hayro::render(pdf.page(), &interpreter_settings, &render_settings); + + sk::Pixmap::from_vec(hayro_pix.take_u8(), IntSize::from_wh(w, h)?) +} diff --git a/crates/typst-svg/Cargo.toml b/crates/typst-svg/Cargo.toml index 5416621e5..9b7dc538e 100644 --- a/crates/typst-svg/Cargo.toml +++ b/crates/typst-svg/Cargo.toml @@ -13,6 +13,7 @@ keywords = { workspace = true } readme = { workspace = true } [dependencies] +typst-assets = { workspace = true } typst-library = { workspace = true } typst-macros = { workspace = true } typst-timing = { workspace = true } @@ -21,6 +22,7 @@ base64 = { workspace = true } comemo = { workspace = true } ecow = { workspace = true } flate2 = { workspace = true } +hayro = { workspace = true } image = { workspace = true } ttf-parser = { workspace = true } xmlparser = { workspace = true } diff --git a/crates/typst-svg/src/image.rs b/crates/typst-svg/src/image.rs index 58f0227b6..55a8f22ac 100644 --- a/crates/typst-svg/src/image.rs +++ b/crates/typst-svg/src/image.rs @@ -1,10 +1,13 @@ +use std::sync::Arc; + use base64::Engine; use ecow::{EcoString, eco_format}; +use hayro::{FontData, FontQuery, InterpreterSettings, RenderSettings, StandardFont}; use image::{ImageEncoder, codecs::png::PngEncoder}; use typst_library::foundations::Smart; use typst_library::layout::{Abs, Axes}; use typst_library::visualize::{ - ExchangeFormat, Image, ImageKind, ImageScaling, RasterFormat, + ExchangeFormat, Image, ImageKind, ImageScaling, PdfImage, RasterFormat, }; use crate::SVGRenderer; @@ -66,6 +69,25 @@ pub fn convert_image_to_base64_url(image: &Image) -> EcoString { }), }, ImageKind::Svg(svg) => ("svg+xml", svg.data()), + ImageKind::Pdf(pdf) => { + // To make sure the image isn't pixelated, we always scale up so the + // lowest dimension has at least 1000 pixels. However, we only scale + // up as much so that the largest dimension doesn't exceed 3000 + // pixels. + const MIN_RES: f32 = 1000.0; + const MAX_RES: f32 = 3000.0; + + let base_width = pdf.width(); + let w_scale = (MIN_RES / base_width).max(MAX_RES / base_width); + let base_height = pdf.height(); + let h_scale = (MIN_RES / base_height).min(MAX_RES / base_height); + let total_scale = w_scale.min(h_scale); + let width = (base_width * total_scale).ceil() as u32; + let height = (base_height * total_scale).ceil() as u32; + + buf = pdf_to_png(pdf, width, height); + ("png", buf.as_slice()) + } }; let mut url = eco_format!("data:image/{format};base64,"); @@ -73,3 +95,45 @@ pub fn convert_image_to_base64_url(image: &Image) -> EcoString { url.push_str(&data); url } + +// Keep this in sync with `typst-png`! +fn pdf_to_png(pdf: &PdfImage, w: u32, h: u32) -> Vec { + let select_standard_font = move |font: StandardFont| -> Option<(FontData, u32)> { + let bytes = match font { + StandardFont::Helvetica => typst_assets::pdf::SANS, + StandardFont::HelveticaBold => typst_assets::pdf::SANS_BOLD, + StandardFont::HelveticaOblique => typst_assets::pdf::SANS_ITALIC, + StandardFont::HelveticaBoldOblique => typst_assets::pdf::SANS_BOLD_ITALIC, + StandardFont::Courier => typst_assets::pdf::FIXED, + StandardFont::CourierBold => typst_assets::pdf::FIXED_BOLD, + StandardFont::CourierOblique => typst_assets::pdf::FIXED_ITALIC, + StandardFont::CourierBoldOblique => typst_assets::pdf::FIXED_BOLD_ITALIC, + StandardFont::TimesRoman => typst_assets::pdf::SERIF, + StandardFont::TimesBold => typst_assets::pdf::SERIF_BOLD, + StandardFont::TimesItalic => typst_assets::pdf::SERIF_ITALIC, + StandardFont::TimesBoldItalic => typst_assets::pdf::SERIF_BOLD_ITALIC, + StandardFont::ZapfDingBats => typst_assets::pdf::DING_BATS, + StandardFont::Symbol => typst_assets::pdf::SYMBOL, + }; + Some((Arc::new(bytes), 0)) + }; + + let interpreter_settings = InterpreterSettings { + font_resolver: Arc::new(move |query| match query { + FontQuery::Standard(s) => select_standard_font(*s), + FontQuery::Fallback(f) => select_standard_font(f.pick_standard_font()), + }), + warning_sink: Arc::new(|_| {}), + }; + + let render_settings = RenderSettings { + x_scale: w as f32 / pdf.width(), + y_scale: h as f32 / pdf.height(), + width: Some(w as u16), + height: Some(h as u16), + }; + + let hayro_pix = hayro::render(pdf.page(), &interpreter_settings, &render_settings); + + hayro_pix.take_png() +} diff --git a/docs/guides/guide-for-latex-users.md b/docs/guides/guide-for-latex-users.md index 93fa296fc..e8078086b 100644 --- a/docs/guides/guide-for-latex-users.md +++ b/docs/guides/guide-for-latex-users.md @@ -665,12 +665,3 @@ applicable, contains possible workarounds. [`page` function]($page) which will force a page break. If you just want a few paragraphs to stretch into the margins, then reverting to the old margins, you can use the [`pad` function]($pad) with negative padding. - -- **Include PDFs as images.** In LaTeX, it has become customary to insert vector - graphics as PDF or EPS files. Typst supports neither format as an image - format, but you can easily convert both into SVG files with [online - tools](https://cloudconvert.com/pdf-to-svg) or - [Inkscape](https://inkscape.org/). The web app will automatically convert PDF - files to SVG files upon uploading them. You can also use the - community-provided [`muchpdf` package](https://typst.app/universe/package/muchpdf) - to embed PDFs. It internally converts PDFs to SVGs on-the-fly. diff --git a/tests/ref/image-pdf-multiple-pages.png b/tests/ref/image-pdf-multiple-pages.png new file mode 100644 index 0000000000000000000000000000000000000000..a6be4a31391ab97054623ceaf5f702f033f724a2 GIT binary patch literal 7618 zcmV;z9X;ZSP)rH;Ac5ZJJSXSPn|qu3x$pfx%X`TaYQi3i zJwYHKKog(|BR~_N3DATQpb5}~5ugds1Zcu^475@;?5baUw!c+A>RSw^2ebnJ?HM&T zo88jVGBh;Q(a|B5O2uNadPWUE<|gRM%F5*A23l+``icJ)6=8gIAWb!#SyF{f@&b44Dlnk}CwIw7Z(CKs@k2lWxl>q^;0xocr zmYVQ*%qa%}xNLSQnS3EC>fL~VKbMpkV~x+9U})sFZL`^n4q=9g>5zi-f`S4jlPQr% zMjn%qvBTZ{3219$V+5e9r{8ej6c(OE{|YGyIU77+Mo7_vbJE^Gw%v5q zKaHP#-{8r2e|+Mw!{^k-q8Zf?C9!&{UVu+=a2h%6OOxj-8ggflbqj;xtFLeN z;)^vYDYLsW#En^6TI%L^{rHUy8%>vmWIBtb!n>c+o69!*^c<^`R##V7TU+~>DVGEV z87*EMe)_aTAkfTQyJHp>7WVe`vj#K-8j|f6V6SiW(YAB1#uj+VtjrE#>8RqGBgr5mfB#?Cyfr^~z9j$EvHT_U;zj&%M3#@;j+z zAxfn}%PHa6uHRa`l~<4rn{LE1ktqH8bp$SyD1C!R-0tYG9kU|&LI=DE|z^_!ZS8Y-1KC6uvQo|cvt=Hqj5(*mc2CnqfP)N9vLY;2OOtT5KyV3=7E ziFCr;YgcVc`NMI6f*V|4Yk&JxOiT>8-0le*N{S1q%`^EW|wCeU&==)G3qapU(;m z%(-Lut~u5C*A5!i%kA7^{&H?r9L9V1?giqzN+Lj)v%MY9(1=7LRLq)527{rer-#L^ zQB`hd=k23MPcK*yd+wZYV1nYaAurGT<(K{R^_v)s=;&zN1i(E<_6%!lX(lIMbv0VT zOWDixTgMyZjyMN5;cR3Q zbm-8Tg$tuiO$8i|dUA#g8W+ZN*)nQkB0xj6T3cInw=%@-tkKE|&CBQ7p)OmKzkBk>1Nx%^CcXudtr23ZzPnO>?%cV>zq4>X zX|JVCp~V>4*=8@j2$BoYbw+eV|gZQFM4l~)RVeQ6aH&|f4WH~{$>iU=%Z+~Buw-$r)=*)Edb zhK2^s=}VU`wXsQCvLukh5vw1{5G`*XIRYi2CM0nB`g9SrLMDqaHcs;JNJ&a^a&jsw zD?=RDth@1y$!ZLVj1P|{H8;255jxc9oh%koTGSC4j*jwQ^5~F|kcA5uA`CV*HewSJ z8a*&D05L(qi3TBy#X?1gS`OF4&CLzR+uKw3?aNU=g4JhbU48f6%kR9Si=b6XC2~*4 zFTOzEAnNSd*19_UvvK#8l$6kDwDBYbL9DQ_5X+N6rzc#xgzyz0rA0u2j|V3 zw{qpm@4x@v+}!-i6-x-kzJ2@FtXcE)(@!H{Lb!erYvtQ-N95*qsUOV-+S+tF81}MQ zCAB~;cI`s*L0gI~li{*?dwW}2S{4-i z-pb0%!@~o+kz=o7US9WK{~9ipD(C(KG!VON7Z+3nmMd50dwUO#N#k()L(_{RBQLF3 z;qcjKnzqj5t-AUJsZ`r$w!VJ0rDeq&e1HZq5KT_(q+qujNiM`xlOfPkQ(ZP~g6zha znGLkxL(@i~IO^%46s9F6svq3w^moMKI<3#Eix3r=Ox|1rjT|5^FAtd+(gviW!GVED zWBXfMyXfdPm!ao-YwOk%fBYi?I@T{j4SG5SUS8;&J!HJ9|5zX>(|(Mb8(mK?5&Dj# zc#eQZb%3t!`PW~E)EfTjPlum;(%`A5(6vDcaB=x^t2JxvKl$Y9d+!;}n|I`?r=S(g z{Co}Khc+g2GoPO|(H@m*&6?=z*E10(=g8BfShf(^p89%-19~)y5m_C^#s2=lZS%ng zNKRGCsR>X`O}n_)(}wsemjE7-9k2&K>@d*U$g1!#C3B~Kt2(#56{YCqfH@VtVgsllanI~3%3*(|AEI#pZvKI5sh!Y>64L> zh3hoo!CWra$IY&n%`PI{2#rqAEzo2#+0WhGW&eJ|`SXJgAMR@$SK4qfGzIhnhCU{` z{#2?HnY@6-+A5JS)emSJHzxn|Q!Hv!Ef*5q5_}6P{-UC)^XJJcRz&Rl{-zEELu!1y zm7boadLHcR(thLPIY(?PVFMI>P9$C+sAXRR5ex++j*pKIDk)h9UFP$%G4JVYnx2*n zS5MlSoB0bDI@i{AYXOZSGcmF7=+T1t^Zkz>FDxtTMc$%A!LZ2Bj~p60VSk;=jb$)C z>F6-+>x<%W8jx$FZI2iQ^yvTIw;zJS9hn)8c7sZNuDjbtrIKsr(M$5T+Sb5es2{{^ zZL79!O3Wc+CXXe6%{#eVsz2aHC!=hA*upYa+uQHjNs;U;yXfGi}YihFZ?ak}x zXodc!rl!Wl#o@1FQD0~ptxy;?+o`(xFJkdMrn$N4B(Lvo*&Na=!w1P#hMP@saV?|f zb8@=YuTMh2MB9(gm(8)QEEU*sIDW0Ihv@XTDU?5;(raiqouBVmR+a%(!Cfp6ptSVI zS{|jy!CrRV1z#rL_~-2aPxS*@QBlu}FW&C&mtc%*6dT+8!3VK#yblf(8D|mxq1) zar`&mq#GFIU${Vaaj6LlYs|{(tf@g1m&}E~Gt{J3h>drYw6mc>4`EX(ZMiRH$IC{( z?l-l7o^)G^yLK(vhi$;j%&?9Q6UYS;47GY(jsQJ%7g!B-Uc5N);>B`_M4{PVhK9_AVA$K+ ziy#BO*ki?pH`K7ZyR)Lgy{>Kp)ET-A-B3SX>+TjpE}+*11>H#Pk@;W+%zDtMA#-zc zDU`ytwpb<;`>orNS0Lr+?+;We#p;=}=;&r-c#sPUr4~EI6y(($&TM^vMj~O+={ss_ zUazeDeSQ5$Sij&aku<7x!?;}O!GpQWmIX&f)+6f(4-W_KS@}oz2y`5duSi5wsT68m zHPkP!y%vfpv7>{B3=i9K#1ErPmx;v+GqbX1pA8HMXdr%pX4;KP?SKFM7*yw#m3;*0 z={4lnC>>F?pEyxCKdQ+X zF~XSdCUmtzMu46o(DDCqd*hVF)7f5bZ9e`lrJIQkd!%VaZ$1X-|bc0@5%wzgMyY)Joz3g1R)zF#kShN zMb1k4wWoI~F&E*EckK_Nq(e$h-DE*4Wioomkk5NK7ikHRM^DO-d&%gblKjiO8%u@J z+W}uYXh;p;^(8^@7jjmjq|_0|6QCz+8dxg12ytx4Yt=-)TG3g0_e7##c^H!vSwjsb zbhTVeREARqT9jspQbiEH89o&F31TJzdRjp9uFvN=F624P!|U+)=CVfz&6CO5Vu^Mi zlFMfXv`Q?JH!>#hrUtb_F%_U~rd2ww&=@}yRciO^wXB%|Eo0CJuV0$b6&&_dWPAOJ z?(&ho$KY^bdf5L=vZ?BawaeA@Bbn|mrW`Dxi~{YTE1;dP{CD7FIU4j-8@;LHo!#fY zG;|m>KUJWODr&4~jALa~T?Ebda}`AR58d|U`?^dwXhv)IA#300>~eufGKHYEyTe?S z4((=O>sLr+s;9_Y7)__kX&Q%U=oeLBFv@*ctuq5!(cK}447{&nQS&_QGv=K zzD|MGULAQdTb>C|jBe|i9qFCCh1K)z=ly356r5hXoh_jGGPy}*%`0)~`E1Upj|zJG z)4O`LdyiN$19>#p{sQNeK0m-sty0Yv&;wH0YjNon{oD@W=rr+2DRn{-&t-FF0JKuT zhYwsdgiNbs(pdr8j8bbc zG>b35a_*BzwSzXPq+hD8KUY<2PN_Xhp0kZ7! z+8?cbNBaINUI(pwM$R0&7C4#Tc5D}lNFCjyJg&VPpkvy)G;dS7*x5aOSiGwfv!9Jh zMjqnJYV~Vu)9#H!f++(nrIbyWIP=`D-Px~_z%k&Q*^dlFyCZVqNS;8X9>+Z6a!?9R z=n|Q>zK`a=k7WyR6FSll$2wNcARmYY^2xSqrVBLhhSli$8p#0>p)d%}8W3Xz^`Hv1>d0*dR zB*0Iz&c$9wZG*2C=fe#x~lgWmzz3-#$c^4+7PcM_?rojowpZTv})-H|gr{XF%<8uS5TGL{q)2{iVQ zjU4=?DuEv;roi{#aa{qe5)4762P{r02e~?4upq1ZdukqtYcE*fr^;z|bf$Gp1A5jo z4_d~mmsFPYo!pB~o?0QF6(#t;a!N+`LUq5_(evFG?A_}{xv8_Ldq?B)koNUUq`Wa& zZ(GxFzN${UQw9d71++>ikk!}R*O7Ac8SEIaI4w#ispRt60vcvmUcElEsIve5$cP=5 zsWGlpwyU5VIYw$1TSq~oNa4BKXm)02BWUzGZZVoQ4mmcisKH>Ar*yJ)0kjQ*-cX45 zP_PHKXibjm>+l4)4crj>MboRKfjJZMEv zr!X#bA`e3{Tfas^63vs)3<@mvQsP)?Am;UNBFN!2uf)?tfea@R&NNBa8#w9g_M zM$Y^*h9y_3W`lI-usK!sE^?<$=n}<4g03Cp7xwmRckH(Oia_s3Y}Sir{VT3%Yy7Z( zO={X0+qm4n?k;HJvE8Ww{gMy;t-!jKLG`ct)xI56|B7!d2G4oc5TGB)hGa^-LU|o3 z*prct0f|C$76JMJOe|OKNolbqv$1~t=>6m#;Yc?x>_UVbIYa3ct&3)DPi($e+#Sl` z5}=1|P^uV|XmhO1{|{kcksi)$uk9DB#~8#qt9^8If^>lXiojvXPH*LF{|dNRp_RsYomEjn=Eb9yf%qGY*6OK)+BWdx988FL(WS$ z@Z;e*=Y()xZ?u+3Wpb4pIK`cO^Du+vx|SEvYnW9s-HLBok04&r;e zvT3+@2`mahBWMJTLeK~rg`g2Mf<_@|1dT$_2pU175Hx}wMwVr{uIph8e)u0kwrw+8 z+T4<+X{}bP-EQl;E{dY6s@-lE#?)#xK@cQKQWOQoAZXu`Wf|~oQ-)`nrUC9YR+1!v zHS|JzqtT!!iXaG%<1nHFMs&Y448w7pUax1GCL{`|LdJkDXn`n(E(mj|B4|`l(5%?4 zl5zl(LWhwFLaYREQ(;x9tcs-oHd>5STn}ce(>XBEg^lLfxx~z~&$plZb2yfYufLg^ zA9;pETNabK>dN9)Ux#FBS3ChHS zOo=k9yzSlJSnKMe_wNdcdx^;sUo7(_@BTz(fi+cr%H*bgcXGb0G4s`>P(FI|``y@| z_U!E`jVq1=_}|!vwlkT`n6^&ZPBPOr!6e3Mt=5>-s8vykHxvvRMe!Dcuz*|^kcH(U z7hy$ia+8Ze#DvQN%`ai%81mxbWncEpZwBVTzI^!c-5-aNjYO)jfN$#T_`hCfETb1? zUV;1w_>f9!Ie8*9&*J?%o>kyODv5o5)iQCYx(#rs)-kd-W|~vA-8{!NNYF*A#qism zqyc9P`m9iTFsUa47pT^dIXk3z2;(>t4kT!J{}9#@^eu<<98~B^W|va@;N|o7`+HHF z`eZ|*{kgqXsW3KmNcTeAHTR_;mAn?T{^0EKlwsNOLSo}zB3?5|c07_9U0)FAj{|F~j6s*_Dm1muodZ6jFF(HKk&!6~2h5h0L-(;KRHdBJ+gQy`no(X#6rfpw#*?*xz<7!AninW2!E< zZ}m{sUe6Q2cj|qSc8{KVdBvo(nApBJmcWyG-kh{Qqfd2Lp=&uKg|+#`eDgz2gU>Vg zZ*X?XH#(e^Zs(L(^wr{-S_xTU>+WiT&Z#iPjql6(JTuVwi*m;VP99x=o!MW2$X-&1 z#o7pO(<{URB2~znpozl*K!2ScQqnRgzrUZbgPryW6A|O<4k6SMIkjS)UAGHhUrf%J z!uZ$e5un5&{k;ZXA-o*3bZ5Pj84ovmFqv`=13G*L@EqK~Ob<1sxb-nT`g$6C5y8Bp zx7*JfKNuPa&P{usKMPFrQd{d}=YxV?cNIFdxvshWQ?*=X2KuGkw;=O>&J7we!4oTk zyNNn~ZAt(=>>tD{?r7<%@(!8m6PV}lr_jQm`S$gJT}RwX9uq`Z5Brvg5%!_A8!dlX zYxac|GZ#jP_wlU;U+t}-bRwg(8tC6jTJ@Hip-;82UpkRDMM|9fCq{g{ALe!H1|QrQ zb1Fq{S8* zW6wg&(t|wVC0@h0Vt@XW;*OvObVNA6_mBe<9y8FRD-H=BMIAZBn#jbOeMI>PvKV!| zdr5FrP9Y2rFhZb0hYg&lPNZqS^^Vv>Qik`#RXLxRneomQ$o|bId`TKf*%>Lq%~R&w z;u{7~m5o8op!{CcK9X|%hpG%CN)W#fT?xI3+RpF|a10JG^UJVWtM~8;g*}7X&a-bQ zkP);NRc6Rpn_j4;XGc$vr zA6p$A9bH{rt*x!#(PT1dG#W58Ha7MxRZ~-AHk-kw#bOy78*6WG?_bJjGc34%aJ2MR$WXaxO8m6es%rDour zb4w8f5#6k;tYjEwU|<03V;BbJWPuh41ZAlic<0$=Xl|`BG-LnXa$2ka%cu8p>)V6SVzH2ze+9cBE-lIAmc;|;-lKY`4A*pz zFHz82MZ)m)U54`_=^MO*rh*jo#mg~GaWfcnva<<;&KHv20+Tvlx}SH@u>ak@f| zT^$ar3e6fN=0CT~3lVfYU31?A#1AfyV=fl-3u(-SBK*Y5a>>(41U)!7=ytnpHk-%e zNlxgmB^>})^`i?sepC1_w2lS+d>V7U82_a}{_2J#f_6Hc4u=CkPfkuI8#KKbah<&M zYfj^_jAnpqJLlE?F|s=J=Jd$9{dnbW@uswJIIL7E!G2X$6~i#-=vX0!X8+mT5MA}9 z?WXz(s2m%5>!x(N`CxB_q)?Ok&&U&D)u^flPCr{p0 z{{6#VmSJN-KbJwCe9QE0v2^FNe1m3#e%3$Ckqhu?Nwxy`{`RHi9Z?gsc3Q7GYax+6G-o1G2fOLEAvX|NI_P)M8nx<0?I&zz;KLm-HVHF%kj~{`! z2cJ`{5rhDF)4Wd+*{Z-=vf>W~2>5 z2TvV(_!Iqig?;^Q{O4pX{P4k@_Ra*VsVj}+35yDXtPv1JpssCCwY632OdaiLN3m|z zt|Y0 ztIRk>ScmTj(Eu%#DA)sSVOr<)Mby%X9}lwCFq6q-$m!{UpwokZRS~gV9z2PzFH&6H zNI)xdBhqeF!f%W<4cNQ!4kebe8B`i%(YMxf!R1Ah#}DLbm?8a)&*!rT8m&QXZLLr! zd_~Z7Z7v}z51B?kPC!m;|YO96er|ORRN`5~mKk*5ntSnB%rPm93pt)JuO84_K-7I?dLYhZ#a4^mzB^3@D zd6!7=U=K9HE2z#@RaH#V2`YF+MaBOQT3%jKxn?P&LjFlD#%zN&GcW$<%JAtkKkRRZ zGuheMsKq$aG>!CBRzcU-*Qcka<6ArJI;uTa5ybT;j*x<~QK%v!YbZ?5IOKcpM8Ja@ zftY>Jj(yDwmV9$|%A61TJG9M#M;11#t|Kce3$CNnpj#;iA8k18U$x#H<>p7ZIIq0t zrMxf(S|2jrviBb7nZPvR&HMFN?@)!MY=Q2Vx4u0p>)I-h~RCZ-T2@o?n!hR=V9Y1|z&b)QdVy^=T z>vcEi0jB-3=59DWalr>Rjv8js(b0*CiR^)WKza$OKU4Z-8_Yj+iS?j^YKw=Lo05Su5eqMmduXa^IE z)PH<;eC(I+TMg1M!%vnlYdtnv;{G9kir|QU{$AQrLb6X7(lUz5MAp0(!Lh zUcZCM;2Y!-NS}AUr_?tDd_`$Ft)L}>=Rn{4scS*o_pwa+#QVs5 z?xQRQx2@4^H-?xeWLDs4Zwwm>8&S1i@QRc*#>|Mw@y|qVSV8{N_eUNhl;=8or_Npv zxQvSbd<1*twWSPbm8iUnLHD*w9KY+}J1gHacW&DS!0IDbL8DE;tz);W{>aiuiiCt(J)I(OT+RnRzc(Yu3Wjo&g3jD zlPek;+3H6Fv~~2TeZLM_<7(oFp&3Sl1ThIJp;EI48oBQjMX@{!&Kl_c#@3fc9^5^6 zt&NeTL?ZF?^FxSZ|Ni}$1xI6u1pusqhO4TqtRx@dtkJE;K=I80%`>(+KlI3t12>E` zd5eT9iI9;YdI7I39*vMG-Ym>Myb!doR2;oBWlx{8(3r1ML{-$wXHqwpUw>Sm-_VVq zjcm?1AKPK?IlRvh4Ku8ZMyx~E1OHEQh2X294aK6DnruDZ|0L1434$wA+wz&BwtM7*z57RKi&;emQod%7X3#{Rv-^jaA7B)R0&F>L^S^}xm zO%)Qxtfrvp8%`Lb8!a!k$d#>5qd}$tI_E@Qw}3XVJ!*A&gSpobqv35w50R0PIt^No zQBSb?n4U#lRw-mb&PR{h1>#IC5|*2*>7w80+|9=)?*`wfommX)$Ss-7O*BB)q}Fr? zXln!BZ)Tw$Cfi*NhqrYd*j_=WK~qng3FvUQ_=eE^qFpnH*6o~4Wn83hyv=ByuiI+F z@KZ}uqJPLHteKls-K}OQ-`;q)B){P!qhrv^C-b`yv=x`<)938hy>_@5jL4R^DGg3h_Jn>JCI>pZUSLeGLV~jK*Im>MGEd zT;7ky{1rw!2XjaC$ds^Vq5OoaKgiZ@`vR#zg74;Eo$|A2-+UT~Z@fzbx3@nM3*Mcs4to8pm@Wg&;cYVrTV~+x#OZ0E(Rpa7k>c2V_aZ=FU2rCU z{kP@*LE=CU(J!A9xOCz>bg4fn^XGg^>he~n%Zldq)4$icMXQ7MoOiXWKwEHlo48?% zx!wbN7U(~33#J*KBzn&`g!m0b?rmJ6o1V6mWGJGiwz5uJND2?aa$|nVd33!(%XCUr zY13FW&&Pc@y z@Kx99ZF320DrB?BXU?K4aTXOD5M zA?%jNIr7YF@~i|}D%Q+QzZFa1N)n@R>{iftjoJfkJKx~nlMJ@m>KbSw8mAx6wS@#Ig zw6N->6CMka$lnTon8noPC*Esl1*>VhCLG((3{QS!@Vymxm=1UES`@TQqUw|o%F60| z%J(xWXod6!U*t1ge)Aa1f&V^S+lfX&qYSrLaEHEu%irim0Ri0{{cFyHTpY|??9H6*Or0I=TwOc7&)~s> z9UL57wF(UIU0MvBot^FN?NQL!V9=0j&EXhuxu#;V7`gs99}o~gQIxKLj*E*!>cPH! z`!Ief=va`Ofb|LmTIKNJ!&pV2#Q+;u0D<tihjm@zqU-~bAEa`F=p++eO^ z?IumrI3m`8qt0yti_{*ZPUAOdvB7g=BNZ(M$R#9sBOM85qqToUU0ofriXtK+v_C3& z+8(wEEH)>{Brz%x;vOK?QEqi+W+ry=*Iq}EL81NkBYOxo+6|EGg6+_?MBNag!J;et zgXy<5)^BUvoe~ohgH{L&Mo{rlb_Xgz4X t=t1j2>qQS*4_XgeFM7~=(0XZ4{tLOJpGAbbAcX(`002ovPDHLkV1kgxoG}0Z literal 0 HcmV?d00001 diff --git a/tests/suite/visualize/image.typ b/tests/suite/visualize/image.typ index 36ec06cb1..7c5fb2916 100644 --- a/tests/suite/visualize/image.typ +++ b/tests/suite/visualize/image.typ @@ -258,7 +258,7 @@ A #box(image("/assets/images/tiger.jpg", height: 1cm, width: 80%)) B --- image-png-but-pixmap-format --- #image( read("/assets/images/tiger.jpg", encoding: none), - // Error: 11-18 expected "png", "jpg", "gif", "webp", dictionary, "svg", or auto + // Error: 11-18 expected "png", "jpg", "gif", "webp", dictionary, "svg", "pdf", or auto format: "rgba8", ) @@ -289,3 +289,16 @@ A #box(image("/assets/images/tiger.jpg", height: 1cm, width: 80%)) B ..rotations.map(v => raw(str(v), lang: "typc")), ..rotations.map(rotated) ) + +--- image-pdf --- +#image("/assets/images/matplotlib.pdf") + +--- image-pdf-multiple-pages --- +#image("/assets/images/diagrams.pdf", page: 1) +#image("/assets/images/diagrams.pdf", page: 3) +#image("/assets/images/diagrams.pdf", page: 2) + +--- image-pdf-invalid-page --- +// Error: 2-49 page 2 does not exist +// Hint: 2-49 the document only has 1 page +#image("/assets/images/matplotlib.pdf", page: 2) From 78355421ad73fdcbe93b4acca890b439c4b6f98d Mon Sep 17 00:00:00 2001 From: Laurenz Date: Tue, 22 Jul 2025 14:07:29 +0200 Subject: [PATCH 09/11] Add `pdf` extension to image autocompletions (#6643) --- crates/typst-ide/src/complete.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/typst-ide/src/complete.rs b/crates/typst-ide/src/complete.rs index 87b592ec0..d2c1040b4 100644 --- a/crates/typst-ide/src/complete.rs +++ b/crates/typst-ide/src/complete.rs @@ -834,7 +834,7 @@ fn param_value_completions<'a>( fn path_completion(func: &Func, param: &ParamInfo) -> Option<&'static [&'static str]> { Some(match (func.name(), param.name) { (Some("image"), "source") => { - &["png", "jpg", "jpeg", "gif", "svg", "svgz", "webp"] + &["png", "jpg", "jpeg", "gif", "svg", "svgz", "webp", "pdf"] } (Some("csv"), "source") => &["csv"], (Some("plugin"), "source") => &["wasm"], From 7278d887cf05fadc9a96478830e5876739b78f53 Mon Sep 17 00:00:00 2001 From: Tobias Schmitz Date: Wed, 23 Jul 2025 16:17:03 +0200 Subject: [PATCH 10/11] Fix bounding box computation for lines in curves (#6647) Co-authored-by: Laurenz --- crates/typst-library/src/visualize/curve.rs | 26 +++++++------------- tests/ref/curve-stroke-gradient-sharp.png | Bin 0 -> 399 bytes tests/ref/curve-stroke-gradient.png | Bin 2136 -> 2367 bytes tests/suite/visualize/curve.typ | 10 ++++++++ 4 files changed, 19 insertions(+), 17 deletions(-) create mode 100644 tests/ref/curve-stroke-gradient-sharp.png diff --git a/crates/typst-library/src/visualize/curve.rs b/crates/typst-library/src/visualize/curve.rs index 4bc5b45fb..9f4a21a4e 100644 --- a/crates/typst-library/src/visualize/curve.rs +++ b/crates/typst-library/src/visualize/curve.rs @@ -476,26 +476,18 @@ impl Curve { /// Computes the size of the bounding box of this curve. pub fn bbox_size(&self) -> Size { - let mut min_x = Abs::inf(); - let mut min_y = Abs::inf(); - let mut max_x = -Abs::inf(); - let mut max_y = -Abs::inf(); + let mut min = Point::splat(Abs::inf()); + let mut max = Point::splat(-Abs::inf()); let mut cursor = Point::zero(); for item in self.0.iter() { match item { CurveItem::Move(to) => { - min_x = min_x.min(cursor.x); - min_y = min_y.min(cursor.y); - max_x = max_x.max(cursor.x); - max_y = max_y.max(cursor.y); cursor = *to; } CurveItem::Line(to) => { - min_x = min_x.min(cursor.x); - min_y = min_y.min(cursor.y); - max_x = max_x.max(cursor.x); - max_y = max_y.max(cursor.y); + min = min.min(cursor).min(*to); + max = max.max(cursor).max(*to); cursor = *to; } CurveItem::Cubic(c0, c1, end) => { @@ -507,17 +499,17 @@ impl Curve { ); let bbox = cubic.bounding_box(); - min_x = min_x.min(Abs::pt(bbox.x0)).min(Abs::pt(bbox.x1)); - min_y = min_y.min(Abs::pt(bbox.y0)).min(Abs::pt(bbox.y1)); - max_x = max_x.max(Abs::pt(bbox.x0)).max(Abs::pt(bbox.x1)); - max_y = max_y.max(Abs::pt(bbox.y0)).max(Abs::pt(bbox.y1)); + min.x = min.x.min(Abs::pt(bbox.x0)).min(Abs::pt(bbox.x1)); + min.y = min.y.min(Abs::pt(bbox.y0)).min(Abs::pt(bbox.y1)); + max.x = max.x.max(Abs::pt(bbox.x0)).max(Abs::pt(bbox.x1)); + max.y = max.y.max(Abs::pt(bbox.y0)).max(Abs::pt(bbox.y1)); cursor = *end; } CurveItem::Close => (), } } - Size::new(max_x - min_x, max_y - min_y) + Size::new(max.x - min.x, max.y - min.y) } } diff --git a/tests/ref/curve-stroke-gradient-sharp.png b/tests/ref/curve-stroke-gradient-sharp.png new file mode 100644 index 0000000000000000000000000000000000000000..ae2a86ef02f1f159616ad435e783991f0ab12783 GIT binary patch literal 399 zcmV;A0dW3_P)00`0000CP)t-s|NsC0 zK{lgsl>l_v$KM!+0003#NklN7p^61K6aES-76Gu{m2-r#3ca`;P8mjp-g%PNz1}nYNrx zZK5-6X`O<=Mr?VVa==Dxd7WawY+FvJ6i=s=oK7LOP9b?+3qy2v3G%&-M?GG^#x(;1x( zc{<&4PNyTDPB)y>>42xx?Z$Pw?CT(#&FFN|*8#HCh)$P$9f+%n>vX}_fw-!S&bO&f zKSy+d#+cTdT#>$W^)&UB3IgKkwV?%L)q(*48xAR8v#a#)kl8 z==C-9@Lu-|^qid;uun~G{jYeyZ(sVW_hXc!`yx!bkDFyJJl<@+JJZS8#^#CP_2a?% zVQWX@9m9A$Tys_b&KY)FwsG>`(_cEnI|iDolqYyYiS?(?`zI=cq~$zQQOeiL_@2GQ zfIsS8-^!}#Gt#VzOqZo^)idj^k@3Up7WMwtCzKGb?X%_DmH0Q1F%fpTE=S$kMG9nB zoxhB5X%}f(c*yYiG*-O(^A4*w6*iGevxrgMzFYH@>Z;Z$Z8=-s8oZ0)<=Uq}Wl=sH z_!p^eYv$=;1zBxyk;p|48ElSu~SC zu7@mr@E|U_va_;Ho^{RpN?SJ7Xm`ApSh+!t{nOTpaDs)Q3zsB zc!1u;Z4xJ3mC%zXw-Eia9K>}kcQB_Cgq^NK2-<)mQtO|l7nCGcbRH%#OXI*G^n<_j zBHfFKEBP0HA7vH~GiD70bilJ}w6~UzagG{i&MlWk(hnz0Me*H|w}5;x*|#|bA-`5T z?$KtKo1FS#GM$%;F}2nO7Yi`;&Zo_Mw%QUd4tsz?_ruoh&+B`Nh3Fb9f<6m}ls~NX zQ9Q5B_dwsq0_#zOG-I$*r1@ixCv$G<AYT&gW1}IO0ji>*>)^2c4!x;2F9MA-pXt$0X}*`^rX-w1I70jX7Ac!O~bN# zR@(utUYToYE0L`WpN7s11>k4~6vHph;9AZKgTlgmvKF99CG2f?erHMoQ5uE<6Ts7q zDq`x!phWqqi|>2;ki{=zC(<5eUVuc}aKslvKf{lxAA8~7wB4sdB!MBTYxkf*lWwY~ zFo4W8ge1#|`x?EIM=b|7ZGN1|#7ILXEMQ3(=oM56vESH@mxmd%PC>wm(_I=K z&^u#Nb&br7tR8B!79%#2(@<`cooTIvH#gwc;X{dBbg@>!LGRyDO-Itl3 z9Xo_X-spOWw+8tFtE)wA09UGNyM;uG#Ku0)3M~k)cA)t1pVM7Jap*u64D>upuaV+_ zL@HySBG62&J4B$}Vd+yxNZZ0(-o|@f=X8O*R}c%2(`{6+7oPfYSMjQ1u~Ys6R)U~; zF|{&awTCBsro7$aHZ5^Zt|O%&w#>l`a&B$UVGtmZAdXfp+r-|D3jA&AMEYlxE687T zxN4cg!nE>l=~ReyWwUpnbCTsv0Va@AOLp^h^PxX{M0-1dj}#0$F|n~_Y)s-i=4}A7 zW^yPcOA>DUE2kz&14(mcnk1Dn=V%4gWqBYJ0$TS(Z{+;kqaryYUASQn6I!7c4Zh~i zy)Ej%%C&0}HQ-HyVcf*1Ugw!oXs>1q(MQ|xyq?+z&%&FYUBD=t^y4l;5qn)WH?scE zEo4r@t`Qvzf+JI_o(L>u@4xb7r5Jp41S){k@cP(Z@y2^03}v=Hl({Zb$SLh_3dR3J z@s~cA(_Wnc@X^5l2F|&sU;*<}4^6{ncOk z7nG=Y*jqI(GAGDUT!jQm-FU?r^aBfhR19qp&n#{!EV6(Y94Q|**_cZ-|M!8$_W@kA zH8~rmK4IH9((I@GT6R|)FQ@8+#%C;$eb=MVu+OM}M0tgj(uAwTV~&vb$ZZQ&qWXJH zUEUT@vq0Y;t#;R=>iiZTcmf43Vf2=g@~+cOKI*z%EP0UEX|5G z!xhmtln~S3%2FSWP~0l3IR~f878d@SyWl3ebj{|ado9MW!elrRyBbQ&C)9r`JhU)c zs(Ew`B9XDb|57lwxij|>Ovc&r;f*~sPoI^73=eRD6T*VCUh~XOXBL-10-@?Z`K0np z$8?L=&B@1BA~hy=6b*hIYVNE%i?jc%R6V^9iOhwpn@PR-df>kG54RV%f;fYhD*L8W zu_kcQDy*YCnJH;gc}4@hU)a<*84Ctp1;7~VB4*?Gd4{3Bx{r)Qql*mQ5;U-Lc@Vy&5h0(EGg)XVO+)Y)D8<4V--abJQ5Dku{TM=?q zL&Xi1ys5ZmSteW)mK_ok2#*3IRFh*85GZvAD0^|oa=&d-ZZ|W?fw7FiRlIt#n>Kb9 zSUo5!#Q5=7VPlxPN2(^qe!?5N`}V+X1DQbvD#;m~ZpsN6gA{pCmuyqY2wXh^9fFq% zh9|{0j`rXGo)US(=-|X$cHeQABqTU(!^vYpcK?b_BbL-RvPV|pWqBC;5WeO2S=&aE z-+ae+5}EQOLZLG1l0%(jmnI&V6u@sSVTY@yz7IMR3)f|3XBZ@RQ5^MSZt-xd z6BYK$y7>>wzL$iUK^h&_+3)(|m@y5_+IFP5Gi`qF_daS)yKoIw+K=yieNj+R0ad&n zlq&5R7kEZ{p6?}`kD(ED{Lo8%>iATSV9LJ5E|**jT{|>u3AJH2e%wX0$5+)06Gq)> T;tyWX#Yhbw7z#A{AI$zgPrz

hOrKa$=`)0G+; z8hR8mNJpM;k;`3M6S=1(?g-G((6*$2o&hKNCI(1R0VMM$u}`IP$VcC83}r_zBhw&w z8Wr-PF(E1{>QmBcZIm|ZWU{|zn*I{sXqR$@WN;?`p`NSm@&gZE*Y-Yy+P3#4^K*lj z-D5s0dOyc}|MztFsmX-GV_stC;DPCNe?>x@i@k650>?LJ(Z#fnTvN9Acw1=Dh~w(8 z8;uQY+xsG$_LR5fRuXRb^x4L4GyBA_M>77P^6W&SYp9zvKu@Mjf7bM4Hkh7rhbwFp zeJ_3Wo%Xq4?qK?4!yRsHgKTGLfhDdsUdg7fU-`Nt7Ou%XNadyfoMQM+tJ|MwI{B-=y~aqKwjp>r?VC`rcDkCS(pA6 zaYQ^9tV>TC9P}ka_YYn$18N@ zA2P&JLxwaFPyx_dWOH6k!heD|H?v#wa_rGKf$o^ZoOUd8fF`d84DGJE@>zzM_EHRi zEL76ec#5}e4e6y{Lh;sfmLc>U?>xYxWshGMQ)_*PvnQczRkC$h|1dEYyeVD=VJw} zIGABpFHS3JWfLkE3yX z!n76Ck(nVvHZba0wp2*)hdTnmH@{w6Or7Sw!Rq9SH+Vw;;e=4YshWu9*oCnYv3`PszoDO&r7t`c_a;E-NFzon>Vec3r*(b9&$|xLtlcZ zo?gj8v1jh&Bsg1Gp$qbaMlP#pDXmY{z@yC94_~q}a1*$p+3N)X4@8D4*D}pqJ{}9w zs&6RBQ(SggLmR~8raTX9gb7bB(J>@V2jUbza3 z*J0I~*C?6)MB4eT>fd`^;L23;G6t2Dfk(4n2%Him65?MkWMg$Vep~=N%UDQ9&%|yl z*^_ZC?n@uK^9-_PikFo(tCVfO?#VzKXF0CtxXZzhQOIBjy=;RNm(vvMuwj!>pXr>* zwo+M;-Xcm=TQJy-GjDNjs)|@A?(~AHFg@;wr5Z4dh^fMEht;%*WU}n1bcLjywF7+N z4E}S0a<$5Sz9xu=-Ck|F+RqpIF`e_-7%J-Kpa1WtvgePC8jJGyjA_4pg52utUt?7r zH6I1>_xtcUqruBn88D(S#1{z7mJgH~W*0m4{8Za=cxjG23z5o|qgUL&AI68xKVF)j z4czlD`}UKi&H3mB}0-8m^)Nqb80i;XcMk6A~MAbnJ%6*4toA6wYL z(zyz^-e^%9>R_f36QwPLVtom?l&v;jn zVJcGI{dlzK;k%>_apUqAyMx!moy&9bxptQ7sh6LnH&qYj%&jg(7#M;wc@GePxrn zdWh{=^V1RHbD*)`+ApdCz9cKT-vqtF;v*XaqhjIPVH0ac^* zk(Vlt=HQfzv!bFRgM~IkWa{XrNzhnBKlp4Gds< zPT~Vk?uLE96<9}w0WF2xQ5PUDLHsj8qJ)yTXAa3`X(v6((o-v{H4#QyV955xZ!gzW we+-Q}ZYuIa4&{y1V!zVo|2wG_bql{_Y30YfTYH{^{4r=yh<;$X*Y7F+1=KVITL1t6 diff --git a/tests/suite/visualize/curve.typ b/tests/suite/visualize/curve.typ index 14a1c0cc8..c94f763c4 100644 --- a/tests/suite/visualize/curve.typ +++ b/tests/suite/visualize/curve.typ @@ -130,6 +130,16 @@ down, up, down, up, down, ) +--- curve-stroke-gradient-sharp --- +#set page(width: auto) +#let down = curve.line((40pt, 40pt), relative: true) +#let up = curve.line((40pt, -40pt), relative: true) + +#curve( + stroke: 4pt + gradient.linear(red, blue).sharp(3), + down, up, down, up, down, +) + --- curve-fill-rule --- #stack( dir: ltr, From e9f1b5825a9d37ca0c173a7b2830ba36a27ca9e0 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Thu, 24 Jul 2025 13:34:08 +0200 Subject: [PATCH 11/11] Lint for iterations over hash types (#6652) --- Cargo.toml | 1 + crates/typst-cli/src/watch.rs | 1 + crates/typst-cli/src/world.rs | 1 + 3 files changed, 3 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 500d116a6..259a8a9f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -159,6 +159,7 @@ strip = true [workspace.lints.clippy] blocks_in_conditions = "allow" comparison_chain = "allow" +iter_over_hash_type = "warn" manual_range_contains = "allow" mutable_key_type = "allow" uninlined_format_args = "warn" diff --git a/crates/typst-cli/src/watch.rs b/crates/typst-cli/src/watch.rs index 765f86808..151c0ca1d 100644 --- a/crates/typst-cli/src/watch.rs +++ b/crates/typst-cli/src/watch.rs @@ -139,6 +139,7 @@ impl Watcher { fn update(&mut self, iter: impl IntoIterator) -> StrResult<()> { // Mark all files as not "seen" so that we may unwatch them if they // aren't in the dependency list. + #[allow(clippy::iter_over_hash_type, reason = "order does not matter")] for seen in self.watched.values_mut() { *seen = false; } diff --git a/crates/typst-cli/src/world.rs b/crates/typst-cli/src/world.rs index 42083ef20..34ebda64b 100644 --- a/crates/typst-cli/src/world.rs +++ b/crates/typst-cli/src/world.rs @@ -173,6 +173,7 @@ impl SystemWorld { /// Reset the compilation state in preparation of a new compilation. pub fn reset(&mut self) { + #[allow(clippy::iter_over_hash_type, reason = "order does not matter")] for slot in self.slots.get_mut().values_mut() { slot.reset(); }