repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/main.rs | crates/typst-cli/src/main.rs | mod args;
mod compile;
mod completions;
mod deps;
mod download;
mod eval;
mod fonts;
mod greet;
mod info;
mod init;
mod package;
mod query;
#[cfg(feature = "http-server")]
mod server;
mod terminal;
mod timings;
#[cfg(feature = "self-update")]
mod update;
mod watch;
mod world;
use std::cell::Cell;
use std::io::{self, Write};
use std::process::ExitCode;
use std::sync::LazyLock;
use clap::Parser;
use clap::error::ErrorKind;
use codespan_reporting::term;
use codespan_reporting::term::termcolor::WriteColor;
use ecow::eco_format;
use serde::Serialize;
use typst::diag::{HintedStrResult, StrResult};
use crate::args::{CliArguments, Command, SerializationFormat};
use crate::timings::Timer;
thread_local! {
/// The CLI's exit code.
static EXIT: Cell<ExitCode> = const { Cell::new(ExitCode::SUCCESS) };
}
/// The parsed command line arguments.
static ARGS: LazyLock<CliArguments> = LazyLock::new(|| {
CliArguments::try_parse().unwrap_or_else(|error| {
if error.kind() == ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand {
crate::greet::greet();
}
error.exit();
})
});
/// Entry point.
fn main() -> ExitCode {
// Handle SIGPIPE
// https://stackoverflow.com/questions/65755853/simple-word-count-rust-program-outputs-valid-stdout-but-panicks-when-piped-to-he/65760807
sigpipe::reset();
let res = dispatch();
if let Err(msg) = res {
set_failed();
print_error(msg.message()).expect("failed to print error");
for hint in msg.hints() {
print_hint(hint).expect("failed to print hint");
}
}
EXIT.with(|cell| cell.get())
}
/// Execute the requested command.
fn dispatch() -> HintedStrResult<()> {
let mut timer = Timer::new(&ARGS);
match &ARGS.command {
Command::Compile(command) => crate::compile::compile(&mut timer, command)?,
Command::Watch(command) => crate::watch::watch(&mut timer, command)?,
Command::Init(command) => crate::init::init(command)?,
Command::Query(command) => crate::query::query(command)?,
Command::Eval(command) => crate::eval::eval(command)?,
Command::Fonts(command) => crate::fonts::fonts(command),
Command::Update(command) => crate::update::update(command)?,
Command::Completions(command) => crate::completions::completions(command),
Command::Info(command) => crate::info::info(command)?,
}
Ok(())
}
/// Ensure a failure exit code.
fn set_failed() {
EXIT.with(|cell| cell.set(ExitCode::FAILURE));
}
/// Print an application-level error (independent from a source file).
fn print_error(msg: &str) -> io::Result<()> {
let styles = term::Styles::default();
let mut output = terminal::out();
output.set_color(&styles.header_error)?;
write!(output, "error")?;
output.reset()?;
writeln!(output, ": {msg}")
}
/// Print an application-level hint (independent from a source file).
fn print_hint(msg: &str) -> io::Result<()> {
let styles = term::Styles::default();
let mut output = terminal::out();
output.set_color(&styles.header_help)?;
write!(output, "hint")?;
output.reset()?;
writeln!(output, ": {msg}")
}
/// Serialize data to the output format and convert the error to an
/// [`EcoString`].
fn serialize(
data: &impl Serialize,
format: SerializationFormat,
pretty: bool,
) -> StrResult<String> {
match format {
SerializationFormat::Json => {
if pretty {
serde_json::to_string_pretty(data).map_err(|e| eco_format!("{e}"))
} else {
serde_json::to_string(data).map_err(|e| eco_format!("{e}"))
}
}
SerializationFormat::Yaml => {
serde_yaml::to_string(data).map_err(|e| eco_format!("{e}"))
}
}
}
#[cfg(not(feature = "self-update"))]
mod update {
use typst::diag::{StrResult, bail};
use crate::args::UpdateCommand;
pub fn update(_: &UpdateCommand) -> StrResult<()> {
bail!(
"self-updating is not enabled for this executable, \
please update with the package manager or mechanism \
used for initial installation",
)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-cli/src/package.rs | crates/typst-cli/src/package.rs | use typst_kit::package::PackageStorage;
use crate::args::PackageArgs;
use crate::download;
/// Returns a new package storage for the given args.
pub fn storage(args: &PackageArgs) -> PackageStorage {
PackageStorage::new(
args.package_cache_path.clone(),
args.package_path.clone(),
download::downloader(),
)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/page.rs | crates/typst-pdf/src/page.rs | use std::num::NonZeroU32;
use krilla::page::{NumberingStyle, PageLabel};
use typst_library::model::Numbering;
pub(crate) trait PageLabelExt {
/// Create a new `PageLabel` from a `Numbering` applied to a page
/// number.
fn generate(numbering: &Numbering, number: u64) -> Option<PageLabel>;
/// Creates an arabic page label with the specified page number.
/// For example, this will display page label `11` when given the page
/// number 11.
fn arabic(number: u64) -> PageLabel;
}
impl PageLabelExt for PageLabel {
fn generate(numbering: &Numbering, number: u64) -> Option<PageLabel> {
{
let Numbering::Pattern(pat) = numbering else {
return None;
};
let (prefix, kind) = pat.pieces.first()?;
// If there is a suffix, we cannot use the common style optimisation,
// since PDF does not provide a suffix field.
let style = if pat.suffix.is_empty() {
use krilla::page::NumberingStyle as Style;
use typst_library::model::NumberingKind as Kind;
match kind {
Kind::Arabic => Some(Style::Arabic),
Kind::LowerRoman => Some(Style::LowerRoman),
Kind::UpperRoman => Some(Style::UpperRoman),
Kind::LowerLatin if number <= 26 => Some(Style::LowerAlpha),
Kind::LowerLatin if number <= 26 => Some(Style::UpperAlpha),
_ => None,
}
} else {
None
};
// Prefix and offset depend on the style: If it is supported by the PDF
// spec, we use the given prefix and an offset. Otherwise, everything
// goes into prefix.
let prefix = if style.is_none() {
Some(pat.apply(&[number]))
} else {
(!prefix.is_empty()).then(|| prefix.clone())
};
let offset = style.and(number.try_into().ok().and_then(NonZeroU32::new));
Some(PageLabel::new(style, prefix.map(Into::into), offset))
}
}
fn arabic(number: u64) -> PageLabel {
PageLabel::new(
Some(NumberingStyle::Arabic),
None,
number.try_into().ok().and_then(NonZeroU32::new),
)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/link.rs | crates/typst-pdf/src/link.rs | use krilla::action::{Action, LinkAction};
use krilla::annotation::Target;
use krilla::destination::XyzDestination;
use krilla::geom as kg;
use typst_library::diag::{At, ExpectInternal, SourceResult, bail};
use typst_library::introspection::DocumentPosition;
use typst_library::layout::{Abs, Point, Size};
use typst_library::model::Destination;
use typst_syntax::Span;
use crate::convert::{FrameContext, GlobalContext, PageIndexConverter};
use crate::tags::{self, AnnotationId, GroupId};
use crate::util::PointExt;
pub(crate) struct LinkAnnotation {
pub kind: LinkAnnotationKind,
pub alt: Option<String>,
pub span: Span,
pub rects: Vec<kg::Rect>,
pub target: Target,
}
pub(crate) enum LinkAnnotationKind {
/// A link annotation that is tagged within a `Link` structure element.
Tagged(AnnotationId),
/// A link annotation within an artifact.
Artifact,
}
pub(crate) fn handle_link(
fc: &mut FrameContext,
gc: &mut GlobalContext,
dest: &Destination,
size: Size,
) -> SourceResult<()> {
let target = match dest {
Destination::Url(u) => {
Target::Action(Action::Link(LinkAction::new(u.to_string())))
}
Destination::Position(p) => {
let Some(dest) =
pos_to_xyz(&gc.page_index_converter, DocumentPosition::Paged(*p))
else {
return Ok(());
};
Target::Destination(krilla::destination::Destination::Xyz(dest))
}
Destination::Location(loc) => {
if let Some(nd) = gc.loc_to_names.get(loc) {
// If a named destination has been registered, it's already guaranteed to
// not point to an excluded page.
Target::Destination(krilla::destination::Destination::Named(nd.clone()))
} else {
let pos = gc.document.introspector.position(*loc);
let Some(dest) = pos_to_xyz(&gc.page_index_converter, pos) else {
return Ok(());
};
Target::Destination(krilla::destination::Destination::Xyz(dest))
}
}
};
let rect = bounding_box(fc, size);
if tags::disabled(gc) {
if gc.tags.in_tiling && gc.options.is_pdf_ua() {
let validator = gc.options.standards.config.validator().as_str();
bail!(
Span::detached(),
"{validator} error: PDF artifacts may not contain links";
hint: "a link was used within a tiling";
hint: "references, citations, and footnotes \
are also considered links in PDF";
);
}
fc.push_link_annotation(
GroupId::INVALID,
LinkAnnotation {
kind: LinkAnnotationKind::Artifact,
alt: None,
span: Span::detached(),
rects: vec![rect],
target,
},
);
return Ok(());
}
let (group_id, link) = (gc.tags.tree.parent_link())
.expect_internal("expected link ancestor in logical tree")
.at(Span::detached())?;
let alt = link.alt.as_ref().map(Into::into);
if gc.tags.tree.parent_artifact().is_some() {
if gc.options.is_pdf_ua() {
let validator = gc.options.standards.config.validator().as_str();
bail!(
link.span(),
"{validator} error: PDF artifacts may not contain links";
hint: "references, citations, and footnotes \
are also considered links in PDF";
);
}
fc.push_link_annotation(
group_id,
LinkAnnotation {
kind: LinkAnnotationKind::Artifact,
alt,
span: link.span(),
rects: vec![rect],
target,
},
);
return Ok(());
}
// Unfortunately quadpoints still aren't well supported by most PDF readers.
// So only add multiple quadpoint entries to one annotation when targeting
// PDF/UA. Otherwise generate multiple annotations, to avoid pdf readers
// falling back to the bounding box rectangle, which can span parts unrelated
// to the link. For example if there is a linebreak:
// ```
// Imagine this is a paragraph containing a link. It starts here https://github.com/
// typst/typst and then ends on another line.
// ```
// The bounding box would span the entire paragraph, which is undesirable.
let join_annotations = gc.options.is_pdf_ua();
match fc.get_link_annotation(group_id) {
Some(annotation) if join_annotations => annotation.rects.push(rect),
_ => {
let annot_id = gc.tags.annotations.reserve();
fc.push_link_annotation(
group_id,
LinkAnnotation {
kind: LinkAnnotationKind::Tagged(annot_id),
alt,
span: link.span(),
rects: vec![rect],
target,
},
);
let group = gc.tags.tree.groups.get_mut(group_id);
group.push_annotation(annot_id);
}
}
Ok(())
}
/// Compute the bounding box of the transformed rectangle for this frame.
fn bounding_box(fc: &FrameContext, size: Size) -> kg::Rect {
let pos = Point::zero();
let points = [
pos + Point::with_y(size.y),
pos + size.to_point(),
pos + Point::with_x(size.x),
pos,
];
let mut min_x = f32::INFINITY;
let mut min_y = f32::INFINITY;
let mut max_x = f32::NEG_INFINITY;
let mut max_y = f32::NEG_INFINITY;
for point in points {
let p = point.transform(fc.state().transform()).to_krilla();
min_x = min_x.min(p.x);
min_y = min_y.min(p.y);
max_x = max_x.max(p.x);
max_y = max_y.max(p.y);
}
kg::Rect::from_ltrb(min_x, min_y, max_x, max_y).unwrap()
}
/// Turns a position link into a PDF XYZ destination.
///
/// - Takes into account page index conversion (if only part of the document is
/// exported)
/// - Consistently shifts the link by 10pt because the position of e.g.
/// backlinks to footnotes is always at the baseline and if you link directly
/// to it, the text will not be visible since it is right above.
pub(crate) fn pos_to_xyz(
pic: &PageIndexConverter,
pos: DocumentPosition,
) -> Option<XyzDestination> {
let pos = pos.as_paged()?;
let page_index = pic.pdf_page_index(pos.page.get() - 1)?;
let adjusted =
Point::new(pos.point.x, (pos.point.y - Abs::pt(10.0)).max(Abs::zero()));
Some(XyzDestination::new(page_index, adjusted.to_krilla()))
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/paint.rs | crates/typst-pdf/src/paint.rs | //! Convert paint types from Typst to krilla.
use krilla::color::{self, cmyk, luma, rgb};
use krilla::num::NormalizedF32;
use krilla::paint::{
Fill, LinearGradient, Pattern, RadialGradient, SpreadMethod, Stop, Stroke,
StrokeDash, SweepGradient,
};
use krilla::surface::Surface;
use typst_library::diag::SourceResult;
use typst_library::layout::{Abs, Angle, Quadrant, Ratio, Size, Transform};
use typst_library::visualize::{
Color, ColorSpace, DashPattern, FillRule, FixedStroke, Gradient, Paint, RatioOrAngle,
RelativeTo, Tiling, WeightedColor,
};
use typst_utils::Numeric;
use crate::convert::{FrameContext, GlobalContext, State, handle_frame};
use crate::tags;
use crate::util::{AbsExt, FillRuleExt, LineCapExt, LineJoinExt, TransformExt};
pub(crate) fn convert_fill(
gc: &mut GlobalContext,
paint_: &Paint,
fill_rule_: FillRule,
on_text: bool,
surface: &mut Surface,
state: &State,
size: Size,
) -> SourceResult<Fill> {
let (paint, opacity) = convert_paint(gc, paint_, on_text, surface, state, size)?;
Ok(Fill {
paint,
rule: fill_rule_.to_krilla(),
opacity: NormalizedF32::new(opacity as f32 / 255.0).unwrap(),
})
}
pub(crate) fn convert_stroke(
fc: &mut GlobalContext,
stroke: &FixedStroke,
on_text: bool,
surface: &mut Surface,
state: &State,
size: Size,
) -> SourceResult<Stroke> {
let (paint, opacity) =
convert_paint(fc, &stroke.paint, on_text, surface, state, size)?;
Ok(Stroke {
paint,
width: stroke.thickness.to_f32(),
miter_limit: stroke.miter_limit.get() as f32,
line_join: stroke.join.to_krilla(),
line_cap: stroke.cap.to_krilla(),
opacity: NormalizedF32::new(opacity as f32 / 255.0).unwrap(),
dash: stroke.dash.as_ref().map(convert_dash),
})
}
fn convert_paint(
gc: &mut GlobalContext,
paint: &Paint,
on_text: bool,
surface: &mut Surface,
state: &State,
mut size: Size,
) -> SourceResult<(krilla::paint::Paint, u8)> {
// Edge cases for strokes.
if size.x.is_zero() {
size.x = Abs::pt(1.0);
}
if size.y.is_zero() {
size.y = Abs::pt(1.0);
}
match paint {
Paint::Solid(c) => {
let (c, a) = convert_solid(c);
Ok((c.into(), a))
}
Paint::Gradient(g) => Ok(convert_gradient(g, on_text, state, size)),
Paint::Tiling(p) => convert_pattern(gc, p, on_text, surface, state),
}
}
fn convert_solid(color: &Color) -> (color::Color, u8) {
match color.space() {
ColorSpace::D65Gray => {
let (c, a) = convert_luma(color);
(c.into(), a)
}
ColorSpace::Cmyk => (convert_cmyk(color).into(), 255),
// Convert all other colors in different colors spaces into RGB.
_ => {
let (c, a) = convert_rgb(color);
(c.into(), a)
}
}
}
fn convert_cmyk(color: &Color) -> cmyk::Color {
let components = color.to_space(ColorSpace::Cmyk).to_vec4_u8();
cmyk::Color::new(components[0], components[1], components[2], components[3])
}
fn convert_rgb(color: &Color) -> (rgb::Color, u8) {
let components = color.to_space(ColorSpace::Srgb).to_vec4_u8();
(rgb::Color::new(components[0], components[1], components[2]), components[3])
}
fn convert_luma(color: &Color) -> (luma::Color, u8) {
let components = color.to_space(ColorSpace::D65Gray).to_vec4_u8();
(luma::Color::new(components[0]), components[3])
}
fn convert_pattern(
gc: &mut GlobalContext,
pattern: &Tiling,
on_text: bool,
surface: &mut Surface,
state: &State,
) -> SourceResult<(krilla::paint::Paint, u8)> {
let transform = correct_transform(state, pattern.unwrap_relative(on_text));
let mut stream_builder = surface.stream_builder();
let mut surface = stream_builder.surface();
tags::tiling(gc, &mut surface, |gc, surface| {
let mut fc = FrameContext::new(None, pattern.frame().size());
handle_frame(&mut fc, pattern.frame(), None, surface, gc)
})?;
surface.finish();
let stream = stream_builder.finish();
let pattern = Pattern {
stream,
transform: transform.to_krilla(),
width: (pattern.size().x + pattern.spacing().x).to_pt() as _,
height: (pattern.size().y + pattern.spacing().y).to_pt() as _,
};
Ok((pattern.into(), 255))
}
fn convert_gradient(
gradient: &Gradient,
on_text: bool,
state: &State,
size: Size,
) -> (krilla::paint::Paint, u8) {
let size = match gradient.unwrap_relative(on_text) {
RelativeTo::Self_ => size,
RelativeTo::Parent => state.container_size(),
};
let mut angle = gradient.angle().unwrap_or_else(Angle::zero);
let base_transform = correct_transform(state, gradient.unwrap_relative(on_text));
let stops = convert_gradient_stops(gradient);
match &gradient {
Gradient::Linear(_) => {
angle = Gradient::correct_aspect_ratio(angle, size.aspect_ratio());
let (x1, y1, x2, y2) = {
let (mut sin, mut cos) = (angle.sin(), angle.cos());
// Scale to edges of unit square.
let factor = cos.abs() + sin.abs();
sin *= factor;
cos *= factor;
match angle.quadrant() {
Quadrant::First => (0.0, 0.0, cos as f32, sin as f32),
Quadrant::Second => (1.0, 0.0, cos as f32 + 1.0, sin as f32),
Quadrant::Third => (1.0, 1.0, cos as f32 + 1.0, sin as f32 + 1.0),
Quadrant::Fourth => (0.0, 1.0, cos as f32, sin as f32 + 1.0),
}
};
let linear = LinearGradient {
x1,
y1,
x2,
y2,
// x and y coordinates are normalized, so need to scale by the size.
transform: base_transform
.pre_concat(Transform::scale(
Ratio::new(size.x.to_f32() as f64),
Ratio::new(size.y.to_f32() as f64),
))
.to_krilla(),
spread_method: SpreadMethod::Pad,
stops,
anti_alias: gradient.anti_alias(),
};
(linear.into(), 255)
}
Gradient::Radial(radial) => {
let radial = RadialGradient {
fx: radial.focal_center.x.get() as f32,
fy: radial.focal_center.y.get() as f32,
fr: radial.focal_radius.get() as f32,
cx: radial.center.x.get() as f32,
cy: radial.center.y.get() as f32,
cr: radial.radius.get() as f32,
transform: base_transform
.pre_concat(Transform::scale(
Ratio::new(size.x.to_f32() as f64),
Ratio::new(size.y.to_f32() as f64),
))
.to_krilla(),
spread_method: SpreadMethod::Pad,
stops,
anti_alias: gradient.anti_alias(),
};
(radial.into(), 255)
}
Gradient::Conic(conic) => {
// Correct the gradient's angle.
let cx = size.x.to_f32() * conic.center.x.get() as f32;
let cy = size.y.to_f32() * conic.center.y.get() as f32;
let actual_transform = base_transform
// Adjust for the angle.
.pre_concat(Transform::rotate_at(
angle,
Abs::pt(cx as f64),
Abs::pt(cy as f64),
))
// Default start point in krilla and Typst are at the opposite side, so we need
// to flip it horizontally.
.pre_concat(Transform::scale_at(
-Ratio::one(),
Ratio::one(),
Abs::pt(cx as f64),
Abs::pt(cy as f64),
));
let sweep = SweepGradient {
cx,
cy,
start_angle: 0.0,
end_angle: 360.0,
transform: actual_transform.to_krilla(),
spread_method: SpreadMethod::Pad,
stops,
anti_alias: gradient.anti_alias(),
};
(sweep.into(), 255)
}
}
}
fn convert_gradient_stops(gradient: &Gradient) -> Vec<Stop> {
let mut stops = vec![];
let use_cmyk = gradient.stops().iter().all(|s| s.color.space() == ColorSpace::Cmyk);
let mut add_single = |color: &Color, offset: Ratio| {
let (color, opacity) = if use_cmyk {
(convert_cmyk(color).into(), 255)
} else {
let (c, a) = convert_rgb(color);
(c.into(), a)
};
let opacity = NormalizedF32::new((opacity as f32) / 255.0).unwrap();
let offset = NormalizedF32::new(offset.get() as f32).unwrap();
let stop = Stop { offset, color, opacity };
stops.push(stop);
};
// Convert stops.
match &gradient {
Gradient::Linear(_) | Gradient::Radial(_) => {
if let Some(s) = gradient.stops().first() {
add_single(&s.color, s.offset.unwrap());
}
// Create the individual gradient functions for each pair of stops.
for window in gradient.stops().windows(2) {
let (first, second) = (window[0], window[1]);
// If we have a hue index or are using Oklab, we will create several
// stops in-between to make the gradient smoother without interpolation
// issues with native color spaces.
if gradient.space().hue_index().is_some()
|| gradient.space() == ColorSpace::Oklab
{
for i in 0..=32 {
let t = i as f64 / 32.0;
let real_t = Ratio::new(
first.offset.unwrap().get() * (1.0 - t)
+ second.offset.unwrap().get() * t,
);
let c = gradient.sample(RatioOrAngle::Ratio(real_t));
add_single(&c, real_t);
}
}
add_single(&second.color, second.offset.unwrap());
}
}
Gradient::Conic(conic) => {
if let Some((c, t)) = conic.stops.first() {
add_single(c, *t);
}
for window in conic.stops.windows(2) {
let ((c0, t0), (c1, t1)) = (window[0], window[1]);
// Precision:
// - On an even color, insert a stop every 90deg.
// - For a hue-based color space, insert 200 stops minimum.
// - On any other, insert 20 stops minimum.
let max_dt = if c0 == c1 {
0.25
} else if conic.space.hue_index().is_some() {
0.005
} else {
0.05
};
let mut t_x = t0.get();
let dt = (t1.get() - t0.get()).min(max_dt);
// Special casing for sharp gradients.
if t0 == t1 {
add_single(&c1, t1);
continue;
}
while t_x < t1.get() {
let t_next = (t_x + dt).min(t1.get());
// The current progress in the current window.
let t = |t| (t - t0.get()) / (t1.get() - t0.get());
let c_next = Color::mix_iter(
[
WeightedColor::new(c0, 1.0 - t(t_next)),
WeightedColor::new(c1, t(t_next)),
],
conic.space,
)
.unwrap();
add_single(&c_next, Ratio::new(t_next));
t_x = t_next;
}
add_single(&c1, t1);
}
}
}
stops
}
fn convert_dash(dash: &DashPattern<Abs, Abs>) -> StrokeDash {
StrokeDash {
array: dash.array.iter().map(|e| e.to_f32()).collect(),
offset: dash.phase.to_f32(),
}
}
fn correct_transform(state: &State, relative: RelativeTo) -> Transform {
// In krilla, if we have a shape with a transform and a complex paint,
// then the paint will inherit the transform of the shape.
match relative {
// Because of the above, we don't need to apply an additional transform here.
RelativeTo::Self_ => Transform::identity(),
// Because of the above, we need to first reverse the transform that will be
// applied from the shape, and then re-apply the transform that is used for
// the next parent container.
RelativeTo::Parent => state
.transform()
.invert()
.unwrap()
.pre_concat(state.container_transform()),
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/shape.rs | crates/typst-pdf/src/shape.rs | use krilla::geom::{Path, PathBuilder, Rect};
use krilla::surface::Surface;
use typst_library::diag::SourceResult;
use typst_library::visualize::{Geometry, Shape};
use typst_syntax::Span;
use typst_utils::defer;
use crate::convert::{FrameContext, GlobalContext};
use crate::util::{AbsExt, TransformExt, convert_path};
use crate::{paint, tags};
#[typst_macros::time(name = "handle shape")]
pub(crate) fn handle_shape(
fc: &mut FrameContext,
shape: &Shape,
surface: &mut Surface,
gc: &mut GlobalContext,
span: Span,
) -> SourceResult<()> {
let mut handle = tags::shape(gc, fc, surface, shape);
let surface = handle.surface();
surface.set_location(span.into_raw());
surface.push_transform(&fc.state().transform().to_krilla());
let mut surface = defer(surface, |s| {
s.pop();
s.reset_location();
});
if let Some(path) = convert_geometry(&shape.geometry) {
let fill = if let Some(paint) = &shape.fill {
Some(paint::convert_fill(
gc,
paint,
shape.fill_rule,
false,
&mut surface,
fc.state(),
shape.geometry.bbox_size(),
)?)
} else {
None
};
let stroke = shape.stroke.as_ref().and_then(|stroke| {
if stroke.thickness.to_f32() > 0.0 { Some(stroke) } else { None }
});
let stroke = if let Some(stroke) = &stroke {
let stroke = paint::convert_stroke(
gc,
stroke,
false,
&mut surface,
fc.state(),
shape.geometry.bbox_size(),
)?;
Some(stroke)
} else {
None
};
// Otherwise, krilla will by default fill with a black paint.
if fill.is_some() || stroke.is_some() {
surface.set_fill(fill);
surface.set_stroke(stroke);
surface.draw_path(&path);
}
}
Ok(())
}
fn convert_geometry(geometry: &Geometry) -> Option<Path> {
let mut path_builder = PathBuilder::new();
match geometry {
Geometry::Line(l) => {
path_builder.move_to(0.0, 0.0);
path_builder.line_to(l.x.to_f32(), l.y.to_f32());
}
Geometry::Rect(size) => {
let w = size.x.to_f32();
let h = size.y.to_f32();
let rect = if w < 0.0 || h < 0.0 {
// krilla doesn't normally allow for negative dimensions, but
// Typst supports them, so we apply a transform if needed.
let transform =
krilla::geom::Transform::from_scale(w.signum(), h.signum());
Rect::from_xywh(0.0, 0.0, w.abs(), h.abs())
.and_then(|rect| rect.transform(transform))
} else {
Rect::from_xywh(0.0, 0.0, w, h)
};
if let Some(rect) = rect {
path_builder.push_rect(rect);
}
}
Geometry::Curve(c) => {
convert_path(c, &mut path_builder);
}
}
path_builder.finish()
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/lib.rs | crates/typst-pdf/src/lib.rs | //! Exporting Typst documents to PDF.
mod attach;
mod convert;
mod image;
mod link;
mod metadata;
mod outline;
mod page;
mod paint;
mod shape;
mod tags;
mod text;
mod util;
pub use self::metadata::{Timestamp, Timezone};
use std::fmt::{self, Debug, Formatter};
use ecow::eco_format;
use krilla::configure::Validator;
use serde::{Deserialize, Serialize};
use typst_library::diag::{SourceResult, StrResult, bail};
use typst_library::foundations::Smart;
use typst_library::layout::{PageRanges, PagedDocument};
/// Export a document into a PDF file.
///
/// Returns the raw bytes making up the PDF file.
#[typst_macros::time(name = "pdf")]
pub fn pdf(document: &PagedDocument, options: &PdfOptions) -> SourceResult<Vec<u8>> {
convert::convert(document, options)
}
/// Settings for PDF export.
#[derive(Debug)]
pub struct PdfOptions<'a> {
/// If not `Smart::Auto`, shall be a string that uniquely and stably
/// identifies the document. It should not change between compilations of
/// the same document. **If you cannot provide such a stable identifier,
/// just pass `Smart::Auto` rather than trying to come up with one.** The
/// CLI, for example, does not have a well-defined notion of a long-lived
/// project and as such just passes `Smart::Auto`.
///
/// If an `ident` is given, the hash of it will be used to create a PDF
/// document identifier (the identifier itself is not leaked). If `ident` is
/// `Auto`, a hash of the document's title and author is used instead (which
/// is reasonably unique and stable).
pub ident: Smart<&'a str>,
/// If not `None`, shall be the creation timestamp of the document. It will
/// only be used if `set document(date: ..)` is `auto`.
pub timestamp: Option<Timestamp>,
/// Specifies which ranges of pages should be exported in the PDF. When
/// `None`, all pages should be exported.
pub page_ranges: Option<PageRanges>,
/// A list of PDF standards that Typst will enforce conformance with.
pub standards: PdfStandards,
/// By default, even when not producing a `PDF/UA-1` document, a tagged PDF
/// document is written to provide a baseline of accessibility. In some
/// circumstances, for example when trying to reduce the size of a document,
/// it can be desirable to disable tagged PDF.
pub tagged: bool,
}
impl PdfOptions<'_> {
/// Whether the current export mode is PDF/UA-1, and in the future maybe
/// PDF/UA-2.
pub(crate) fn is_pdf_ua(&self) -> bool {
self.standards.config.validator() == Validator::UA1
}
}
impl Default for PdfOptions<'_> {
fn default() -> Self {
Self {
ident: Smart::Auto,
timestamp: None,
page_ranges: None,
standards: PdfStandards::default(),
tagged: true,
}
}
}
/// Encapsulates a list of compatible PDF standards.
#[derive(Clone)]
pub struct PdfStandards {
pub(crate) config: krilla::configure::Configuration,
}
impl PdfStandards {
/// Validates a list of PDF standards for compatibility and returns their
/// encapsulated representation.
pub fn new(list: &[PdfStandard]) -> StrResult<Self> {
use krilla::configure::{Configuration, PdfVersion, Validator};
let mut version: Option<PdfVersion> = None;
let mut set_version = |v: PdfVersion| -> StrResult<()> {
if let Some(prev) = version {
bail!(
"PDF cannot conform to {} and {} at the same time",
prev.as_str(),
v.as_str(),
);
}
version = Some(v);
Ok(())
};
let mut validator = None;
let mut set_validator = |v: Validator| -> StrResult<()> {
if validator.is_some() {
bail!("Typst currently only supports one PDF substandard at a time");
}
validator = Some(v);
Ok(())
};
for standard in list {
match standard {
PdfStandard::V_1_4 => set_version(PdfVersion::Pdf14)?,
PdfStandard::V_1_5 => set_version(PdfVersion::Pdf15)?,
PdfStandard::V_1_6 => set_version(PdfVersion::Pdf16)?,
PdfStandard::V_1_7 => set_version(PdfVersion::Pdf17)?,
PdfStandard::V_2_0 => set_version(PdfVersion::Pdf20)?,
PdfStandard::A_1b => set_validator(Validator::A1_B)?,
PdfStandard::A_1a => set_validator(Validator::A1_A)?,
PdfStandard::A_2b => set_validator(Validator::A2_B)?,
PdfStandard::A_2u => set_validator(Validator::A2_U)?,
PdfStandard::A_2a => set_validator(Validator::A2_A)?,
PdfStandard::A_3b => set_validator(Validator::A3_B)?,
PdfStandard::A_3u => set_validator(Validator::A3_U)?,
PdfStandard::A_3a => set_validator(Validator::A3_A)?,
PdfStandard::A_4 => set_validator(Validator::A4)?,
PdfStandard::A_4f => set_validator(Validator::A4F)?,
PdfStandard::A_4e => set_validator(Validator::A4E)?,
PdfStandard::Ua_1 => set_validator(Validator::UA1)?,
}
}
let config = match (version, validator) {
(Some(version), Some(validator)) => {
Configuration::new_with(validator, version).ok_or_else(|| {
eco_format!(
"{} is not compatible with {}",
version.as_str(),
validator.as_str()
)
})?
}
(Some(version), None) => Configuration::new_with_version(version),
(None, Some(validator)) => Configuration::new_with_validator(validator),
(None, None) => Configuration::new_with_version(PdfVersion::Pdf17),
};
Ok(Self { config })
}
}
impl Debug for PdfStandards {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.pad("PdfStandards(..)")
}
}
impl Default for PdfStandards {
fn default() -> Self {
use krilla::configure::{Configuration, PdfVersion};
Self {
config: Configuration::new_with_version(PdfVersion::Pdf17),
}
}
}
/// A PDF standard that Typst can enforce conformance with.
///
/// Support for more standards is planned.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
#[allow(non_camel_case_types)]
#[non_exhaustive]
pub enum PdfStandard {
/// PDF 1.4.
#[serde(rename = "1.4")]
V_1_4,
/// PDF 1.5.
#[serde(rename = "1.5")]
V_1_5,
/// PDF 1.5.
#[serde(rename = "1.6")]
V_1_6,
/// PDF 1.7.
#[serde(rename = "1.7")]
V_1_7,
/// PDF 2.0.
#[serde(rename = "2.0")]
V_2_0,
/// PDF/A-1b.
#[serde(rename = "a-1b")]
A_1b,
/// PDF/A-1a.
#[serde(rename = "a-1a")]
A_1a,
/// PDF/A-2b.
#[serde(rename = "a-2b")]
A_2b,
/// PDF/A-2u.
#[serde(rename = "a-2u")]
A_2u,
/// PDF/A-2a.
#[serde(rename = "a-2a")]
A_2a,
/// PDF/A-3b.
#[serde(rename = "a-3b")]
A_3b,
/// PDF/A-3u.
#[serde(rename = "a-3u")]
A_3u,
/// PDF/A-3a.
#[serde(rename = "a-3a")]
A_3a,
/// PDF/A-4.
#[serde(rename = "a-4")]
A_4,
/// PDF/A-4f.
#[serde(rename = "a-4f")]
A_4f,
/// PDF/A-4e.
#[serde(rename = "a-4e")]
A_4e,
/// PDF/UA-1.
#[serde(rename = "ua-1")]
Ua_1,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/convert.rs | crates/typst-pdf/src/convert.rs | use ecow::{EcoVec, eco_format};
use indexmap::IndexMap;
use krilla::configure::{Configuration, ValidationError, Validator};
use krilla::destination::NamedDestination;
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;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
use smallvec::SmallVec;
use typst_library::diag::{
At, ExpectInternal, SourceDiagnostic, SourceResult, bail, error,
};
use typst_library::foundations::{NativeElement, Repr};
use typst_library::introspection::{Location, Tag};
use typst_library::layout::{
Frame, FrameItem, GroupItem, PagedDocument, Size, Transform,
};
use typst_library::model::HeadingElem;
use typst_library::text::Font;
use typst_library::visualize::{Geometry, Paint};
use typst_syntax::Span;
use crate::PdfOptions;
use crate::attach::attach_files;
use crate::image::handle_image;
use crate::link::{LinkAnnotation, handle_link};
use crate::metadata::build_metadata;
use crate::outline::build_outline;
use crate::page::PageLabelExt;
use crate::shape::handle_shape;
use crate::tags::{self, GroupId, Tags};
use crate::text::handle_text;
use crate::util::{AbsExt, TransformExt, convert_path, display_font};
#[typst_macros::time(name = "convert document")]
pub fn convert(
typst_document: &PagedDocument,
options: &PdfOptions,
) -> SourceResult<Vec<u8>> {
let settings = SerializeSettings {
compress_content_streams: true,
no_device_cs: true,
ascii_compatible: false,
xmp_metadata: true,
cmyk_profile: None,
configuration: options.standards.config,
enable_tagging: options.tagged,
render_svg_glyph_fn: render_svg_glyph,
};
let mut document = Document::new_with(settings);
let page_index_converter = PageIndexConverter::new(typst_document, options);
let named_destinations =
collect_named_destinations(typst_document, &page_index_converter);
let tags = tags::init(typst_document, options)?;
let mut gc = GlobalContext::new(
typst_document,
options,
named_destinations,
page_index_converter,
tags,
);
convert_pages(&mut gc, &mut document)?;
attach_files(&gc, &mut document)?;
let (doc_lang, tree) = tags::resolve(&mut gc)?;
document.set_outline(build_outline(&gc));
document.set_metadata(build_metadata(&gc, doc_lang));
document.set_tag_tree(tree);
finish(document, gc, options.standards.config)
}
fn convert_pages(gc: &mut GlobalContext, document: &mut Document) -> SourceResult<()> {
for (i, typst_page) in gc.document.pages.iter().enumerate() {
if gc.page_index_converter.pdf_page_index(i).is_none() {
// Don't export this page.
continue;
}
// PDF 1.4 upwards to 1.7 specifies a minimum page size of 3x3 units.
// PDF 2.0 doesn't define an explicit limit, but krilla and probably
// some viewers won't handle pages that have zero sized pages.
let mut settings = PageSettings::from_wh(
typst_page.frame.width().to_f32().max(3.0),
typst_page.frame.height().to_f32().max(3.0),
)
.expect_internal("invalid page size")
.at(Span::detached())?;
if let Some(label) = typst_page
.numbering
.as_ref()
.and_then(|num| PageLabel::generate(num, typst_page.number))
.or_else(|| {
// When some pages were ignored from export, we show a page label with
// the correct real (not logical) page number.
// This is for consistency with normal output when pages have no numbering
// and all are exported: the final PDF page numbers always correspond to
// the real (not logical) page numbers. Here, the final PDF page number
// will differ, but we can at least use labels to indicate what was
// the corresponding real page number in the Typst document.
gc.page_index_converter
.has_skipped_pages()
.then(|| PageLabel::arabic((i + 1) as u64))
})
{
settings = settings.with_page_label(label);
}
let mut page = document.start_page_with(settings);
let mut surface = page.surface();
let page_idx = gc.page_index_converter.pdf_page_index(i);
let mut fc = FrameContext::new(page_idx, typst_page.frame.size());
tags::page(gc, &mut surface, |gc, surface| {
handle_frame(
&mut fc,
&typst_page.frame,
typst_page.fill_or_transparent(),
surface,
gc,
)
})?;
surface.finish();
let link_annotations = fc.link_annotations.into_values().flatten();
tags::add_link_annotations(gc, &mut page, link_annotations);
}
Ok(())
}
/// A state allowing us to keep track of transforms and container sizes,
/// which is mainly needed to resolve gradients and patterns correctly.
#[derive(Debug, Clone)]
pub(crate) struct State {
/// The current transform.
transform: Transform,
/// The transform of first hard frame in the hierarchy.
container_transform: Transform,
/// The size of the first hard frame in the hierarchy.
container_size: Size,
}
impl State {
/// Creates a new, clean state for a given `size`.
fn new(size: Size) -> Self {
Self {
transform: Transform::identity(),
container_transform: Transform::identity(),
container_size: size,
}
}
pub(crate) fn register_container(&mut self, size: Size) {
self.container_transform = self.transform;
self.container_size = size;
}
pub(crate) fn pre_concat(&mut self, transform: Transform) {
self.transform = self.transform.pre_concat(transform);
}
pub(crate) fn transform(&self) -> Transform {
self.transform
}
pub(crate) fn container_transform(&self) -> Transform {
self.container_transform
}
pub(crate) fn container_size(&self) -> Size {
self.container_size
}
}
/// Context needed for converting a single frame.
pub(crate) struct FrameContext {
/// The logical page index. This might be `None` if the page isn't exported,
/// of if the FrameContext has been built to convert a pattern.
pub(crate) page_idx: Option<usize>,
states: Vec<State>,
/// The link annotations belonging to a Link tag.
link_annotations: IndexMap<GroupId, SmallVec<[LinkAnnotation; 1]>, FxBuildHasher>,
}
impl FrameContext {
pub(crate) fn new(page_idx: Option<usize>, size: Size) -> Self {
Self {
page_idx,
states: vec![State::new(size)],
link_annotations: IndexMap::default(),
}
}
pub(crate) fn push(&mut self) {
self.states.push(self.states.last().unwrap().clone());
}
pub(crate) fn pop(&mut self) {
self.states.pop();
}
pub(crate) fn state(&self) -> &State {
self.states.last().unwrap()
}
pub(crate) fn state_mut(&mut self) -> &mut State {
self.states.last_mut().unwrap()
}
pub(crate) fn get_link_annotation(
&mut self,
id: GroupId,
) -> Option<&mut LinkAnnotation> {
self.link_annotations.get_mut(&id)?.last_mut()
}
pub(crate) fn push_link_annotation(
&mut self,
id: GroupId,
annotation: LinkAnnotation,
) {
let annotations = self.link_annotations.entry(id).or_default();
annotations.push(annotation);
}
}
/// Globally needed context for converting a Typst document.
pub(crate) struct GlobalContext<'a> {
/// Cache the conversion between krilla and Typst fonts (forward and backward).
pub(crate) fonts_forward: FxHashMap<Font, krilla::text::Font>,
pub(crate) fonts_backward: FxHashMap<krilla::text::Font, Font>,
/// Mapping between images and their span.
// Note: In theory, the same image can have multiple spans
// if it appears in the document multiple times. We just store the
// first appearance, though.
pub(crate) image_to_spans: FxHashMap<krilla::image::Image, Span>,
/// The spans of all images that appear in the document. We use this so
/// we can give more accurate error messages.
pub(crate) image_spans: FxHashSet<Span>,
/// The document to convert.
pub(crate) document: &'a PagedDocument,
/// Options for PDF export.
pub(crate) options: &'a PdfOptions<'a>,
/// Mapping between locations in the document and named destinations.
pub(crate) loc_to_names: FxHashMap<Location, NamedDestination>,
pub(crate) page_index_converter: PageIndexConverter,
/// Tagged PDF context.
pub(crate) tags: Tags,
}
impl<'a> GlobalContext<'a> {
pub(crate) fn new(
document: &'a PagedDocument,
options: &'a PdfOptions,
loc_to_names: FxHashMap<Location, NamedDestination>,
page_index_converter: PageIndexConverter,
tags: Tags,
) -> GlobalContext<'a> {
Self {
fonts_forward: FxHashMap::default(),
fonts_backward: FxHashMap::default(),
document,
options,
loc_to_names,
image_to_spans: FxHashMap::default(),
image_spans: FxHashSet::default(),
page_index_converter,
tags,
}
}
}
#[typst_macros::time(name = "handle page")]
pub(crate) fn handle_frame(
fc: &mut FrameContext,
frame: &Frame,
fill: Option<Paint>,
surface: &mut Surface,
gc: &mut GlobalContext,
) -> SourceResult<()> {
fc.push();
if frame.kind().is_hard() {
fc.state_mut().register_container(frame.size());
}
if let Some(fill) = fill {
let shape = Geometry::Rect(frame.size()).filled(fill);
handle_shape(fc, &shape, surface, gc, Span::detached())?;
}
for (point, item) in frame.items() {
fc.push();
fc.state_mut().pre_concat(Transform::translate(point.x, point.y));
match item {
FrameItem::Group(g) => handle_group(fc, g, surface, gc)?,
FrameItem::Text(t) => handle_text(fc, t, surface, gc)?,
FrameItem::Shape(s, span) => handle_shape(fc, s, surface, gc, *span)?,
FrameItem::Image(image, size, span) => {
handle_image(gc, fc, image, *size, surface, *span)?
}
FrameItem::Link(dest, size) => handle_link(fc, gc, dest, *size)?,
FrameItem::Tag(Tag::Start(_, flags)) => {
if flags.tagged {
tags::handle_start(gc, surface);
}
}
FrameItem::Tag(Tag::End(_, _, flags)) => {
if flags.tagged {
tags::handle_end(gc, surface);
}
}
}
fc.pop();
}
fc.pop();
Ok(())
}
pub(crate) fn handle_group(
fc: &mut FrameContext,
group: &GroupItem,
surface: &mut Surface,
gc: &mut GlobalContext,
) -> SourceResult<()> {
fc.push();
fc.state_mut().pre_concat(group.transform);
tags::group(gc, surface, group.parent, |gc, surface| -> SourceResult<()> {
let clip_path = group
.clip
.as_ref()
.and_then(|p| {
let mut builder = PathBuilder::new();
convert_path(p, &mut builder);
builder.finish()
})
.and_then(|p| p.transform(fc.state().transform.to_krilla()));
if let Some(clip_path) = &clip_path {
surface.push_clip_path(clip_path, &krilla::paint::FillRule::NonZero);
}
let res = handle_frame(fc, &group.frame, None, surface, gc);
if clip_path.is_some() {
surface.pop();
}
res
})?;
fc.pop();
Ok(())
}
/// Finish a krilla document and handle export errors.
#[typst_macros::time(name = "finish export")]
fn finish(
document: Document,
gc: GlobalContext,
configuration: Configuration,
) -> SourceResult<Vec<u8>> {
let validator = configuration.validator();
match document.finish() {
Ok(r) => Ok(r),
Err(e) => match e {
KrillaError::Font(f, err) => {
bail!(
Span::detached(),
"failed to process {} ({err})",
display_font(gc.fonts_backward.get(&f));
hint: "make sure the font is valid";
hint: "the used font might be unsupported by Typst";
);
}
KrillaError::Validation(ve) => {
let errors = ve
.iter()
.map(|e| convert_error(&gc, validator, e))
.collect::<EcoVec<_>>();
Err(errors)
}
KrillaError::Image(_, loc, err) => {
let span = to_span(loc);
bail!(span, "failed to process image ({err})");
}
KrillaError::SixteenBitImage(image, _) => {
let span = gc.image_to_spans.get(&image).unwrap();
bail!(
*span, "16 bit images are not supported in this export mode";
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";
);
}
},
}
}
/// Converts a krilla error into a Typst error.
fn convert_error(
gc: &GlobalContext,
validator: Validator,
error: &ValidationError,
) -> SourceDiagnostic {
let prefix = eco_format!("{} error:", validator.as_str());
match error {
ValidationError::TooLongString => error!(
Span::detached(),
"{prefix} a PDF string is longer than 32767 characters";
hint: "ensure title and author names are short enough";
),
// Should in theory never occur, as krilla always trims font names.
ValidationError::TooLongName => error!(
Span::detached(),
"{prefix} a PDF name is longer than 127 characters";
hint: "perhaps a font name is too long";
),
ValidationError::TooLongArray => error!(
Span::detached(),
"{prefix} a PDF array is longer than 8191 elements";
hint: "this can happen if you have a very long text in a single line";
),
ValidationError::TooLongDictionary => error!(
Span::detached(),
"{prefix} a PDF dictionary has more than 4095 entries";
hint: "try reducing the complexity of your document";
),
ValidationError::TooLargeFloat => error!(
Span::detached(),
"{prefix} a PDF floating point number is larger than the allowed limit";
hint: "try exporting with a higher PDF version";
),
ValidationError::TooManyIndirectObjects => error!(
Span::detached(),
"{prefix} the PDF has too many indirect objects";
hint: "reduce the size of your document";
),
// Can only occur if we have 27+ nested clip paths
ValidationError::TooHighQNestingLevel => error!(
Span::detached(),
"{prefix} the PDF has too high q nesting";
hint: "reduce the number of nested containers";
),
ValidationError::ContainsPostScript(loc) => error!(
to_span(*loc),
"{prefix} the PDF contains PostScript code";
hint: "conic gradients are not supported in this PDF standard";
),
ValidationError::MissingCMYKProfile => error!(
Span::detached(),
"{prefix} the PDF is missing a CMYK profile";
hint: "CMYK colors are not yet supported in this export mode";
),
ValidationError::ContainsNotDefGlyph(f, loc, text) => error!(
to_span(*loc),
"{prefix} the text `{}` could not be displayed with {}",
text.repr(),
display_font(gc.fonts_backward.get(f));
hint: "try using a different font";
),
ValidationError::NoCodepointMapping(_, _, loc) => {
let msg = if loc.is_some() {
"the text was not mapped to a code point"
} else {
"the PDF contains text with missing codepoints"
};
error!(
to_span(*loc),
"{prefix} {msg}";
hint: "for complex scripts like Arabic, it might not be \
possible to produce a compliant document";
)
}
ValidationError::InvalidCodepointMapping(_, _, c, loc) => {
let msg = if loc.is_some() {
"the text contains"
} else {
"the PDF contains text with"
};
error!(
to_span(*loc),
"{prefix} {msg} the disallowed codepoint `{}`",
c.repr(),
)
}
ValidationError::UnicodePrivateArea(_, _, c, loc) => {
let msg = if loc.is_some() { "the PDF" } else { "the text" };
error!(
to_span(*loc),
"{prefix} {msg} contains the codepoint `{}`", c.repr();
hint: "codepoints from the Unicode private area are \
forbidden in this export mode";
)
}
ValidationError::RestrictedLicense(f) => error!(
Span::detached(),
"{prefix} license of {} is too restrictive",
display_font(gc.fonts_backward.get(f));
hint: "the font has specified \"Restricted License embedding\" in its \
metadata";
hint: "restrictive font licenses are prohibited by {} because they limit \
the suitability for archival",
validator.as_str();
),
ValidationError::Transparency(loc) => {
let span = to_span(*loc);
let hint1 = "try exporting with a different standard that \
supports transparency";
if loc.is_some() {
if gc.image_spans.contains(&span) {
error!(
span, "{prefix} the image contains transparency";
hint: "{hint1}";
hint: "or convert the image to a non-transparent one";
hint: "you might have to convert SVGs into \
non-transparent bitmap images";
)
} else {
error!(
span, "{prefix} the used fill or stroke has transparency";
hint: "{hint1}";
hint: "or don't use colors with transparency in \
this export mode";
)
}
} else {
error!(
span, "{prefix} the PDF contains transparency";
hint: "{hint1}";
)
}
}
ValidationError::ImageInterpolation(loc) => {
let span = to_span(*loc);
if loc.is_some() {
error!(
span, "{prefix} the image has smooth scaling";
hint: "set the `scaling` attribute to `pixelated`";
)
} else {
error!(
span, "{prefix} an image in the PDF has smooth scaling";
hint: "set the `scaling` attribute of all images to `pixelated`";
)
}
}
ValidationError::EmbeddedFile(e, s) => {
// We always set the span for attached files, so it cannot be detached.
let span = to_span(*s);
match e {
EmbedError::Existence => {
error!(
span, "{prefix} document contains an attached file";
hint: "file attachments are not supported in this export mode";
)
}
EmbedError::MissingDate => {
error!(
span, "{prefix} document date is missing";
hint: "the document must have a date when attaching files";
hint: "`set document(date: none)` must not be used in this case";
)
}
EmbedError::MissingDescription => {
error!(span, "{prefix} the file description is missing")
}
EmbedError::MissingMimeType => {
error!(span, "{prefix} the file mime type is missing")
}
}
}
// 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(loc) => {
let span = to_span(*loc);
error!(
span, "{prefix} missing annotation alt text";
hint: "please report this as a bug";
)
}
ValidationError::MissingAltText(loc) => {
let span = to_span(*loc);
error!(
span, "{prefix} missing alt text";
hint: "make sure your images and equations have alt text";
)
}
ValidationError::NoDocumentLanguage => error!(
Span::detached(),
"{prefix} missing document language";
hint: "set the language of the document";
),
// Needs to be set by typst-pdf.
ValidationError::MissingHeadingTitle => error!(
Span::detached(),
"{prefix} missing heading title";
hint: "please report this as a bug";
),
ValidationError::MissingDocumentOutline => error!(
Span::detached(),
"{prefix} missing document outline";
hint: "please report this as a bug";
),
ValidationError::MissingTagging => error!(
Span::detached(),
"{prefix} missing document tags";
hint: "please report this as a bug";
),
ValidationError::NoDocumentTitle => error!(
Span::detached(),
"{prefix} missing document title";
hint: "set the title with `set document(title: [...])`";
),
ValidationError::MissingDocumentDate => error!(
Span::detached(),
"{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";
)
}
}
}
/// Convert a krilla location to a span.
pub(crate) fn to_span(loc: Option<krilla::surface::Location>) -> Span {
loc.map(Span::from_raw).unwrap_or(Span::detached())
}
fn collect_named_destinations(
document: &PagedDocument,
pic: &PageIndexConverter,
) -> FxHashMap<Location, NamedDestination> {
let mut locs_to_names = FxHashMap::default();
// Find all headings that have a label and are the first among other
// headings with the same label.
let matches: Vec<_> = {
let mut seen = FxHashSet::default();
document
.introspector
.query(&HeadingElem::ELEM.select())
.iter()
.filter_map(|elem| elem.location().zip(elem.label()))
.filter(|&(_, label)| seen.insert(label))
.collect()
};
for (loc, label) in matches {
// Only add named destination if page belonging to the position is exported.
let pos = document.introspector.position(loc);
if let Some(dest) = crate::link::pos_to_xyz(pic, pos) {
let named = NamedDestination::new(label.resolve().to_string(), dest);
locs_to_names.insert(loc, named);
}
}
locs_to_names
}
pub(crate) struct PageIndexConverter {
page_indices: FxHashMap<usize, usize>,
skipped_pages: usize,
}
impl PageIndexConverter {
pub fn new(document: &PagedDocument, options: &PdfOptions) -> Self {
let mut page_indices = FxHashMap::default();
let mut skipped_pages = 0;
for i in 0..document.pages.len() {
if options
.page_ranges
.as_ref()
.is_some_and(|ranges| !ranges.includes_page_index(i))
{
skipped_pages += 1;
} else {
page_indices.insert(i, i - skipped_pages);
}
}
Self { page_indices, skipped_pages }
}
pub(crate) fn has_skipped_pages(&self) -> bool {
self.skipped_pages > 0
}
/// Get the PDF page index of a page index, if it's not excluded.
pub(crate) fn pdf_page_index(&self, page_index: usize) -> Option<usize> {
self.page_indices.get(&page_index).copied()
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/image.rs | crates/typst-pdf/src/image.rs | use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock};
use ecow::eco_format;
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::{At, SourceResult};
use typst_library::foundations::Smart;
use typst_library::layout::{Abs, Angle, Ratio, Size, Transform};
use typst_library::visualize::{
ExchangeFormat, Image, ImageKind, ImageScaling, PdfImage, RasterFormat, RasterImage,
};
use typst_syntax::Span;
use typst_utils::defer;
use crate::convert::{FrameContext, GlobalContext};
use crate::tags;
use crate::util::{SizeExt, TransformExt};
#[typst_macros::time(name = "handle image")]
pub(crate) fn handle_image(
gc: &mut GlobalContext,
fc: &mut FrameContext,
image: &Image,
size: Size,
surface: &mut Surface,
span: Span,
) -> SourceResult<()> {
surface.push_transform(&fc.state().transform().to_krilla());
surface.set_location(span.into_raw());
let mut surface = defer(surface, |s| {
s.pop();
s.reset_location();
});
let interpolate = image.scaling() == Smart::Custom(ImageScaling::Smooth);
gc.image_spans.insert(span);
let mut handle = tags::image(gc, fc, &mut surface, image, size);
let surface = handle.surface();
match image.kind() {
ImageKind::Raster(raster) => {
let (exif_transform, new_size) = exif_transform(raster, size);
surface.push_transform(&exif_transform.to_krilla());
let mut surface = defer(surface, |s| s.pop());
let image = convert_raster(raster.clone(), interpolate)
.map_err(|err| eco_format!("failed to process image ({err})"))
.at(span)?;
if !gc.image_to_spans.contains_key(&image) {
gc.image_to_spans.insert(image.clone(), span);
}
if let Some(size) = new_size.to_krilla() {
surface.draw_image(image, size);
}
}
ImageKind::Svg(svg) => {
if let Some(size) = size.to_krilla() {
surface.draw_svg(
svg.tree(),
size,
SvgSettings { embed_text: true, ..Default::default() },
);
}
}
ImageKind::Pdf(pdf) => {
if let Some(size) = size.to_krilla() {
surface.draw_pdf_page(&convert_pdf(pdf), size, pdf.page_index());
}
}
}
Ok(())
}
/// A wrapper around `RasterImage` so that we can implement `CustomImage`.
#[derive(Clone)]
struct PdfRasterImage(Arc<PdfRasterImageInner>);
/// The internal representation of a [`PdfRasterImage`].
struct PdfRasterImageInner {
/// The original, underlying raster image.
raster: RasterImage,
/// The alpha channel of the raster image, if existing.
alpha_channel: OnceLock<Option<Vec<u8>>>,
/// A (potentially) converted version of the dynamic image stored `raster` that is
/// guaranteed to either be in luma8 or rgb8, and thus can be used for the
/// `color_channel` method of `CustomImage`.
actual_dynamic: OnceLock<Arc<DynamicImage>>,
}
impl PdfRasterImage {
/// Wraps a raster image.
pub fn new(raster: RasterImage) -> Self {
Self(Arc::new(PdfRasterImageInner {
raster,
alpha_channel: OnceLock::new(),
actual_dynamic: OnceLock::new(),
}))
}
}
impl Hash for PdfRasterImage {
fn hash<H: Hasher>(&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.
self.0.raster.hash(state);
}
}
impl CustomImage for PdfRasterImage {
fn color_channel(&self) -> &[u8] {
self.0
.actual_dynamic
.get_or_init(|| {
let dynamic = self.0.raster.dynamic();
let channel_count = dynamic.color().channel_count();
match (dynamic.as_ref(), channel_count) {
// Pure luma8 or rgb8 image, can use it directly.
(DynamicImage::ImageLuma8(_), _) => dynamic.clone(),
(DynamicImage::ImageRgb8(_), _) => dynamic.clone(),
// Grey-scale image, convert to luma8.
(_, 1 | 2) => Arc::new(DynamicImage::ImageLuma8(dynamic.to_luma8())),
// Anything else, convert to rgb8.
_ => Arc::new(DynamicImage::ImageRgb8(dynamic.to_rgb8())),
}
})
.as_bytes()
}
fn alpha_channel(&self) -> Option<&[u8]> {
self.0
.alpha_channel
.get_or_init(|| {
self.0.raster.dynamic().color().has_alpha().then(|| {
self.0
.raster
.dynamic()
.pixels()
.map(|(_, _, Rgba([_, _, _, a]))| a)
.collect()
})
})
.as_ref()
.map(|v| &**v)
}
fn bits_per_component(&self) -> BitsPerComponent {
BitsPerComponent::Eight
}
fn size(&self) -> (u32, u32) {
(self.0.raster.width(), self.0.raster.height())
}
fn icc_profile(&self) -> Option<&[u8]> {
if matches!(
self.0.raster.dynamic().as_ref(),
DynamicImage::ImageLuma8(_)
| DynamicImage::ImageLumaA8(_)
| DynamicImage::ImageRgb8(_)
| DynamicImage::ImageRgba8(_)
) {
self.0.raster.icc().map(|b| b.as_bytes())
} else {
// In all other cases, the dynamic will be converted into RGB8 or LUMA8, so the ICC
// profile may become invalid, and thus we don't include it.
None
}
}
fn color_space(&self) -> ImageColorspace {
// Remember that we convert all images to either RGB or luma.
if self.0.raster.dynamic().color().has_color() {
ImageColorspace::Rgb
} else {
ImageColorspace::Luma
}
}
}
#[comemo::memoize]
fn convert_raster(
raster: RasterImage,
interpolate: bool,
) -> Result<krilla::image::Image, String> {
if let RasterFormat::Exchange(ExchangeFormat::Jpg) = raster.format() {
let image_data: Arc<dyn AsRef<[u8]> + Send + Sync> =
Arc::new(raster.data().clone());
let icc_profile = raster.icc().map(|i| {
let i: Arc<dyn AsRef<[u8]> + Send + Sync> = Arc::new(i.clone());
i
});
krilla::image::Image::from_jpeg_with_icc(
image_data.into(),
icc_profile.map(|i| i.into()),
interpolate,
)
} else {
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) {
// For JPEGs, we want to apply the EXIF orientation as a transformation
// because we don't recode them. For other formats, the transform is already
// baked into the dynamic image data.
if image.format() != RasterFormat::Exchange(ExchangeFormat::Jpg) {
return (Transform::identity(), size);
}
let base = |hp: bool, vp: bool, mut base_ts: Transform, size: Size| {
if hp {
// Flip horizontally in-place.
base_ts = base_ts.pre_concat(
Transform::scale(-Ratio::one(), Ratio::one())
.pre_concat(Transform::translate(-size.x, Abs::zero())),
)
}
if vp {
// Flip vertically in-place.
base_ts = base_ts.pre_concat(
Transform::scale(Ratio::one(), -Ratio::one())
.pre_concat(Transform::translate(Abs::zero(), -size.y)),
)
}
base_ts
};
let no_flipping =
|hp: bool, vp: bool| (base(hp, vp, Transform::identity(), size), size);
let with_flipping = |hp: bool, vp: bool| {
let base_ts = Transform::rotate_at(Angle::deg(90.0), Abs::zero(), Abs::zero())
.pre_concat(Transform::scale(Ratio::one(), -Ratio::one()));
let inv_size = Size::new(size.y, size.x);
(base(hp, vp, base_ts, inv_size), inv_size)
};
match image.exif_rotation() {
Some(2) => no_flipping(true, false),
Some(3) => no_flipping(true, true),
Some(4) => no_flipping(false, true),
Some(5) => with_flipping(false, false),
Some(6) => with_flipping(false, true),
Some(7) => with_flipping(true, true),
Some(8) => with_flipping(true, false),
_ => no_flipping(false, false),
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/text.rs | crates/typst-pdf/src/text.rs | use std::ops::Range;
use std::sync::Arc;
use bytemuck::TransparentWrapper;
use krilla::surface::{Location, Surface};
use krilla::text::GlyphId;
use typst_library::diag::{SourceResult, bail};
use typst_library::layout::Size;
use typst_library::text::{Font, Glyph, TextItem};
use typst_library::visualize::FillRule;
use typst_syntax::Span;
use typst_utils::defer;
use crate::convert::{FrameContext, GlobalContext};
use crate::util::{AbsExt, TransformExt, display_font};
use crate::{paint, tags};
#[typst_macros::time(name = "handle text")]
pub(crate) fn handle_text(
fc: &mut FrameContext,
t: &TextItem,
surface: &mut Surface,
gc: &mut GlobalContext,
) -> SourceResult<()> {
let mut handle = tags::text(gc, fc, surface, t);
let surface = handle.surface();
let font = convert_font(gc, t.font.clone())?;
let fill = paint::convert_fill(
gc,
&t.fill,
FillRule::NonZero,
true,
surface,
fc.state(),
Size::zero(),
)?;
let stroke =
if let Some(stroke) = t.stroke.as_ref().map(|s| {
paint::convert_stroke(gc, s, true, surface, fc.state(), Size::zero())
}) {
Some(stroke?)
} else {
None
};
let text = t.text.as_str();
let size = t.size;
let glyphs: &[PdfGlyph] = TransparentWrapper::wrap_slice(t.glyphs.as_slice());
surface.push_transform(&fc.state().transform().to_krilla());
let mut surface = defer(surface, |s| s.pop());
surface.set_fill(Some(fill));
surface.set_stroke(stroke);
surface.draw_glyphs(
krilla::geom::Point::from_xy(0.0, 0.0),
glyphs,
font.clone(),
text,
size.to_f32(),
false,
);
Ok(())
}
fn convert_font(
gc: &mut GlobalContext,
typst_font: Font,
) -> SourceResult<krilla::text::Font> {
if let Some(font) = gc.fonts_forward.get(&typst_font) {
Ok(font.clone())
} else {
let font = build_font(typst_font.clone())?;
gc.fonts_forward.insert(typst_font.clone(), font.clone());
gc.fonts_backward.insert(font.clone(), typst_font.clone());
Ok(font)
}
}
#[comemo::memoize]
fn build_font(typst_font: Font) -> SourceResult<krilla::text::Font> {
let font_data: Arc<dyn AsRef<[u8]> + Send + Sync> =
Arc::new(typst_font.data().clone());
match krilla::text::Font::new(font_data.into(), typst_font.index()) {
Some(f) => Ok(f),
None => {
bail!(
Span::detached(),
"failed to process {}",
display_font(Some(&typst_font)),
)
}
}
}
#[derive(Debug, TransparentWrapper)]
#[repr(transparent)]
struct PdfGlyph(Glyph);
impl krilla::text::Glyph for PdfGlyph {
#[inline(always)]
fn glyph_id(&self) -> GlyphId {
GlyphId::new(self.0.id as u32)
}
#[inline(always)]
fn text_range(&self) -> Range<usize> {
self.0.range.start as usize..self.0.range.end as usize
}
#[inline(always)]
fn x_advance(&self, size: f32) -> f32 {
// Don't use `Em::at`, because it contains an expensive check whether the result is finite.
self.0.x_advance.get() as f32 * size
}
#[inline(always)]
fn x_offset(&self, size: f32) -> f32 {
// Don't use `Em::at`, because it contains an expensive check whether the result is finite.
self.0.x_offset.get() as f32 * size
}
#[inline(always)]
fn y_offset(&self, size: f32) -> f32 {
// Don't use `Em::at`, because it contains an expensive check whether the result is finite.
self.0.y_offset.get() as f32 * size
}
#[inline(always)]
fn y_advance(&self, size: f32) -> f32 {
// Don't use `Em::at`, because it contains an expensive check whether the result is finite.
self.0.y_advance.get() as f32 * size
}
fn location(&self) -> Option<Location> {
Some(self.0.span.0.into_raw())
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/util.rs | crates/typst-pdf/src/util.rs | //! Basic utilities for converting Typst types to krilla.
use ecow::{EcoString, eco_format};
use krilla::geom as kg;
use krilla::geom::PathBuilder;
use krilla::paint as kp;
use krilla::tagging as kt;
use typst_library::foundations::Repr;
use typst_library::layout::{Abs, Point, Sides, Size, Transform};
use typst_library::text::Font;
use typst_library::visualize::{Curve, CurveItem, FillRule, LineCap, LineJoin};
pub(crate) trait SidesExt<T> {
/// Map to the [`kt::Sides`] struct assuming [`kt::WritingMode::LrTb`].
fn to_lrtb_krilla(self) -> kt::Sides<T>;
}
impl<T> SidesExt<T> for Sides<T> {
fn to_lrtb_krilla(self) -> kt::Sides<T> {
kt::Sides {
before: self.top,
after: self.bottom,
start: self.left,
end: self.right,
}
}
}
pub(crate) trait SizeExt {
fn to_krilla(&self) -> Option<kg::Size>;
}
impl SizeExt for Size {
fn to_krilla(&self) -> Option<kg::Size> {
kg::Size::from_wh(self.x.to_f32(), self.y.to_f32())
}
}
pub(crate) trait PointExt {
fn to_krilla(&self) -> kg::Point;
}
impl PointExt for Point {
fn to_krilla(&self) -> kg::Point {
kg::Point::from_xy(self.x.to_f32(), self.y.to_f32())
}
}
pub(crate) trait LineCapExt {
fn to_krilla(&self) -> kp::LineCap;
}
impl LineCapExt for LineCap {
fn to_krilla(&self) -> kp::LineCap {
match self {
LineCap::Butt => kp::LineCap::Butt,
LineCap::Round => kp::LineCap::Round,
LineCap::Square => kp::LineCap::Square,
}
}
}
pub(crate) trait LineJoinExt {
fn to_krilla(&self) -> kp::LineJoin;
}
impl LineJoinExt for LineJoin {
fn to_krilla(&self) -> kp::LineJoin {
match self {
LineJoin::Miter => kp::LineJoin::Miter,
LineJoin::Round => kp::LineJoin::Round,
LineJoin::Bevel => kp::LineJoin::Bevel,
}
}
}
pub(crate) trait TransformExt {
fn to_krilla(&self) -> kg::Transform;
}
impl TransformExt for Transform {
fn to_krilla(&self) -> kg::Transform {
kg::Transform::from_row(
self.sx.get() as f32,
self.ky.get() as f32,
self.kx.get() as f32,
self.sy.get() as f32,
self.tx.to_f32(),
self.ty.to_f32(),
)
}
}
pub(crate) trait FillRuleExt {
fn to_krilla(&self) -> kp::FillRule;
}
impl FillRuleExt for FillRule {
fn to_krilla(&self) -> kp::FillRule {
match self {
FillRule::NonZero => kp::FillRule::NonZero,
FillRule::EvenOdd => kp::FillRule::EvenOdd,
}
}
}
pub(crate) trait AbsExt {
fn to_f32(self) -> f32;
}
impl AbsExt for Abs {
fn to_f32(self) -> f32 {
self.to_pt() as f32
}
}
/// Display the font family of a font.
pub(crate) fn display_font(font: Option<&Font>) -> EcoString {
match font {
Some(font) => eco_format!("font `{}`", font.info().family.repr()),
None => "a font".into(),
}
}
/// Convert a Typst path to a krilla path.
pub(crate) fn convert_path(path: &Curve, builder: &mut PathBuilder) {
for item in &path.0 {
match item {
CurveItem::Move(p) => builder.move_to(p.x.to_f32(), p.y.to_f32()),
CurveItem::Line(p) => builder.line_to(p.x.to_f32(), p.y.to_f32()),
CurveItem::Cubic(p1, p2, p3) => builder.cubic_to(
p1.x.to_f32(),
p1.y.to_f32(),
p2.x.to_f32(),
p2.y.to_f32(),
p3.x.to_f32(),
p3.y.to_f32(),
),
CurveItem::Close => builder.close(),
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/outline.rs | crates/typst-pdf/src/outline.rs | use krilla::outline::{Outline as KrillaOutline, OutlineNode as KrillaOutlineNode};
use typst_library::foundations::{NativeElement, Packed, StyleChain};
use typst_library::model::{HeadingElem, OutlineNode};
use crate::convert::GlobalContext;
pub(crate) fn build_outline(gc: &GlobalContext) -> KrillaOutline {
let elems = gc.document.introspector.query(&HeadingElem::ELEM.select());
let flat = elems
.iter()
.map(|elem| {
let heading = elem.to_packed::<HeadingElem>().unwrap();
let level = heading.resolve_level(StyleChain::default());
let boomarked = heading
.bookmarked
.get(StyleChain::default())
.unwrap_or_else(|| heading.outlined.get(StyleChain::default()));
let visible = gc.options.page_ranges.as_ref().is_none_or(|ranges| {
!ranges.includes_page(
gc.document.introspector.page(elem.location().unwrap()),
)
});
let include = boomarked && visible;
(heading, level, include)
})
.collect::<Vec<_>>();
let tree = OutlineNode::build_tree(flat);
let mut outline = KrillaOutline::new();
for child in convert_list(&tree, gc) {
outline.push_child(child);
}
outline
}
fn convert_list(
nodes: &[OutlineNode<&Packed<HeadingElem>>],
gc: &GlobalContext,
) -> Vec<KrillaOutlineNode> {
nodes.iter().flat_map(|node| convert_node(node, gc)).collect()
}
fn convert_node(
node: &OutlineNode<&Packed<HeadingElem>>,
gc: &GlobalContext,
) -> Option<KrillaOutlineNode> {
let loc = node.entry.location().unwrap();
let pos = gc.document.introspector.position(loc);
// Prepend the numbers to the title if they exist.
let text = node.entry.body.plain_text();
let title = match &node.entry.numbers {
Some(num) => format!("{num} {text}"),
None => text.to_string(),
};
if let Some(dest) = crate::link::pos_to_xyz(&gc.page_index_converter, pos) {
let mut outline_node = KrillaOutlineNode::new(title, dest);
for child in convert_list(&node.children, gc) {
outline_node.push_child(child);
}
return Some(outline_node);
}
None
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/attach.rs | crates/typst-pdf/src/attach.rs | use std::sync::Arc;
use krilla::Document;
use krilla::embed::{AssociationKind, EmbeddedFile, MimeType};
use typst_library::diag::{SourceResult, bail};
use typst_library::foundations::{NativeElement, StyleChain};
use typst_library::pdf::{AttachElem, AttachedFileRelationship};
use crate::convert::GlobalContext;
use crate::metadata;
pub(crate) fn attach_files(
gc: &GlobalContext,
document: &mut Document,
) -> SourceResult<()> {
let elements = gc.document.introspector.query(&AttachElem::ELEM.select());
for elem in &elements {
let elem = elem.to_packed::<AttachElem>().unwrap();
let span = elem.span();
let derived_path = &elem.path.derived;
let path = derived_path.to_string();
let mime_type = elem
.mime_type
.get_ref(StyleChain::default())
.as_ref()
.map(|s| match MimeType::new(s) {
Some(mime_type) => Ok(mime_type),
None => bail!(elem.span(), "invalid mime type"),
})
.transpose()?;
let description = elem
.description
.get_ref(StyleChain::default())
.as_ref()
.map(Into::into);
let association_kind = match elem.relationship.get(StyleChain::default()) {
None => AssociationKind::Unspecified,
Some(e) => match e {
AttachedFileRelationship::Source => AssociationKind::Source,
AttachedFileRelationship::Data => AssociationKind::Data,
AttachedFileRelationship::Alternative => AssociationKind::Alternative,
AttachedFileRelationship::Supplement => AssociationKind::Supplement,
},
};
let data: Arc<dyn AsRef<[u8]> + Send + Sync> = Arc::new(elem.data.clone());
let compress = should_compress(&elem.data);
let file = EmbeddedFile {
path,
mime_type,
description,
association_kind,
data: data.into(),
compress,
location: Some(span.into_raw()),
modification_date: metadata::creation_date(gc),
};
if document.embed_file(file).is_none() {
bail!(span, "attempted to attach file {derived_path} twice");
}
}
Ok(())
}
fn should_compress(data: &[u8]) -> Option<bool> {
let ty = infer::get(data)?;
match ty.matcher_type() {
infer::MatcherType::App => None,
infer::MatcherType::Archive => match ty.mime_type() {
#[rustfmt::skip]
"application/zip"
| "application/vnd.rar"
| "application/gzip"
| "application/x-bzip2"
| "application/vnd.bzip3"
| "application/x-7z-compressed"
| "application/x-xz"
| "application/vnd.ms-cab-compressed"
| "application/vnd.debian.binary-package"
| "application/x-compress"
| "application/x-lzip"
| "application/x-rpm"
| "application/zstd"
| "application/x-lz4"
| "application/x-ole-storage" => Some(false),
_ => None,
},
infer::MatcherType::Audio => match ty.mime_type() {
#[rustfmt::skip]
"audio/mpeg"
| "audio/m4a"
| "audio/opus"
| "audio/ogg"
| "audio/x-flac"
| "audio/amr"
| "audio/aac"
| "audio/x-ape" => Some(false),
_ => None,
},
infer::MatcherType::Book => None,
infer::MatcherType::Doc => None,
infer::MatcherType::Font => None,
infer::MatcherType::Image => match ty.mime_type() {
#[rustfmt::skip]
"image/jpeg"
| "image/jp2"
| "image/png"
| "image/webp"
| "image/vnd.ms-photo"
| "image/heif"
| "image/avif"
| "image/jxl"
| "image/vnd.djvu" => None,
_ => None,
},
infer::MatcherType::Text => None,
infer::MatcherType::Video => match ty.mime_type() {
#[rustfmt::skip]
"video/mp4"
| "video/x-m4v"
| "video/x-matroska"
| "video/webm"
| "video/quicktime"
| "video/x-flv" => Some(false),
_ => None,
},
infer::MatcherType::Custom => None,
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/metadata.rs | crates/typst-pdf/src/metadata.rs | use krilla::metadata::{Metadata, TextDirection};
use typst_library::foundations::{Datetime, Smart};
use typst_library::layout::Dir;
use typst_library::text::Locale;
use crate::convert::GlobalContext;
pub(crate) fn build_metadata(gc: &GlobalContext, doc_lang: Option<Locale>) -> Metadata {
let creator = format!("Typst {}", typst_utils::version().raw());
// Always write a language, PDF/UA-1 implicitly requires a document language
// so the metadata and outline entries have an applicable language.
let lang = doc_lang.unwrap_or(Locale::DEFAULT);
let dir = if lang.lang.dir() == Dir::RTL {
TextDirection::RightToLeft
} else {
TextDirection::LeftToRight
};
let mut metadata = Metadata::new()
.creator(creator)
.keywords(gc.document.info.keywords.iter().map(Into::into).collect())
.authors(gc.document.info.author.iter().map(Into::into).collect())
.language(lang.rfc_3066().to_string());
if let Some(title) = &gc.document.info.title {
metadata = metadata.title(title.to_string());
}
if let Some(description) = &gc.document.info.description {
metadata = metadata.description(description.to_string());
}
if let Some(ident) = gc.options.ident.custom() {
metadata = metadata.document_id(ident.to_string());
}
if let Some(date) = creation_date(gc) {
metadata = metadata.creation_date(date);
}
metadata = metadata.text_direction(dir);
metadata
}
/// (1) If the `document.date` is set to specific `datetime` or `none`, use it.
/// (2) If the `document.date` is set to `auto` or not set, try to use the
/// date from the options.
/// (3) Otherwise, we don't write date metadata.
pub fn creation_date(gc: &GlobalContext) -> Option<krilla::metadata::DateTime> {
let (datetime, tz) = match (gc.document.info.date, gc.options.timestamp) {
(Smart::Custom(Some(date)), _) => (date, None),
(Smart::Auto, Some(timestamp)) => (timestamp.datetime, Some(timestamp.timezone)),
_ => return None,
};
let year = datetime.year().filter(|&y| y >= 0)? as u16;
let mut kd = krilla::metadata::DateTime::new(year);
if let Some(month) = datetime.month() {
kd = kd.month(month);
}
if let Some(day) = datetime.day() {
kd = kd.day(day);
}
if let Some(h) = datetime.hour() {
kd = kd.hour(h);
}
if let Some(m) = datetime.minute() {
kd = kd.minute(m);
}
if let Some(s) = datetime.second() {
kd = kd.second(s);
}
match tz {
Some(Timezone::UTC) => kd = kd.utc_offset_hour(0).utc_offset_minute(0),
Some(Timezone::Local { hour_offset, minute_offset }) => {
kd = kd.utc_offset_hour(hour_offset).utc_offset_minute(minute_offset)
}
None => {}
}
Some(kd)
}
/// A timestamp with timezone information.
#[derive(Debug, Copy, Clone)]
pub struct Timestamp {
/// The datetime of the timestamp.
pub(crate) datetime: Datetime,
/// The timezone of the timestamp.
pub(crate) timezone: Timezone,
}
impl Timestamp {
/// Create a new timestamp with a given datetime and UTC suffix.
pub fn new_utc(datetime: Datetime) -> Self {
Self { datetime, timezone: Timezone::UTC }
}
/// Create a new timestamp with a given datetime, and a local timezone offset.
pub fn new_local(datetime: Datetime, whole_minute_offset: i32) -> Option<Self> {
let hour_offset = (whole_minute_offset / 60).try_into().ok()?;
// Note: the `%` operator in Rust is the remainder operator, not the
// modulo operator. The remainder operator can return negative results.
// We can simply apply `abs` here because we assume the `minute_offset`
// will have the same sign as `hour_offset`.
let minute_offset = (whole_minute_offset % 60).abs().try_into().ok()?;
match (hour_offset, minute_offset) {
// Only accept valid timezone offsets with `-23 <= hours <= 23`,
// and `0 <= minutes <= 59`.
(-23..=23, 0..=59) => Some(Self {
datetime,
timezone: Timezone::Local { hour_offset, minute_offset },
}),
_ => None,
}
}
}
/// A timezone.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Timezone {
/// The UTC timezone.
UTC,
/// The local timezone offset from UTC. And the `minute_offset` will have
/// same sign as `hour_offset`.
Local { hour_offset: i8, minute_offset: u8 },
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_timestamp_new_local() {
let dummy_datetime = Datetime::from_ymd_hms(2024, 12, 17, 10, 10, 10).unwrap();
let test = |whole_minute_offset, expect_timezone| {
assert_eq!(
Timestamp::new_local(dummy_datetime, whole_minute_offset)
.unwrap()
.timezone,
expect_timezone
);
};
// Valid timezone offsets
test(0, Timezone::Local { hour_offset: 0, minute_offset: 0 });
test(480, Timezone::Local { hour_offset: 8, minute_offset: 0 });
test(-480, Timezone::Local { hour_offset: -8, minute_offset: 0 });
test(330, Timezone::Local { hour_offset: 5, minute_offset: 30 });
test(-210, Timezone::Local { hour_offset: -3, minute_offset: 30 });
test(-720, Timezone::Local { hour_offset: -12, minute_offset: 0 }); // AoE
// Corner cases
test(315, Timezone::Local { hour_offset: 5, minute_offset: 15 });
test(-225, Timezone::Local { hour_offset: -3, minute_offset: 45 });
test(1439, Timezone::Local { hour_offset: 23, minute_offset: 59 });
test(-1439, Timezone::Local { hour_offset: -23, minute_offset: 59 });
// Invalid timezone offsets
assert!(Timestamp::new_local(dummy_datetime, 1440).is_none());
assert!(Timestamp::new_local(dummy_datetime, -1440).is_none());
assert!(Timestamp::new_local(dummy_datetime, i32::MAX).is_none());
assert!(Timestamp::new_local(dummy_datetime, i32::MIN).is_none());
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/mod.rs | crates/typst-pdf/src/tags/mod.rs | use krilla::configure::Validator;
use krilla::geom as kg;
use krilla::page::Page;
use krilla::surface::Surface;
use krilla::tagging::{ArtifactType, ContentTag, SpanTag};
use typst_library::diag::SourceResult;
use typst_library::layout::{FrameParent, PagedDocument, Point, Rect, Size};
use typst_library::text::{Locale, TextItem};
use typst_library::visualize::{Image, Shape};
use crate::PdfOptions;
use crate::convert::{FrameContext, GlobalContext};
use crate::link::{LinkAnnotation, LinkAnnotationKind};
use crate::tags::tree::Tree;
pub use crate::tags::context::{AnnotationId, Tags};
pub use crate::tags::groups::GroupId;
pub use crate::tags::resolve::resolve;
mod context;
mod groups;
mod resolve;
mod tree;
mod util;
pub fn init(document: &PagedDocument, options: &PdfOptions) -> SourceResult<Tags> {
let tree = if options.tagged {
tree::build(document, options)?
} else {
Tree::empty(document, options)
};
Ok(Tags::new(tree))
}
pub fn handle_start(gc: &mut GlobalContext, surface: &mut Surface) {
if disabled(gc) {
return;
}
tree::step_start_tag(&mut gc.tags.tree, surface);
}
pub fn handle_end(gc: &mut GlobalContext, surface: &mut Surface) {
if disabled(gc) {
return;
}
tree::step_end_tag(&mut gc.tags.tree, surface);
}
pub fn group<T>(
gc: &mut GlobalContext,
surface: &mut Surface,
parent: Option<FrameParent>,
group_fn: impl FnOnce(&mut GlobalContext, &mut Surface) -> T,
) -> T {
if disabled(gc) || parent.is_none() {
return group_fn(gc, surface);
}
tree::enter_logical_child(&mut gc.tags.tree, surface);
let res = group_fn(gc, surface);
tree::leave_logical_child(&mut gc.tags.tree, surface);
res
}
pub fn page<T>(
gc: &mut GlobalContext,
surface: &mut Surface,
page_fn: impl FnOnce(&mut GlobalContext, &mut Surface) -> T,
) -> T {
if disabled(gc) {
return page_fn(gc, surface);
}
if let Some(ty) = gc.tags.tree.parent_artifact() {
surface.start_tagged(ContentTag::Artifact(ty));
}
let res = page_fn(gc, surface);
if gc.tags.tree.parent_artifact().is_some() {
surface.end_tagged();
}
res
}
/// Tags are completely disabled within tags.
pub fn tiling<T>(
gc: &mut GlobalContext,
surface: &mut Surface,
f: impl FnOnce(&mut GlobalContext, &mut Surface) -> T,
) -> T {
if disabled(gc) {
return f(gc, surface);
}
let prev = gc.tags.in_tiling;
gc.tags.in_tiling = true;
let mark_artifact = gc.tags.tree.parent_artifact().is_none();
if mark_artifact {
surface.start_tagged(ContentTag::Artifact(ArtifactType::Other));
}
let res = f(gc, surface);
if mark_artifact {
surface.end_tagged();
}
gc.tags.in_tiling = prev;
res
}
/// Whether tag generation is currently disabled. Either because it has been
/// disabled by the user using the [`PdfOptions::tagged`] flag, or we're inside
/// a tiling.
pub fn disabled(gc: &GlobalContext) -> bool {
!gc.options.tagged || gc.tags.in_tiling
}
/// Add all annotations that were found in the page frame.
pub fn add_link_annotations(
gc: &mut GlobalContext,
page: &mut Page,
annotations: impl IntoIterator<Item = LinkAnnotation>,
) {
for a in annotations.into_iter() {
let link_annotation = if let [rect] = a.rects.as_slice() {
krilla::annotation::LinkAnnotation::new(*rect, a.target)
} else {
let quads = a.rects.iter().map(|r| kg::Quadrilateral::from(*r)).collect();
krilla::annotation::LinkAnnotation::new_with_quad_points(quads, a.target)
};
let annotation = krilla::annotation::Annotation::new_link(link_annotation, a.alt)
.with_location(Some(a.span.into_raw()));
if let LinkAnnotationKind::Tagged(annot_id) = a.kind {
let identifier = page.add_tagged_annotation(annotation);
gc.tags.annotations.init(annot_id, identifier);
} else {
page.add_annotation(annotation);
}
}
}
/// Automatically calls [`Surface::end_tagged`] when dropped.
pub struct TagHandle<'a, 'b> {
surface: &'b mut Surface<'a>,
/// Whether this tag handle started the marked content sequence, and should
/// thus end it when it is dropped.
started: bool,
}
impl Drop for TagHandle<'_, '_> {
fn drop(&mut self) {
if self.started {
self.surface.end_tagged();
}
}
}
impl<'a> TagHandle<'a, '_> {
pub fn surface<'c>(&'c mut self) -> &'c mut Surface<'a> {
self.surface
}
}
pub fn text<'a, 'b>(
gc: &mut GlobalContext,
fc: &FrameContext,
surface: &'b mut Surface<'a>,
text: &TextItem,
) -> TagHandle<'a, 'b> {
if disabled(gc) {
return TagHandle { surface, started: false };
}
update_bbox(gc, fc, || text.bbox());
if gc.tags.tree.parent_artifact().is_some() {
return TagHandle { surface, started: false };
}
let attrs = tree::resolve_text_attrs(&mut gc.tags.tree, gc.options, text);
let lang = {
let locale = Locale::new(text.lang, text.region);
gc.tags.tree.groups.propagate_lang(gc.tags.tree.current(), locale)
};
let lang_str = lang.map(Locale::rfc_3066);
let content = ContentTag::Span(SpanTag::empty().with_lang(lang_str.as_deref()));
let id = surface.start_tagged(content);
gc.tags.push_text(attrs, id);
TagHandle { surface, started: true }
}
pub fn image<'a, 'b>(
gc: &mut GlobalContext,
fc: &FrameContext,
surface: &'b mut Surface<'a>,
image: &Image,
size: Size,
) -> TagHandle<'a, 'b> {
if disabled(gc) {
return TagHandle { surface, started: false };
}
update_bbox(gc, fc, || Rect::from_pos_size(Point::zero(), size));
if gc.tags.tree.parent_artifact().is_some() {
return TagHandle { surface, started: false };
}
let content = ContentTag::Span(SpanTag::empty().with_alt_text(image.alt()));
let id = surface.start_tagged(content);
gc.tags.push_leaf(id);
TagHandle { surface, started: true }
}
pub fn shape<'a, 'b>(
gc: &mut GlobalContext,
fc: &FrameContext,
surface: &'b mut Surface<'a>,
shape: &Shape,
) -> TagHandle<'a, 'b> {
if disabled(gc) {
return TagHandle { surface, started: false };
}
update_bbox(gc, fc, || shape.geometry.bbox());
if gc.tags.tree.parent_artifact().is_some() {
return TagHandle { surface, started: false };
}
surface.start_tagged(ContentTag::Artifact(ArtifactType::Other));
TagHandle { surface, started: true }
}
fn update_bbox(
gc: &mut GlobalContext,
fc: &FrameContext,
compute_bbox: impl FnOnce() -> Rect,
) {
if let Some(bbox) = gc.tags.tree.parent_bbox()
&& gc.options.standards.config.validator() == Validator::UA1
{
bbox.expand_frame(fc, compute_bbox);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/resolve.rs | crates/typst-pdf/src/tags/resolve.rs | use std::num::NonZeroU16;
use ecow::EcoVec;
use krilla::tagging::{self as kt, Node, Tag, TagGroup, TagKind};
use krilla::tagging::{Identifier, TagTree};
use smallvec::SmallVec;
use typst_library::diag::{At, SourceDiagnostic, SourceResult, error};
use typst_library::text::Locale;
use typst_syntax::Span;
use crate::PdfOptions;
use crate::convert::{GlobalContext, to_span};
use crate::tags::context::{self, Annotations, BBoxCtx, Ctx};
use crate::tags::groups::{Group, GroupId, GroupKind, TagStorage};
use crate::tags::tree::ResolvedTextAttrs;
use crate::tags::util::{self, IdVec, PropertyOptRef, PropertyValCopied};
use crate::tags::{AnnotationId, disabled};
#[derive(Debug, Clone, PartialEq)]
pub enum TagNode {
Group(GroupId),
Leaf(Identifier),
/// Allows inserting a annotation into the tag tree.
/// Currently used for [`krilla::page::Page::add_tagged_annotation`].
Annotation(AnnotationId),
/// If the attributes are non-empty this will resolve to a [`Tag::Span`],
/// otherwise the items are inserted directly.
Text(ResolvedTextAttrs, Vec<Identifier>),
}
struct Resolver<'a> {
options: &'a PdfOptions<'a>,
ctx: &'a Ctx,
groups: &'a IdVec<Group>,
tags: &'a mut TagStorage,
annotations: &'a mut Annotations,
last_heading_level: Option<NonZeroU16>,
flatten: bool,
errors: EcoVec<SourceDiagnostic>,
}
impl<'a> Resolver<'a> {
fn with_flatten<T>(&mut self, flatten: bool, f: impl FnOnce(&mut Self) -> T) -> T {
let prev = self.flatten;
self.flatten |= flatten;
let res = f(self);
self.flatten = prev;
res
}
}
pub fn resolve(gc: &mut GlobalContext) -> SourceResult<(Option<Locale>, TagTree)> {
gc.tags.tree.assert_finished_traversal().at(Span::detached())?;
if !disabled(gc) {
context::finish(&mut gc.tags.tree);
}
let root = gc.tags.tree.groups.list.get(GroupId::ROOT);
let GroupKind::Root(mut doc_lang) = root.kind else { unreachable!() };
if disabled(gc) {
return Ok((doc_lang, TagTree::new()));
}
let mut resolver = Resolver {
options: gc.options,
ctx: &gc.tags.tree.ctx,
groups: &gc.tags.tree.groups.list,
tags: &mut gc.tags.tree.groups.tags,
annotations: &mut gc.tags.annotations,
last_heading_level: None,
flatten: false,
errors: std::mem::take(&mut gc.tags.tree.errors),
};
let mut children = Vec::with_capacity(root.nodes().len());
let mut accum = Accumulator::new(ElementKind::Grouping, &mut children);
for child in root.nodes().iter() {
resolve_node(&mut resolver, &mut doc_lang, &mut None, &mut accum, child);
}
if !resolver.errors.is_empty() {
return Err(resolver.errors);
}
accum.finish();
Ok((doc_lang, TagTree::from(children)))
}
/// Resolves nodes into an accumulator.
fn resolve_node(
rs: &mut Resolver,
parent_lang: &mut Option<Locale>,
parent_bbox: &mut Option<BBoxCtx>,
accum: &mut Accumulator,
node: &TagNode,
) {
match &node {
TagNode::Group(id) => {
resolve_group_node(rs, parent_lang, parent_bbox, accum, *id);
}
TagNode::Leaf(identifier) => {
accum.push(Node::Leaf(*identifier));
}
TagNode::Annotation(id) => {
accum.push(rs.annotations.take(*id));
}
TagNode::Text(attrs, ids) => {
resolve_text(accum, attrs, ids);
}
}
}
fn resolve_group_node(
rs: &mut Resolver,
parent_lang: &mut Option<Locale>,
mut parent_bbox: &mut Option<BBoxCtx>,
accum: &mut Accumulator,
id: GroupId,
) {
let group = rs.groups.get(id);
let tag = build_group_tag(rs, group);
let mut lang = group.kind.lang().filter(|_| tag.is_some());
let mut bbox = rs.ctx.bbox(&group.kind).cloned();
let mut nodes = Vec::new();
let mut children = {
let nesting = tag.as_ref().map(element_kind).unwrap_or(accum.nesting);
let buf = if tag.is_some() { &mut nodes } else { &mut accum.buf };
Accumulator::new(nesting, buf)
};
// If a tag has an alternative description specified, flatten the children
// tags, only retaining link tags, because they are required. The inner tags
// won't be ingested by AT anyway, but would still have to comply with all
// rules, which can be annoying.
let flatten = tag.as_ref().is_some_and(|t| t.alt_text().is_some());
rs.with_flatten(flatten, |rs| {
let lang = lang.as_mut().unwrap_or(parent_lang);
let bbox = if bbox.is_some() { &mut bbox } else { &mut parent_bbox };
// In PDF 1.7, don't include artifacts in the tag tree. In PDF 2.0
// this might become an `Artifact` tag.
if group.kind.is_artifact() {
for child in group.nodes().iter() {
resolve_artifact_node(rs, bbox, child);
}
} else {
children.buf.reserve(group.nodes().len());
for child in group.nodes().iter() {
resolve_node(rs, lang, bbox, &mut children, child);
}
}
});
// Try to propagate the group's language to the parent tag.
let lang = util::propagate_lang(parent_lang, lang.flatten());
// Update the parent bbox.
if let Some((parent, child)) = parent_bbox.as_mut().zip(bbox.as_ref()) {
parent.expand_page(child);
}
children.finish();
// Omit the weak group if it is empty.
if group.weak && nodes.is_empty() {
return;
}
// If this isn't a tagged group the children we're directly inserted into
// the parent.
let Some(mut tag) = tag else { return };
tag.set_lang(lang.map(|l| l.rfc_3066().to_string()));
if let Some(bbox) = bbox {
match &mut tag {
TagKind::Table(tag) => tag.set_bbox(bbox.to_krilla()),
TagKind::Figure(tag) => tag.set_bbox(bbox.to_krilla()),
TagKind::Formula(tag) => tag.set_bbox(bbox.to_krilla()),
_ => (),
}
}
if rs.options.is_pdf_ua() {
validate_children(rs, &tag, &nodes);
}
accum.push(Node::Group(kt::TagGroup::with_children(tag, nodes)));
}
fn resolve_text(
accum: &mut Accumulator,
attrs: &ResolvedTextAttrs,
children: &[kt::Identifier],
) {
enum Prev<'a> {
Children(&'a [kt::Identifier]),
Group(kt::TagGroup),
}
impl Prev<'_> {
fn into_nodes(self) -> Vec<Node> {
match self {
Prev::Children(ids) => ids.iter().map(|id| Node::Leaf(*id)).collect(),
Prev::Group(group) => vec![Node::Group(group)],
}
}
}
let mut prev = Prev::Children(children);
if attrs.script.is_some() || attrs.background.is_some() || attrs.deco.is_some() {
let tag = Tag::Span
.with_line_height(attrs.script.map(|s| s.lineheight))
.with_baseline_shift(attrs.script.map(|s| s.baseline_shift))
.with_background_color(attrs.background.flatten())
.with_text_decoration_type(attrs.deco.map(|d| d.kind.to_krilla()))
.with_text_decoration_color(attrs.deco.and_then(|d| d.color))
.with_text_decoration_thickness(attrs.deco.and_then(|d| d.thickness));
let group = kt::TagGroup::with_children(tag, prev.into_nodes());
prev = Prev::Group(group);
}
if attrs.strong == Some(true) {
let group = kt::TagGroup::with_children(Tag::Strong, prev.into_nodes());
prev = Prev::Group(group);
}
if attrs.emph == Some(true) {
let group = kt::TagGroup::with_children(Tag::Em, prev.into_nodes());
prev = Prev::Group(group);
}
match prev {
Prev::Group(group) => accum.push(Node::Group(group)),
Prev::Children(ids) => accum.extend(ids.iter().map(|id| Node::Leaf(*id))),
}
}
/// Currently only done to resolve bounding boxes.
fn resolve_artifact_node(
rs: &mut Resolver,
mut parent_bbox: &mut Option<BBoxCtx>,
node: &TagNode,
) {
match &node {
TagNode::Group(id) => {
let group = rs.groups.get(*id);
let mut bbox = rs.ctx.bbox(&group.kind).cloned();
{
let bbox = if bbox.is_some() { &mut bbox } else { &mut parent_bbox };
for child in group.nodes().iter() {
resolve_artifact_node(rs, bbox, child);
}
}
// Update the parent bbox.
if let Some((parent, child)) = parent_bbox.as_mut().zip(bbox.as_ref()) {
parent.expand_page(child);
}
}
TagNode::Leaf(..) => (),
TagNode::Annotation(..) => (),
TagNode::Text(..) => (),
}
}
fn build_group_tag(rs: &mut Resolver, group: &Group) -> Option<TagKind> {
let tag = match &group.kind {
GroupKind::Root(_) => unreachable!(),
GroupKind::Artifact(_) => return None,
GroupKind::LogicalParent(_) => return None,
GroupKind::LogicalChild(_, _) => return None,
GroupKind::Outline(_, _) => Tag::TOC.into(),
GroupKind::OutlineEntry(_, _) => Tag::TOCI.into(),
GroupKind::Table(id, _, _) => rs.ctx.tables.get(*id).build_tag(),
GroupKind::TableCell(_, tag, _) => rs.tags.take(*tag),
GroupKind::Grid(_, _) => Tag::Div.into(),
GroupKind::GridCell(_, _) => Tag::Div.into(),
GroupKind::List(_, numbering, _) => Tag::L(*numbering).into(),
GroupKind::ListItemLabel(_) => Tag::Lbl.into(),
GroupKind::ListItemBody(_) => Tag::LBody.into(),
GroupKind::TermsItemLabel(_) => Tag::Lbl.into(),
GroupKind::TermsItemBody(_, _) => Tag::LBody.into(),
GroupKind::BibEntry(_) => Tag::BibEntry.into(),
GroupKind::FigureWrapper(id) => rs.ctx.figures.get(*id).build_wrapper_tag()?,
GroupKind::Figure(id, _, _) => rs.ctx.figures.get(*id).build_tag()?,
GroupKind::FigureCaption(_, _) => Tag::Caption.into(),
GroupKind::Image(image, _, _) => {
let alt = image.alt.opt_ref().map(Into::into);
Tag::Figure(alt).with_placement(Some(kt::Placement::Block)).into()
}
GroupKind::Formula(equation, _, _) => {
let alt = equation.alt.opt_ref().map(Into::into);
let placement = equation.block.val().then_some(kt::Placement::Block);
Tag::Formula(alt).with_placement(placement).into()
}
GroupKind::Link(_, _) => Tag::Link.into(),
GroupKind::CodeBlock(_) => {
Tag::Code.with_placement(Some(kt::Placement::Block)).into()
}
GroupKind::CodeBlockLine(_) => Tag::P.into(),
GroupKind::Par(_) => Tag::P.into(),
GroupKind::TextAttr(_) => return None,
GroupKind::Transparent => return None,
GroupKind::Standard(tag, _) => rs.tags.take(*tag),
};
let tag = tag.with_location(Some(group.span.into_raw()));
if rs.flatten && !group.kind.is_link() {
return None;
}
// Check that no heading levels were skipped.
if let TagKind::Hn(tag) = &tag {
let prev_level = rs.last_heading_level.map_or(0, |l| l.get());
let next_level = tag.level();
if rs.options.is_pdf_ua() && next_level.get().saturating_sub(prev_level) > 1 {
let span = to_span(tag.as_any().location);
let validator = rs.options.standards.config.validator().as_str();
if rs.last_heading_level.is_none() {
rs.errors.push(error!(
span,
"{validator} error: the first heading must be of level 1",
));
} else {
rs.errors.push(error!(
span,
"{validator} error: skipped from heading level \
{prev_level} to {next_level}";
hint: "heading levels must be consecutive";
));
}
}
rs.last_heading_level = Some(next_level);
}
Some(tag)
}
struct Accumulator<'a> {
nesting: ElementKind,
buf: &'a mut Vec<Node>,
// Whether the last node is a `Span` used to wrap marked content sequences
// inside a grouping element. Groupings element may not contain marked
// content sequences directly.
grouping_span: Option<Vec<Node>>,
}
impl std::ops::Drop for Accumulator<'_> {
fn drop(&mut self) {
self.push_grouping_span();
}
}
impl<'a> Accumulator<'a> {
fn new(nesting: ElementKind, buf: &'a mut Vec<Node>) -> Self {
Self { nesting, buf, grouping_span: None }
}
fn push_buf(&mut self, node: Node) {
self.buf.push(node);
}
fn push_grouping_span(&mut self) {
if let Some(span_nodes) = self.grouping_span.take() {
let tag = Tag::Span.with_placement(Some(kt::Placement::Block));
let group = TagGroup::with_children(tag, span_nodes);
self.push_buf(group.into());
}
}
fn push(&mut self, mut node: Node) {
if self.nesting == ElementKind::Grouping {
match &mut node {
Node::Group(group) => {
self.push_grouping_span();
// Ensure ILSE have block placement when inside grouping elements.
if element_kind(&group.tag) == ElementKind::Inline {
group.tag.set_placement(Some(kt::Placement::Block));
}
self.push_buf(node);
}
Node::Leaf(_) => {
let span_nodes = self.grouping_span.get_or_insert_default();
span_nodes.push(node);
}
}
} else {
self.push_buf(node);
}
}
fn extend(&mut self, nodes: impl ExactSizeIterator<Item = Node>) {
self.buf.reserve(nodes.len());
for node in nodes {
self.push(node);
}
}
// Postfix drop.
fn finish(self) {}
}
#[derive(Copy, Clone, Eq, PartialEq)]
enum ElementKind {
Grouping,
Block,
Table,
Inline,
}
fn element_kind(tag: &TagKind) -> ElementKind {
match tag {
TagKind::Part(_)
| TagKind::Article(_)
| TagKind::Section(_)
| TagKind::Div(_)
| TagKind::BlockQuote(_)
| TagKind::Caption(_)
| TagKind::TOC(_)
| TagKind::TOCI(_)
| TagKind::Index(_)
| TagKind::NonStruct(_) => ElementKind::Grouping,
TagKind::P(_)
| TagKind::Hn(_)
| TagKind::L(_)
| TagKind::LI(_)
| TagKind::Lbl(_)
| TagKind::LBody(_)
| TagKind::Table(_) => ElementKind::Block,
TagKind::THead(_)
| TagKind::TBody(_)
| TagKind::TFoot(_)
| TagKind::TR(_)
| TagKind::TH(_)
| TagKind::TD(_) => ElementKind::Table,
TagKind::Span(_)
| TagKind::InlineQuote(_)
| TagKind::Note(_)
| TagKind::Reference(_)
| TagKind::BibEntry(_)
| TagKind::Code(_)
| TagKind::Link(_)
| TagKind::Annot(_)
| TagKind::Figure(_)
| TagKind::Formula(_) => ElementKind::Inline,
// Mapped to `Span`.
TagKind::Datetime(_) => ElementKind::Inline,
// Mapped to `Part`.
TagKind::Terms(_) => ElementKind::Grouping,
// Mapped to `P`.
TagKind::Title(_) => ElementKind::Block,
// Mapped to `Span`.
TagKind::Strong(_) | TagKind::Em(_) => ElementKind::Inline,
}
}
fn validate_children(rs: &mut Resolver, tag: &TagKind, children: &[Node]) {
match tag {
TagKind::TOC(_) => validate_children_groups(rs, tag, children, |child| {
matches!(child, TagKind::TOC(_) | TagKind::TOCI(_))
}),
TagKind::TOCI(_) => validate_children_groups(rs, tag, children, |child| {
matches!(
child,
TagKind::TOC(_)
| TagKind::Reference(_)
| TagKind::NonStruct(_)
| TagKind::P(_)
| TagKind::Lbl(_)
)
}),
TagKind::L(_) => validate_children_groups(rs, tag, children, |child| {
matches!(child, TagKind::Caption(_) | TagKind::L(_) | TagKind::LI(_))
}),
TagKind::LI(_) => validate_children_groups(rs, tag, children, |child| {
matches!(child, TagKind::Lbl(_) | TagKind::LBody(_))
}),
TagKind::Table(_) => validate_children_groups(rs, tag, children, |child| {
matches!(
child,
TagKind::Caption(_)
| TagKind::THead(_)
| TagKind::TBody(_)
| TagKind::TFoot(_)
| TagKind::TR(_)
)
}),
TagKind::THead(_) | TagKind::TBody(_) | TagKind::TFoot(_) => {
validate_children_groups(rs, tag, children, |child| {
matches!(child, TagKind::TR(_))
})
}
TagKind::TR(_) => validate_children_groups(rs, tag, children, |child| {
matches!(child, TagKind::TD(_) | TagKind::TH(_))
}),
_ => (),
}
}
fn validate_children_groups(
rs: &mut Resolver,
parent: &TagKind,
children: &[Node],
mut is_valid: impl FnMut(&TagKind) -> bool,
) {
let parent_span = to_span(parent.location());
let mut caption_spans = SmallVec::<[_; 3]>::new();
let mut contains_leaf_nodes = false;
for node in children {
let Node::Group(child) = node else {
contains_leaf_nodes = true;
continue;
};
if !is_valid(&child.tag) {
let validator = rs.options.standards.config.validator().as_str();
let span = to_span(child.tag.location()).or(parent_span);
let parent = tag_name(parent);
let child = tag_name(&child.tag);
rs.errors.push(error!(
span,
"{validator} error: invalid {parent} structure";
hint: "{parent} may not contain {child}";
hint: "this is probably caused by a show rule";
));
} else if matches!(&child.tag, TagKind::Caption(_)) {
caption_spans.push(to_span(child.tag.location()));
}
}
if caption_spans.len() > 1 {
let validator = rs.options.standards.config.validator().as_str();
let parent = tag_name(parent);
let child = tag_name(&Tag::Caption.into());
let caption_error = |span| {
error!(
span,
"{validator} error: invalid {parent} structure";
hint: "{parent} may not contain multiple {child} tags";
hint: "avoid manually calling `figure.caption`";
)
};
if caption_spans.iter().all(|s| !s.is_detached()) {
rs.errors.extend(caption_spans.into_iter().map(caption_error));
} else {
rs.errors.push(caption_error(parent_span));
}
}
if contains_leaf_nodes {
let validator = rs.options.standards.config.validator().as_str();
let parent = tag_name(parent);
rs.errors.push(error!(
parent_span,
"{validator} error: invalid {parent} structure";
hint: "{parent} may not contain marked content directly";
hint: "this is probably caused by a show rule";
));
}
}
fn tag_name(tag: &TagKind) -> &'static str {
match tag {
TagKind::Part(_) => "part (Part)",
TagKind::Article(_) => "article (Art)",
TagKind::Section(_) => "section (Section)",
TagKind::Div(_) => "division (Div)",
TagKind::BlockQuote(_) => "block quote (BlockQuote)",
TagKind::Caption(_) => "caption (Caption)",
TagKind::TOC(_) => "outline (TOC)",
TagKind::TOCI(_) => "outline entry (TOCI)",
TagKind::Index(_) => "index (Index)",
TagKind::P(_) => "paragraph (P)",
TagKind::Hn(_) => "heading (Hn)",
TagKind::L(_) => "list (L)",
TagKind::LI(_) => "list item (LI)",
TagKind::Lbl(_) => "label (Lbl)",
TagKind::LBody(_) => "list body (LBody)",
TagKind::Table(_) => "table (Table)",
TagKind::TR(_) => "table row (TR)",
TagKind::TH(_) => "table header cell (TH)",
TagKind::TD(_) => "table data cell (TD)",
TagKind::THead(_) => "table header (THead)",
TagKind::TBody(_) => "table body (TBody)",
TagKind::TFoot(_) => "table footer (TFoot)",
TagKind::Span(_) => "span (Span)",
TagKind::InlineQuote(_) => "inline quote (Quote)",
TagKind::Note(_) => "note (Note)",
TagKind::Reference(_) => "reference (Reference)",
TagKind::BibEntry(_) => "bibliography entry (BibEntry)",
TagKind::Code(_) => "raw text (Code)",
TagKind::Link(_) => "link (Link)",
TagKind::Annot(_) => "annotation (Annot)",
TagKind::Figure(_) => "figure (Figure)",
TagKind::Formula(_) => "equation (Formula)",
TagKind::NonStruct(_) => "non structural element (NonStruct)",
TagKind::Datetime(_) => "date time (Span)",
TagKind::Terms(_) => "terms (P)",
TagKind::Title(_) => "title (Title)",
TagKind::Strong(_) => "strong (Strong/Span)",
TagKind::Em(_) => "emph (Em/Span)",
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/groups.rs | crates/typst-pdf/src/tags/groups.rs | use std::collections::hash_map::Entry;
use krilla::tagging::{ArtifactType, Identifier, ListNumbering, TagKind};
use rustc_hash::FxHashMap;
use typst_library::foundations::{Content, Packed};
use typst_library::introspection::Location;
use typst_library::layout::{GridCell, Inherit};
use typst_library::math::EquationElem;
use typst_library::model::{LinkMarker, OutlineEntry, TableCell};
use typst_library::text::Locale;
use typst_library::visualize::ImageElem;
use typst_syntax::Span;
use crate::tags::context::{
AnnotationId, BBoxId, FigureId, GridId, ListId, OutlineId, TableId, TagId,
};
use crate::tags::resolve::TagNode;
use crate::tags::tree::{ResolvedTextAttrs, TextAttr};
use crate::tags::util::{self, Id, IdVec};
pub type GroupId = Id<Group>;
impl GroupId {
pub const ROOT: Self = Self::new(0);
pub const INVALID: Self = Self::new(u32::MAX);
}
#[derive(Debug)]
pub struct Groups {
locations: FxHashMap<Location, LocatedGroup>,
pub list: IdVec<Group>,
pub tags: TagStorage,
}
impl Groups {
pub fn new() -> Self {
Self {
locations: FxHashMap::default(),
list: IdVec::new(),
tags: TagStorage::new(),
}
}
pub fn by_loc(&self, loc: &Location) -> Option<LocatedGroup> {
self.locations.get(loc).copied()
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn get(&self, id: GroupId) -> &Group {
self.list.get(id)
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn get_mut(&mut self, id: GroupId) -> &mut Group {
self.list.get_mut(id)
}
/// See [`util::propagate_lang`].
pub fn propagate_lang(&mut self, id: GroupId, lang: Locale) -> Option<Locale> {
// TODO: walk up to the first parent that has a language.
let group = &mut self.get_mut(id);
let Some(parent) = group.kind.lang_mut() else { return Some(lang) };
util::propagate_lang(parent, Some(lang))
}
/// Create a located group. If the location has already been taken,
/// create a new virtual group.
pub fn new_located(
&mut self,
loc: Location,
parent: GroupId,
span: Span,
kind: GroupKind,
) -> GroupId {
let id = self.new_virtual(parent, span, kind);
match self.locations.entry(loc) {
Entry::Occupied(occupied) => {
// Multiple introspection tags have the same location,
// for example because an element was queried and then
// placed again. Create a new group that doesn't have
// a location mapping.
let located = occupied.into_mut();
located.multiple_parents = true;
}
Entry::Vacant(vacant) => {
vacant.insert(LocatedGroup { id, multiple_parents: false });
}
}
id
}
/// Create a new virtual group, not associated with any location.
pub fn new_virtual(
&mut self,
parent: GroupId,
span: Span,
kind: GroupKind,
) -> GroupId {
self.list.push(Group::new(parent, span, kind))
}
/// Create a new weak group, not associated with any location.
pub fn new_weak(&mut self, parent: GroupId, span: Span, kind: GroupKind) -> GroupId {
self.list.push(Group::weak(parent, span, kind))
}
/// NOTE: this needs to be kept in sync with [`Groups::break_group`].
pub fn breakable(&self, kind: &GroupKind) -> BreakOpportunity {
use BreakOpportunity::*;
match kind {
GroupKind::Root(..) => Never,
GroupKind::Artifact(..) => Always(BreakPriority::Span),
GroupKind::LogicalParent(..) => Never,
GroupKind::LogicalChild(..) => Never,
GroupKind::Outline(..) => Never,
GroupKind::OutlineEntry(..) => Never,
GroupKind::Table(..) => Never,
GroupKind::TableCell(..) => Never,
GroupKind::Grid(..) => Never,
GroupKind::GridCell(..) => Never,
GroupKind::List(..) => Never,
GroupKind::ListItemLabel(..) => Never,
GroupKind::ListItemBody(..) => Never,
GroupKind::TermsItemLabel(..) => Never,
GroupKind::TermsItemBody(..) => Never,
GroupKind::BibEntry(..) => Never,
GroupKind::FigureWrapper(..) => Never,
GroupKind::Figure(..) => Never,
GroupKind::FigureCaption(..) => Never,
GroupKind::Image(..) => Never,
GroupKind::Formula(..) => Never,
GroupKind::Link(..) => NoPdfUa(BreakPriority::Span),
GroupKind::CodeBlock(..) => Never,
GroupKind::CodeBlockLine(..) => Never,
GroupKind::Par(..) => NoPdfUa(BreakPriority::Par),
GroupKind::TextAttr(_) => Always(BreakPriority::TextAttr),
GroupKind::Transparent => Never,
GroupKind::Standard(tag, ..) => match self.tags.get(*tag) {
TagKind::Part(_) => Never,
TagKind::Article(_) => Never,
TagKind::Section(_) => Never,
TagKind::Div(_) => Never,
TagKind::BlockQuote(_) => Never,
TagKind::Caption(_) => Never,
TagKind::TOC(_) => Never,
TagKind::TOCI(_) => Never,
TagKind::Index(_) => Never,
TagKind::P(_) => NoPdfUa(BreakPriority::Par),
TagKind::Hn(_) => Never,
TagKind::L(_) => Never,
TagKind::LI(_) => Never,
TagKind::Lbl(_) => Never,
TagKind::LBody(_) => Never,
TagKind::Table(_) => Never,
TagKind::TR(_) => Never,
TagKind::TH(_) => Never,
TagKind::TD(_) => Never,
TagKind::THead(_) => Never,
TagKind::TBody(_) => Never,
TagKind::TFoot(_) => Never,
TagKind::Span(_) => Always(BreakPriority::Span),
TagKind::InlineQuote(_) => Never,
TagKind::Note(_) => Never,
TagKind::Reference(_) => NoPdfUa(BreakPriority::Span),
TagKind::BibEntry(_) => Never,
TagKind::Code(_) => NoPdfUa(BreakPriority::Span),
TagKind::Link(_) => NoPdfUa(BreakPriority::Span),
TagKind::Annot(_) => Never,
TagKind::Figure(_) => Never,
TagKind::Formula(_) => Never,
TagKind::NonStruct(_) => Never,
TagKind::Datetime(_) => Never,
TagKind::Terms(_) => Never,
TagKind::Title(_) => Never,
TagKind::Strong(_) => Always(BreakPriority::Span),
TagKind::Em(_) => Always(BreakPriority::Span),
},
}
}
/// NOTE: this needs to be kept in sync with [`Groups::breakable`].
pub fn break_group(&mut self, id: GroupId, new_parent: GroupId) -> GroupId {
let group = self.get(id);
let span = group.span;
let new_kind = match &group.kind {
GroupKind::Artifact(ty) => GroupKind::Artifact(*ty),
GroupKind::Link(elem, _) => GroupKind::Link(elem.clone(), None),
GroupKind::Par(_) => GroupKind::Par(None),
GroupKind::TextAttr(attr) => GroupKind::TextAttr(attr.clone()),
GroupKind::Standard(old, _) => {
let tag = self.tags.get(*old).clone();
let new = self.tags.push(tag);
GroupKind::Standard(new, None)
}
GroupKind::Root(..)
| GroupKind::LogicalParent(..)
| GroupKind::LogicalChild(..)
| GroupKind::Outline(..)
| GroupKind::OutlineEntry(..)
| GroupKind::Table(..)
| GroupKind::TableCell(..)
| GroupKind::Grid(..)
| GroupKind::GridCell(..)
| GroupKind::List(..)
| GroupKind::ListItemLabel(..)
| GroupKind::ListItemBody(..)
| GroupKind::TermsItemLabel(..)
| GroupKind::TermsItemBody(..)
| GroupKind::BibEntry(..)
| GroupKind::FigureWrapper(..)
| GroupKind::Figure(..)
| GroupKind::FigureCaption(..)
| GroupKind::Image(..)
| GroupKind::Formula(..)
| GroupKind::CodeBlock(..)
| GroupKind::CodeBlockLine(..)
| GroupKind::Transparent => unreachable!(),
};
self.list.push(Group::weak(new_parent, span, new_kind))
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum BreakOpportunity {
/// The group is unbreakable.
Never,
/// The group can only be broken, when
NoPdfUa(BreakPriority),
/// The group can always be broken.
Always(BreakPriority),
}
impl BreakOpportunity {
pub fn get(self, is_pdf_ua: bool) -> Option<BreakPriority> {
match self {
BreakOpportunity::Never => None,
BreakOpportunity::NoPdfUa(p) if !is_pdf_ua => Some(p),
BreakOpportunity::NoPdfUa(_) => None,
BreakOpportunity::Always(p) => Some(p),
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum BreakPriority {
Par,
Span,
TextAttr,
Artifact,
}
impl BreakPriority {
pub const MAX: Self = Self::Artifact;
}
/// These methods are the only way to insert nested groups in the
/// [`Group::nodes`] list.
impl Groups {
/// Create a new group with a standard tag and push it into the parent.
pub fn push_tag(&mut self, parent: GroupId, tag: impl Into<TagKind>) -> GroupId {
let tag_id = self.tags.push(tag);
let kind = GroupKind::Standard(tag_id, None);
let id = self.list.push(Group::new(parent, Span::detached(), kind));
self.get_mut(parent).nodes.push(TagNode::Group(id));
id
}
/// Prepend multiple existing group to the start of the parent.
#[cfg_attr(debug_assertions, track_caller)]
pub fn prepend_groups(&mut self, parent: GroupId, children: &[GroupId]) {
debug_assert!({
children.iter().all(|child| self.check_ancestor(parent, *child))
});
self.get_mut(parent)
.nodes
.splice(..0, children.iter().map(|id| TagNode::Group(*id)));
}
/// Append an existing group to the end of the parent.
#[cfg_attr(debug_assertions, track_caller)]
pub fn push_group(&mut self, parent: GroupId, child: GroupId) {
debug_assert!(self.check_ancestor(parent, child));
self.get_mut(parent).nodes.push(TagNode::Group(child));
}
/// Append multiple existing groups to the end of the parent.
#[cfg_attr(debug_assertions, track_caller)]
pub fn push_groups(&mut self, parent: GroupId, children: &[GroupId]) {
debug_assert!({
children.iter().all(|child| self.check_ancestor(parent, *child))
});
self.get_mut(parent)
.nodes
.extend(children.iter().map(|id| TagNode::Group(*id)));
}
/// Check whether the child's [`Group::parent`] is either the `parent` or an
/// ancestor of the `parent`.
fn check_ancestor(&self, parent: GroupId, child: GroupId) -> bool {
let group = self.get(child);
// Logical children that don't inherit their parent's styles have their
// parent set to the the original location they appeared in the tree,
// but will be inserted into the correct logical parent.
if let GroupKind::LogicalChild(Inherit::No, _) = group.kind {
return true;
}
let ancestor = group.parent;
let mut current = parent;
while current != GroupId::INVALID {
if current == ancestor {
return true;
}
current = self.get(current).parent;
}
false
}
}
#[derive(Debug, Default)]
pub struct TagStorage(Vec<Option<TagKind>>);
impl TagStorage {
pub const fn new() -> Self {
Self(Vec::new())
}
pub fn push(&mut self, tag: impl Into<TagKind>) -> TagId {
let id = TagId::new(self.0.len() as u32);
self.0.push(Some(tag.into()));
id
}
pub fn set(&mut self, id: TagId, tag: impl Into<TagKind>) {
self.0[id.idx()] = Some(tag.into());
}
pub fn get(&self, id: TagId) -> &TagKind {
self.0[id.idx()].as_ref().expect("tag")
}
pub fn take(&mut self, id: TagId) -> TagKind {
self.0[id.idx()].take().expect("tag")
}
}
#[derive(Debug, Copy, Clone)]
pub struct LocatedGroup {
pub id: GroupId,
pub multiple_parents: bool,
}
#[derive(Debug)]
pub struct Group {
/// The parent of this group. Must not be the direct parent in the concrete
/// tag tree that will be built. But it must be an ancestor in the resulting
/// tree. For example for a [`GroupKind::TableCell`] this will point to the
/// parent [`GroupKind::Table`] even though the concrete tag tree will have
/// intermediate [`TagKind::TR`] or [`TagKind::TBody`] groups in the
/// generated `nodes`.
pub parent: GroupId,
pub span: Span,
pub kind: GroupKind,
/// Only allow mutating this list through the API, to ensure the parent
/// will be set for child groups.
nodes: Vec<TagNode>,
/// Whether this group was split off another group as a result of
/// overlapping tags. A weak group will be omitted if it has no children.
pub weak: bool,
}
impl Group {
fn new(parent: GroupId, span: Span, kind: GroupKind) -> Self {
Group { parent, span, kind, nodes: Vec::new(), weak: false }
}
fn weak(parent: GroupId, span: Span, kind: GroupKind) -> Self {
Group { parent, span, kind, nodes: Vec::new(), weak: true }
}
pub fn nodes(&self) -> &[TagNode] {
&self.nodes
}
pub fn push_leaf(&mut self, id: Identifier) {
self.nodes.push(TagNode::Leaf(id));
}
pub fn push_annotation(&mut self, annot_id: AnnotationId) {
self.nodes.push(TagNode::Annotation(annot_id));
}
pub fn push_text(&mut self, new_attrs: ResolvedTextAttrs, text_id: Identifier) {
if new_attrs.is_empty() {
self.push_leaf(text_id);
return;
}
let last_node = self.nodes.last_mut();
if let Some(TagNode::Text(prev_attrs, nodes)) = last_node
&& *prev_attrs == new_attrs
{
nodes.push(text_id);
} else {
self.nodes.push(TagNode::Text(new_attrs, vec![text_id]));
}
}
pub fn pop_node(&mut self) -> Option<TagNode> {
self.nodes.pop()
}
}
pub enum GroupKind {
Root(Option<Locale>),
Artifact(ArtifactType),
LogicalParent(Content),
LogicalChild(Inherit, GroupId),
Outline(OutlineId, Option<Locale>),
OutlineEntry(Packed<OutlineEntry>, Option<Locale>),
Table(TableId, BBoxId, Option<Locale>),
TableCell(Packed<TableCell>, TagId, Option<Locale>),
Grid(GridId, Option<Locale>),
GridCell(Packed<GridCell>, Option<Locale>),
List(ListId, ListNumbering, Option<Locale>),
ListItemLabel(Option<Locale>),
ListItemBody(Option<Locale>),
TermsItemLabel(Option<Locale>),
TermsItemBody(Option<GroupId>, Option<Locale>),
BibEntry(Option<Locale>),
/// An wrapper element that enclosed the figure tag and its caption.
/// If there is no caption, this is omitted.
FigureWrapper(FigureId),
Figure(FigureId, BBoxId, Option<Locale>),
/// The figure caption has a bbox so marked content sequences won't expand
/// the bbox of the parent figure group kind. The caption might be moved
/// into table, or next to to the figure tag.
FigureCaption(BBoxId, Option<Locale>),
Image(Packed<ImageElem>, BBoxId, Option<Locale>),
Formula(Packed<EquationElem>, BBoxId, Option<Locale>),
Link(Packed<LinkMarker>, Option<Locale>),
CodeBlock(Option<Locale>),
CodeBlockLine(Option<Locale>),
/// Whether this paragraph is a `weak` pragraph that is omitted when it
/// contains no children. This can happen when there are overlapping tags
/// and a pragraph is split up.
Par(Option<Locale>),
TextAttr(TextAttr),
Transparent,
Standard(TagId, Option<Locale>),
}
impl std::fmt::Debug for GroupKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.pad(match self {
Self::Root(..) => "Root",
Self::Artifact(..) => "Artifact",
Self::LogicalParent(..) => "LogicalParent",
Self::LogicalChild(..) => "LogicalChild",
Self::Outline(..) => "Outline",
Self::OutlineEntry(..) => "OutlineEntry",
Self::Table(..) => "Table",
Self::TableCell(..) => "TableCell",
Self::Grid(..) => "Grid",
Self::GridCell(..) => "GridCell",
Self::List(..) => "List",
Self::ListItemLabel(..) => "ListItemLabel",
Self::ListItemBody(..) => "ListItemBody",
Self::TermsItemLabel(..) => "TermsItemLabel",
Self::TermsItemBody(..) => "TermsItemBody",
Self::BibEntry(..) => "BibEntry",
Self::FigureWrapper(..) => "FigureWrapper",
Self::Figure(..) => "Figure",
Self::FigureCaption(..) => "FigureCaption",
Self::Image(..) => "Image",
Self::Formula(..) => "Formula",
Self::Link(..) => "Link",
Self::CodeBlock(..) => "CodeBlock",
Self::CodeBlockLine(..) => "CodeBlockLine",
Self::Par(..) => "Par",
Self::TextAttr(..) => "TextAttr",
Self::Transparent => "Transparent",
Self::Standard(..) => "Standard",
})
}
}
impl GroupKind {
pub fn is_artifact(&self) -> bool {
self.as_artifact().is_some()
}
pub fn is_link(&self) -> bool {
matches!(self, Self::Link(..))
}
pub fn as_artifact(&self) -> Option<ArtifactType> {
match *self {
GroupKind::Artifact(ty) => Some(ty),
_ => None,
}
}
pub fn as_link(&self) -> Option<&Packed<LinkMarker>> {
if let Self::Link(v, ..) = self { Some(v) } else { None }
}
pub fn as_table(&self) -> Option<TableId> {
if let Self::Table(id, ..) = self { Some(*id) } else { None }
}
pub fn as_grid(&self) -> Option<GridId> {
if let Self::Grid(id, ..) = self { Some(*id) } else { None }
}
pub fn as_list(&self) -> Option<ListId> {
if let Self::List(id, ..) = self { Some(*id) } else { None }
}
pub fn bbox(&self) -> Option<BBoxId> {
match self {
GroupKind::Table(_, id, _) => Some(*id),
GroupKind::Figure(_, id, _) => Some(*id),
GroupKind::FigureCaption(id, _) => Some(*id),
GroupKind::Image(_, id, _) => Some(*id),
GroupKind::Formula(_, id, _) => Some(*id),
_ => None,
}
}
pub fn lang(&self) -> Option<Option<Locale>> {
Some(match *self {
GroupKind::Root(lang) => lang,
GroupKind::Artifact(_) => return None,
GroupKind::LogicalParent(_) => return None,
GroupKind::LogicalChild(_, _) => return None,
GroupKind::Outline(_, lang) => lang,
GroupKind::OutlineEntry(_, lang) => lang,
GroupKind::Table(_, _, lang) => lang,
GroupKind::TableCell(_, _, lang) => lang,
GroupKind::Grid(_, lang) => lang,
GroupKind::GridCell(_, lang) => lang,
GroupKind::List(_, _, lang) => lang,
GroupKind::ListItemLabel(lang) => lang,
GroupKind::ListItemBody(lang) => lang,
GroupKind::TermsItemLabel(lang) => lang,
GroupKind::TermsItemBody(_, lang) => lang,
GroupKind::BibEntry(lang) => lang,
GroupKind::FigureWrapper(_) => return None,
GroupKind::Figure(_, _, lang) => lang,
GroupKind::FigureCaption(_, lang) => lang,
GroupKind::Image(_, _, lang) => lang,
GroupKind::Formula(_, _, lang) => lang,
GroupKind::Link(_, lang) => lang,
GroupKind::CodeBlock(lang) => lang,
GroupKind::CodeBlockLine(lang) => lang,
GroupKind::Par(lang) => lang,
GroupKind::TextAttr(_) => return None,
GroupKind::Transparent => return None,
GroupKind::Standard(_, lang) => lang,
})
}
pub fn lang_mut(&mut self) -> Option<&mut Option<Locale>> {
Some(match self {
GroupKind::Root(lang) => lang,
GroupKind::Artifact(_) => return None,
GroupKind::LogicalParent(_) => return None,
GroupKind::LogicalChild(_, _) => return None,
GroupKind::Outline(_, lang) => lang,
GroupKind::OutlineEntry(_, lang) => lang,
GroupKind::Table(_, _, lang) => lang,
GroupKind::TableCell(_, _, lang) => lang,
GroupKind::Grid(_, lang) => lang,
GroupKind::GridCell(_, lang) => lang,
GroupKind::List(_, _, lang) => lang,
GroupKind::ListItemLabel(lang) => lang,
GroupKind::ListItemBody(lang) => lang,
GroupKind::TermsItemLabel(lang) => lang,
GroupKind::TermsItemBody(_, lang) => lang,
GroupKind::BibEntry(lang) => lang,
GroupKind::FigureWrapper(_) => return None,
GroupKind::Figure(_, _, lang) => lang,
GroupKind::FigureCaption(_, lang) => lang,
GroupKind::Image(_, _, lang) => lang,
GroupKind::Formula(_, _, lang) => lang,
GroupKind::Link(_, lang) => lang,
GroupKind::CodeBlock(lang) => lang,
GroupKind::CodeBlockLine(lang) => lang,
GroupKind::Par(lang) => lang,
GroupKind::TextAttr(_) => return None,
GroupKind::Transparent => return None,
GroupKind::Standard(_, lang) => lang,
})
}
/// Whether this group is a semantic parent or child group. Non-semantic
/// groups will be ignored when searching the tree hierarchy.
pub fn is_semantic(&self) -> bool {
// While paragraphs do have a semantic meaning, they are automatically
// generated and may interfere with other more strongly structured
// nesting groups. For example the `TermsItemLabel` might be wrapped by
// a paragraph, out of which it is moved into the parent `LI`.
!matches!(
self,
GroupKind::Transparent
| GroupKind::LogicalParent(..)
| GroupKind::LogicalChild(..)
| GroupKind::TextAttr(_)
| GroupKind::Par(_)
)
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/util/prop.rs | crates/typst-pdf/src/tags/util/prop.rs | //! Convenience methods to retrieve a property value by passing the default
//! stylechain.
//! Since in the PDF export all elements are materialized, meaning all of their
//! fields have been copied from the stylechain, there is no point in providing
//! any other stylechain.
use typst_library::foundations::{
NativeElement, RefableProperty, Settable, SettableProperty, StyleChain,
};
pub trait PropertyValCopied<E, T, const I: u8> {
/// Get the copied value.
fn val(&self) -> T;
}
impl<E, T: Copy, const I: u8> PropertyValCopied<E, T, I> for Settable<E, I>
where
E: NativeElement,
E: SettableProperty<I, Type = T>,
{
fn val(&self) -> T {
self.get(StyleChain::default())
}
}
pub trait PropertyValCloned<E, T, const I: u8> {
/// Get the cloned value.
fn val_cloned(&self) -> T;
}
impl<E, T: Clone, const I: u8> PropertyValCloned<E, T, I> for Settable<E, I>
where
E: NativeElement,
E: SettableProperty<I, Type = T>,
{
fn val_cloned(&self) -> T {
self.get_cloned(StyleChain::default())
}
}
pub trait PropertyOptRef<E, T, const I: u8> {
fn opt_ref(&self) -> Option<&T>;
}
impl<E, T, const I: u8> PropertyOptRef<E, T, I> for Settable<E, I>
where
E: NativeElement,
E: SettableProperty<I, Type = Option<T>>,
E: RefableProperty<I>,
{
/// Get an `Option` with a reference to the contained value.
fn opt_ref(&self) -> Option<&T> {
self.get_ref(StyleChain::default()).as_ref()
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/util/idvec.rs | crates/typst-pdf/src/tags/util/idvec.rs | use std::marker::PhantomData;
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub struct IdVec<T> {
inner: Vec<T>,
}
impl<T> IdVec<T> {
pub const fn new() -> Self {
Self { inner: Vec::new() }
}
pub fn next_id(&self) -> Id<T> {
Id::new(self.inner.len() as u32)
}
pub fn push(&mut self, val: T) -> Id<T> {
let id = self.next_id();
self.inner.push(val);
id
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn get(&self, id: Id<T>) -> &T {
&self.inner[id.idx()]
}
#[cfg_attr(debug_assertions, track_caller)]
pub fn get_mut(&mut self, id: Id<T>) -> &mut T {
&mut self.inner[id.idx()]
}
#[allow(unused)]
pub fn iter(&self) -> std::slice::Iter<'_, T> {
self.inner.iter()
}
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
self.inner.iter_mut()
}
pub fn ids(
&self,
) -> impl ExactSizeIterator<Item = Id<T>> + DoubleEndedIterator + use<T> {
(0..self.inner.len()).map(|i| Id::new(i as u32))
}
}
/// A strongly typed ID.
pub struct Id<T> {
id: u32,
_ty: PhantomData<T>,
}
impl<T> Id<T> {
#[inline]
pub const fn new(id: u32) -> Self {
Self { id, _ty: PhantomData::<T> }
}
#[inline]
pub const fn get(self) -> u32 {
self.id
}
#[inline]
pub const fn idx(self) -> usize {
self.id as usize
}
}
impl<T> Copy for Id<T> {}
impl<T> Clone for Id<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> std::fmt::Debug for Id<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let full_name = std::any::type_name::<T>();
let start = full_name.rfind("::").map(|i| i + 2).unwrap_or(0);
let short_name = &full_name[start..];
write!(f, "Id::<{}>({})", short_name, self.id)
}
}
impl<T> Eq for Id<T> {}
impl<T> PartialEq for Id<T> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl<T> Ord for Id<T> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.id.cmp(&other.id)
}
}
impl<T> PartialOrd for Id<T> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<T> std::hash::Hash for Id<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/util/mod.rs | crates/typst-pdf/src/tags/util/mod.rs | use krilla::tagging as kt;
use krilla::tagging::{ArtifactType, NaiveRgbColor};
use typst_library::pdf::{ArtifactKind, TableHeaderScope};
use typst_library::text::Locale;
use typst_library::visualize::Paint;
mod idvec;
mod prop;
pub use idvec::*;
pub use prop::*;
// Best effort fallible conversion.
pub fn paint_to_color(paint: &Paint) -> Option<NaiveRgbColor> {
match paint {
Paint::Solid(color) => {
let c = color.to_rgb();
Some(NaiveRgbColor::new_f32(c.red, c.green, c.blue))
}
Paint::Gradient(_) => None,
Paint::Tiling(_) => None,
}
}
pub trait ArtifactKindExt {
fn to_krilla(self) -> ArtifactType;
}
impl ArtifactKindExt for ArtifactKind {
fn to_krilla(self) -> ArtifactType {
match self {
Self::Header => ArtifactType::Header,
Self::Footer => ArtifactType::Footer,
Self::Page => ArtifactType::Page,
Self::Other => ArtifactType::Other,
}
}
}
pub trait TableHeaderScopeExt {
fn to_krilla(self) -> kt::TableHeaderScope;
}
impl TableHeaderScopeExt for TableHeaderScope {
fn to_krilla(self) -> kt::TableHeaderScope {
match self {
Self::Both => kt::TableHeaderScope::Both,
Self::Column => kt::TableHeaderScope::Column,
Self::Row => kt::TableHeaderScope::Row,
}
}
}
/// Try to propagate the child language to the parent. If the parent language
/// is absent or the same as the child, the language is propagated successfully,
/// this function will return `None`, and the language is written to the parent.
/// Otherwise this function will return `Some`, and the language should be
/// specified for the child.
pub fn propagate_lang(
parent: &mut Option<Locale>,
mut child: Option<Locale>,
) -> Option<Locale> {
if let Some(child) = child.take_if(|c| parent.is_none_or(|p| p == *c)) {
*parent = Some(child);
}
child
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/tree/text.rs | crates/typst-pdf/src/tags/tree/text.rs | use krilla::tagging::{LineHeight, NaiveRgbColor, TextDecorationType};
use typst_library::diag::{SourceDiagnostic, error};
use typst_library::foundations::{Content, Packed, Smart};
use typst_library::layout::Length;
use typst_library::text::{
HighlightElem, OverlineElem, ScriptKind, StrikeElem, SubElem, SuperElem, TextItem,
TextSize, UnderlineElem,
};
use typst_library::visualize::Stroke;
use crate::PdfOptions;
use crate::tags::tree::Tree;
use crate::tags::util::{PropertyOptRef, PropertyValCloned, PropertyValCopied};
use crate::tags::{GroupId, util};
use crate::util::AbsExt;
#[derive(Debug, Clone)]
pub struct TextAttrs {
/// Store the last resolved set of text attributes. The resolution isn't
/// that expensive, but for large bodies of text it is resolved quite often.
last_resolved: Option<(TextParams, ResolvedTextAttrs)>,
items: Vec<(GroupId, TextAttr)>,
}
impl TextAttrs {
pub const fn new() -> Self {
Self { last_resolved: None, items: Vec::new() }
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn push(&mut self, id: GroupId, attr: TextAttr) {
self.last_resolved = None;
self.items.push((id, attr));
}
pub fn insert(&mut self, idx: usize, id: GroupId, attr: TextAttr) {
self.last_resolved = None;
self.items.insert(idx, (id, attr));
}
/// Returns true if a decoration was removed.
pub fn pop(&mut self, id: GroupId) -> bool {
self.last_resolved = None;
self.items.pop_if(|(i, _)| *i == id).is_some()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum TextAttr {
Strong,
Emph,
SuperScript(Packed<SuperElem>),
SubScript(Packed<SubElem>),
Highlight(Packed<HighlightElem>),
Underline(Packed<UnderlineElem>),
Overline(Packed<OverlineElem>),
Strike(Packed<StrikeElem>),
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ResolvedTextAttrs {
pub strong: Option<bool>,
pub emph: Option<bool>,
pub script: Option<ResolvedScript>,
pub background: Option<Option<NaiveRgbColor>>,
pub deco: Option<ResolvedTextDeco>,
}
impl ResolvedTextAttrs {
pub const EMPTY: Self = Self {
strong: None,
emph: None,
script: None,
background: None,
deco: None,
};
pub fn is_empty(&self) -> bool {
self == &Self::EMPTY
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ResolvedScript {
pub baseline_shift: f32,
pub lineheight: LineHeight,
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ResolvedTextDeco {
pub kind: TextDecoKind,
pub color: Option<NaiveRgbColor>,
pub thickness: Option<f32>,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TextDecoKind {
Underline,
Overline,
Strike,
}
impl TextDecoKind {
pub fn to_krilla(self) -> TextDecorationType {
match self {
TextDecoKind::Underline => TextDecorationType::Underline,
TextDecoKind::Overline => TextDecorationType::Overline,
TextDecoKind::Strike => TextDecorationType::LineThrough,
}
}
}
/// A hash of relevant text parameters.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct TextParams(u128);
impl TextParams {
fn new(text: &TextItem) -> TextParams {
TextParams(typst_utils::hash128(&(&text.font, text.size)))
}
}
pub fn resolve_text_attrs(
tree: &mut Tree,
options: &PdfOptions,
text: &TextItem,
) -> ResolvedTextAttrs {
let params = TextParams::new(text);
if let Some((prev_params, attrs)) = tree.state.text_attrs.last_resolved
&& prev_params == params
{
return attrs;
}
let (attrs, error) = compute_attrs(options, &tree.state.text_attrs.items, text);
tree.errors.extend(error);
tree.state.text_attrs.last_resolved = Some((params, attrs));
attrs
}
fn compute_attrs(
options: &PdfOptions,
items: &[(GroupId, TextAttr)],
text: &TextItem,
) -> (ResolvedTextAttrs, Option<SourceDiagnostic>) {
let mut attrs = ResolvedTextAttrs::EMPTY;
let mut resolved_deco: Option<(&Content, ResolvedTextDeco)> = None;
let mut err = None;
for (_, attr) in items.iter().rev() {
match attr {
TextAttr::Strong => {
attrs.strong.get_or_insert(true);
}
TextAttr::Emph => {
attrs.emph.get_or_insert(true);
}
TextAttr::SubScript(sub) => {
attrs.script.get_or_insert_with(|| {
let kind = ScriptKind::Sub;
compute_script(text, kind, sub.baseline.val(), sub.size.val())
});
}
TextAttr::SuperScript(sub) => {
attrs.script.get_or_insert_with(|| {
let kind = ScriptKind::Super;
compute_script(text, kind, sub.baseline.val(), sub.size.val())
});
}
TextAttr::Highlight(highlight) => {
let paint = highlight.fill.opt_ref();
let color = paint.and_then(util::paint_to_color);
attrs.background.get_or_insert(color);
}
TextAttr::Underline(underline) => {
compute_deco(
&mut resolved_deco,
&mut err,
options,
text,
underline.pack_ref(),
TextDecoKind::Underline,
underline.stroke.val_cloned(),
);
}
TextAttr::Overline(overline) => {
compute_deco(
&mut resolved_deco,
&mut err,
options,
text,
overline.pack_ref(),
TextDecoKind::Overline,
overline.stroke.val_cloned(),
);
}
TextAttr::Strike(strike) => {
compute_deco(
&mut resolved_deco,
&mut err,
options,
text,
strike.pack_ref(),
TextDecoKind::Strike,
strike.stroke.val_cloned(),
);
}
}
}
attrs.deco = resolved_deco.map(|(_, d)| d);
(attrs, err)
}
fn compute_script(
text: &TextItem,
kind: ScriptKind,
baseline_shift: Smart<Length>,
lineheight: Smart<TextSize>,
) -> ResolvedScript {
// TODO: The `typographic` setting is ignored for now.
// Is it better to be accurate regarding the layouting, and
// thus don't write any baseline shift and lineheight when
// a typographic sub/super script glyph is used? Or should
// we always write the shift so the sub/super script can be
// picked up by AT?
let script_metrics = kind.read_metrics(text.font.metrics());
// NOTE: The user provided baseline_shift needs to be inverted.
let baseline_shift = (baseline_shift.map(|s| -s.at(text.size)))
.unwrap_or_else(|| script_metrics.vertical_offset.at(text.size));
let lineheight = (lineheight.map(|s| s.0.at(text.size)))
.unwrap_or_else(|| script_metrics.height.at(text.size));
ResolvedScript {
baseline_shift: baseline_shift.to_f32(),
lineheight: LineHeight::Custom(lineheight.to_f32()),
}
}
fn compute_deco<'a>(
resolved: &mut Option<(&'a Content, ResolvedTextDeco)>,
err: &mut Option<SourceDiagnostic>,
options: &PdfOptions,
text: &TextItem,
elem: &'a Content,
kind: TextDecoKind,
stroke: Smart<Stroke>,
) {
match resolved {
Some((elem, deco)) => {
// PDF can only represent one text decoration style at a time.
// If PDF/UA-1 is enforced throw an error.
if err.is_none() && deco.kind != kind && options.is_pdf_ua() {
let validator = options.standards.config.validator().as_str();
let span = elem.span();
*err = Some(error!(
span,
"{validator} error: cannot combine underline, overline, or strike",
));
}
}
None => {
let color = (stroke.as_ref().custom())
.and_then(|s| s.paint.as_ref().custom())
.and_then(util::paint_to_color);
let thickness = (stroke.as_ref().custom())
.and_then(|s| s.thickness.custom())
.map(|t| t.at(text.size).to_f32());
let deco = ResolvedTextDeco { kind, color, thickness };
*resolved = Some((elem, deco));
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/tree/build.rs | crates/typst-pdf/src/tags/tree/build.rs | //! Building the logical tree.
//!
//! The tree of [`Frame`]s which is split up into pages doesn't necessarily
//! represent the logical structure of the Typst document. The logical structure
//! is instead defined by the start and end [`introspection::Tag`]s and
//! additional insertions of frames by the means of [`Frame::set_parent`].
//! These inserted frames resolve to groups of kind [`GroupKind::LogicalChild`].
//!
//! This module resolves the logical structure in a pre-pass, so that the
//! complete logical tree is available when the document's content is converted.
//!
//! [`introspection::Tag`]: typst_library::introspection::Tag
//! [`FrameItem::parent`]: typst_library::layout::FrameItem
use std::num::NonZeroU16;
use std::ops::ControlFlow;
use ecow::EcoVec;
use krilla::tagging::{ArtifactType, ListNumbering, Tag, TagKind};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use typst_library::diag::{
At, ExpectInternal, SourceDiagnostic, SourceResult, assert_internal, bail, error,
panic_internal,
};
use typst_library::foundations::{Content, ContextElem};
use typst_library::introspection::Location;
use typst_library::layout::{
Frame, FrameItem, FrameParent, GridCell, GridElem, GroupItem, HideElem, Inherit,
PagedDocument, PlaceElem, RepeatElem,
};
use typst_library::math::EquationElem;
use typst_library::model::{
EmphElem, EnumElem, FigureCaption, FigureElem, FootnoteElem, FootnoteEntry,
HeadingElem, LinkMarker, ListElem, Outlinable, OutlineEntry, ParElem, QuoteElem,
StrongElem, TableCell, TableElem, TermsElem, TitleElem,
};
use typst_library::pdf::{ArtifactElem, PdfMarkerTag, PdfMarkerTagKind};
use typst_library::text::{
HighlightElem, OverlineElem, RawElem, RawLine, StrikeElem, SubElem, SuperElem,
UnderlineElem,
};
use typst_library::visualize::ImageElem;
use typst_syntax::Span;
use crate::PdfOptions;
use crate::tags::GroupId;
use crate::tags::context::{Ctx, FigureCtx, GridCtx, ListCtx, OutlineCtx, TableCtx};
use crate::tags::groups::{BreakOpportunity, BreakPriority, GroupKind, Groups};
use crate::tags::tree::text::TextAttr;
use crate::tags::tree::{Break, TraversalStates, Tree, Unfinished};
use crate::tags::util::{ArtifactKindExt, PropertyValCopied};
pub struct TreeBuilder<'a> {
options: &'a PdfOptions<'a>,
/// Each [`FrameItem::Tag`] and each [`FrameItem::Group`] with a parent
/// will append a progression to this tree. This list of progressions is
/// used to determine the location in the tree when doing the actual PDF
/// generation and inserting the marked content sequences.
progressions: Vec<GroupId>,
breaks: Vec<Break>,
unfinished: Vec<Unfinished>,
groups: Groups,
ctx: Ctx,
logical_children: FxHashMap<Location, SmallVec<[GroupId; 4]>>,
errors: EcoVec<SourceDiagnostic>,
stack: TagStack,
/// Currently only used for table/grid cells that are broken across multiple
/// regions, and thus can have opening/closing introspection tags that are
/// in completely different frames, due to the logical parenting mechanism.
unfinished_stacks: FxHashMap<Location, Vec<StackEntry>>,
}
impl<'a> TreeBuilder<'a> {
pub fn new(document: &PagedDocument, options: &'a PdfOptions) -> Self {
let doc_lang = document.info.locale.custom();
let mut groups = Groups::new();
let doc = groups.new_virtual(
GroupId::INVALID,
Span::detached(),
GroupKind::Root(doc_lang),
);
Self {
options,
progressions: vec![doc],
breaks: Vec::new(),
unfinished: Vec::new(),
groups,
ctx: Ctx::new(),
logical_children: FxHashMap::default(),
errors: EcoVec::new(),
stack: TagStack::new(),
unfinished_stacks: FxHashMap::default(),
}
}
pub fn finish(self) -> Tree {
Tree {
prog_cursor: 0,
progressions: self.progressions,
break_cursor: 0,
breaks: self.breaks,
unfinished_cursor: 0,
unfinished: self.unfinished,
state: TraversalStates::new(),
groups: self.groups,
ctx: self.ctx,
logical_children: self.logical_children,
errors: self.errors,
}
}
pub fn root_document(&self) -> GroupId {
self.progressions[0]
}
/// The last group in the progression.
pub fn current(&self) -> GroupId {
*self.progressions.last().unwrap()
}
/// The last group on the stack or the root document.
pub fn parent(&self) -> GroupId {
self.stack.last().map(|e| e.id).unwrap_or(self.root_document())
}
pub fn parent_kind(&self) -> &GroupKind {
&self.groups.get(self.parent()).kind
}
}
#[derive(Debug)]
struct TagStack {
items: Vec<StackEntry>,
}
impl std::ops::Deref for TagStack {
type Target = Vec<StackEntry>;
fn deref(&self) -> &Self::Target {
&self.items
}
}
impl std::ops::DerefMut for TagStack {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.items
}
}
impl TagStack {
fn new() -> Self {
Self { items: Vec::new() }
}
/// Remove all stack entries after the idx.
fn take_unfinished_stack(&mut self, idx: usize) -> Option<Vec<StackEntry>> {
if idx + 1 < self.items.len() {
Some(self.items.drain(idx + 1..).collect())
} else {
None
}
}
}
#[derive(Debug, Copy, Clone)]
struct StackEntry {
/// The location of the stack entry. If this is `None` the stack entry has
/// to be manually popped.
loc: Option<Location>,
id: GroupId,
prog_idx: u32,
}
pub fn build(document: &PagedDocument, options: &PdfOptions) -> SourceResult<Tree> {
let mut tree = TreeBuilder::new(document, options);
for page in document.pages.iter() {
visit_frame(&mut tree, &page.frame)?;
}
if let Some(last) = tree.stack.last() {
panic_internal("tags weren't properly closed")
.at(tree.groups.get(last.id).span)?;
}
assert_internal(tree.unfinished_stacks.is_empty(), "tags weren't properly closed")
.at(Span::detached())?;
assert_internal(
tree.progressions.first() == tree.progressions.last(),
"tags weren't properly closed",
)
.at(Span::detached())?;
// Insert logical children into the tree.
#[allow(clippy::iter_over_hash_type)]
for (loc, children) in tree.logical_children.iter() {
let located = (tree.groups.by_loc(loc))
.expect_internal("parent group")
.at(Span::detached())?;
if options.is_pdf_ua() && located.multiple_parents {
let validator = options.standards.config.validator().as_str();
let group = tree.groups.get(located.id);
bail!(
group.span,
"{validator} error: ambiguous logical parent";
hint: "please report this as a bug";
);
}
for child in children.iter() {
let child = tree.groups.get_mut(*child);
let GroupKind::LogicalChild(inherit, logical_parent) = &mut child.kind else {
unreachable!()
};
*logical_parent = located.id;
// Move the child into its logical parent, so artifact, bbox, and
// text attributes are inherited.
if *inherit == Inherit::Yes {
child.parent = located.id;
}
}
}
#[cfg(debug_assertions)]
for group in tree.groups.list.iter().skip(1) {
assert_ne!(group.parent, GroupId::INVALID);
}
Ok(tree.finish())
}
fn visit_frame(tree: &mut TreeBuilder, frame: &Frame) -> SourceResult<()> {
for (_, item) in frame.items() {
match item {
FrameItem::Group(group) => visit_group_frame(tree, group)?,
FrameItem::Tag(typst_library::introspection::Tag::Start(elem, flags)) => {
if flags.tagged {
visit_start_tag(tree, elem);
}
}
FrameItem::Tag(typst_library::introspection::Tag::End(loc, _, flags)) => {
if flags.tagged {
visit_end_tag(tree, *loc)?;
}
}
FrameItem::Text(_) => (),
FrameItem::Shape(..) => (),
FrameItem::Image(..) => (),
FrameItem::Link(..) => (),
}
}
Ok(())
}
/// Handle children frames logically belonging to another element, because
/// [typst_library::layout::GroupItem::parent] has been set. All elements that
/// can have children set by this mechanism must be handled in [`handle_start`]
/// and must produce a located [`Group`], so the children can be inserted there.
///
/// Currently the the frame parent is only set for:
/// - place elements [`PlaceElem`]
/// - footnote entries [`FootnoteEntry`]
/// - broken table/grid cells [`TableCell`]/[`GridCell`]
fn visit_group_frame(tree: &mut TreeBuilder, group: &GroupItem) -> SourceResult<()> {
let Some(parent) = group.parent else {
return visit_frame(tree, &group.frame);
};
// Push the logical child.
let prev = tree.current();
let stack_idx = tree.stack.len();
let id = push_logical_child(tree, parent);
tree.progressions.push(id);
// Handle the group frame.
visit_frame(tree, &group.frame)?;
// Pop logical child.
pop_logical_child(tree, parent, stack_idx);
tree.progressions.push(prev);
Ok(())
}
fn push_logical_child(tree: &mut TreeBuilder, parent: FrameParent) -> GroupId {
let id = tree.groups.new_virtual(
match parent.inherit {
Inherit::Yes => GroupId::INVALID,
Inherit::No => tree.current(),
},
Span::detached(),
GroupKind::LogicalChild(parent.inherit, GroupId::INVALID),
);
tree.logical_children.entry(parent.location).or_default().push(id);
push_stack_entry(tree, None, id);
if let Some(stack) = tree.unfinished_stacks.remove(&parent.location) {
tree.stack.extend(stack);
}
// Move to the top of the stack, including the pushed on unfinished stack.
tree.stack.last().unwrap().id
}
fn pop_logical_child(tree: &mut TreeBuilder, parent: FrameParent, stack_idx: usize) {
if let Some(stack) = tree.stack.take_unfinished_stack(stack_idx) {
tree.unfinished_stacks.insert(parent.location, stack);
tree.unfinished.push(Unfinished {
prog_idx: tree.progressions.len() as u32,
group_to_close: tree.stack[stack_idx].id,
});
}
tree.stack.pop().expect("stack entry");
}
fn visit_start_tag(tree: &mut TreeBuilder, elem: &Content) {
let group_id = progress_tree_start(tree, elem);
tree.progressions.push(group_id);
}
fn visit_end_tag(tree: &mut TreeBuilder, loc: Location) -> SourceResult<()> {
let group = progress_tree_end(tree, loc)?;
tree.progressions.push(group);
Ok(())
}
fn progress_tree_start(tree: &mut TreeBuilder, elem: &Content) -> GroupId {
// Artifacts
#[allow(clippy::redundant_pattern_matching)]
if let Some(_) = elem.to_packed::<HideElem>() {
push_artifact(tree, elem, ArtifactType::Other)
} else if let Some(artifact) = elem.to_packed::<ArtifactElem>() {
let kind = artifact.kind.val();
push_artifact(tree, elem, kind.to_krilla())
} else if let Some(_) = elem.to_packed::<RepeatElem>() {
push_artifact(tree, elem, ArtifactType::Other)
// Elements
} else if let Some(tag) = elem.to_packed::<PdfMarkerTag>() {
match &tag.kind {
PdfMarkerTagKind::OutlineBody => {
let id = tree.ctx.outlines.push(OutlineCtx::new());
push_group(tree, elem, GroupKind::Outline(id, None))
}
PdfMarkerTagKind::Bibliography(numbered) => {
let numbering =
if *numbered { ListNumbering::Decimal } else { ListNumbering::None };
let id = tree.ctx.lists.push(ListCtx::new());
push_group(tree, elem, GroupKind::List(id, numbering, None))
}
PdfMarkerTagKind::BibEntry => {
push_group(tree, elem, GroupKind::BibEntry(None))
}
PdfMarkerTagKind::ListItemLabel => {
push_group(tree, elem, GroupKind::ListItemLabel(None))
}
PdfMarkerTagKind::ListItemBody => {
push_group(tree, elem, GroupKind::ListItemBody(None))
}
PdfMarkerTagKind::TermsItemLabel => {
push_group(tree, elem, GroupKind::TermsItemLabel(None))
}
PdfMarkerTagKind::TermsItemBody => {
push_group(tree, elem, GroupKind::TermsItemBody(None, None))
}
PdfMarkerTagKind::Label => push_tag(tree, elem, Tag::Lbl),
}
} else if let Some(link) = elem.to_packed::<LinkMarker>() {
push_group(tree, elem, GroupKind::Link(link.clone(), None))
} else if let Some(_) = elem.to_packed::<TitleElem>() {
push_tag(tree, elem, Tag::Title)
} else if let Some(entry) = elem.to_packed::<OutlineEntry>() {
push_group(tree, elem, GroupKind::OutlineEntry(entry.clone(), None))
} else if let Some(_) = elem.to_packed::<ListElem>() {
// TODO: infer numbering from `list.marker`
let numbering = ListNumbering::Circle;
let id = tree.ctx.lists.push(ListCtx::new());
push_group(tree, elem, GroupKind::List(id, numbering, None))
} else if let Some(_) = elem.to_packed::<EnumElem>() {
// TODO: infer numbering from `enum.numbering`
let numbering = ListNumbering::Decimal;
let id = tree.ctx.lists.push(ListCtx::new());
push_group(tree, elem, GroupKind::List(id, numbering, None))
} else if let Some(_) = elem.to_packed::<TermsElem>() {
let numbering = ListNumbering::None;
let id = tree.ctx.lists.push(ListCtx::new());
push_group(tree, elem, GroupKind::List(id, numbering, None))
} else if let Some(figure) = elem.to_packed::<FigureElem>() {
let lang = figure.locale;
let bbox = tree.ctx.new_bbox();
let group_id = tree.groups.list.next_id();
let figure_id = tree.ctx.figures.push(FigureCtx::new(group_id, figure.clone()));
push_group(tree, elem, GroupKind::Figure(figure_id, bbox, lang))
} else if let Some(_) = elem.to_packed::<FigureCaption>() {
let bbox = tree.ctx.new_bbox();
push_group(tree, elem, GroupKind::FigureCaption(bbox, None))
} else if let Some(image) = elem.to_packed::<ImageElem>() {
let lang = image.locale;
let bbox = tree.ctx.new_bbox();
push_group(tree, elem, GroupKind::Image(image.clone(), bbox, lang))
} else if let Some(equation) = elem.to_packed::<EquationElem>() {
let lang = equation.locale;
let bbox = tree.ctx.new_bbox();
push_group(tree, elem, GroupKind::Formula(equation.clone(), bbox, lang))
} else if let Some(table) = elem.to_packed::<TableElem>() {
let group_id = tree.groups.list.next_id();
let table_id = tree.ctx.tables.next_id();
tree.ctx.tables.push(TableCtx::new(group_id, table_id, table.clone()));
let bbox = tree.ctx.new_bbox();
push_group(tree, elem, GroupKind::Table(table_id, bbox, None))
} else if let Some(cell) = elem.to_packed::<TableCell>() {
// Only repeated table headers and footer cells are laid out multiple
// times. Mark duplicate headers as artifacts, since they have no
// semantic meaning in the tag tree, which doesn't use page breaks for
// it's semantic structure.
let kind = if cell.is_repeated.val() {
GroupKind::Artifact(ArtifactType::Other)
} else {
let tag = tree.groups.tags.push(Tag::TD);
GroupKind::TableCell(cell.clone(), tag, None)
};
push_located(tree, elem, kind)
} else if let Some(grid) = elem.to_packed::<GridElem>() {
let group_id = tree.groups.list.next_id();
let id = tree.ctx.grids.push(GridCtx::new(group_id, grid));
push_group(tree, elem, GroupKind::Grid(id, None))
} else if let Some(cell) = elem.to_packed::<GridCell>() {
// The grid cells are collected into a grid to ensure proper reading
// order even when using rowspans, which may be laid out later than
// other cells in the same row.
let kind = if !matches!(tree.parent_kind(), GroupKind::Grid(..)) {
// If there is no grid parent, this means a grid layouter is used
// internally.
GroupKind::Transparent
} else if cell.is_repeated.val() {
// Only repeated grid headers and footer cells are laid out multiple
// times. Mark duplicate headers as artifacts, since they have no
// semantic meaning in the tag tree, which doesn't use page breaks
// for it's semantic structure.
GroupKind::Artifact(ArtifactType::Other)
} else {
GroupKind::GridCell(cell.clone(), None)
};
push_located(tree, elem, kind)
} else if let Some(heading) = elem.to_packed::<HeadingElem>() {
let level = heading.level().try_into().unwrap_or(NonZeroU16::MAX);
let title = heading.body.plain_text().to_string();
if title.is_empty() && tree.options.is_pdf_ua() {
let contains_context = heading.body.traverse(&mut |c| {
if c.is::<ContextElem>() {
return ControlFlow::Break(());
}
ControlFlow::Continue(())
});
let validator = tree.options.standards.config.validator().as_str();
tree.errors.push(if contains_context.is_break() {
error!(
heading.span(),
"{validator} error: heading title could not be determined";
hint: "this seems to be caused by a context expression within the \
heading";
hint: "consider wrapping the entire heading in a context expression \
instead";
)
} else {
error!(heading.span(), "{validator} error: heading title is empty")
});
}
push_tag(tree, elem, Tag::Hn(level, Some(title)))
} else if let Some(_) = elem.to_packed::<FootnoteElem>() {
push_located(tree, elem, GroupKind::LogicalParent(elem.clone()))
} else if let Some(_) = elem.to_packed::<FootnoteEntry>() {
push_tag(tree, elem, Tag::Note)
} else if let Some(quote) = elem.to_packed::<QuoteElem>() {
// TODO: should the attribution be handled somehow?
if quote.block.val() {
push_tag(tree, elem, Tag::BlockQuote)
} else {
push_tag(tree, elem, Tag::InlineQuote)
}
} else if let Some(raw) = elem.to_packed::<RawElem>() {
if raw.block.val() {
push_group(tree, elem, GroupKind::CodeBlock(None))
} else {
push_tag(tree, elem, Tag::Code)
}
} else if let Some(_) = elem.to_packed::<RawLine>() {
// If the raw element is inline, the content can be inserted directly.
if matches!(tree.parent_kind(), GroupKind::CodeBlock(..)) {
push_group(tree, elem, GroupKind::CodeBlockLine(None))
} else {
no_progress(tree)
}
} else if let Some(place) = elem.to_packed::<PlaceElem>() {
if place.float.val() {
push_located(tree, elem, GroupKind::LogicalParent(elem.clone()))
} else {
no_progress(tree)
}
} else if let Some(_) = elem.to_packed::<ParElem>() {
push_weak(tree, elem, GroupKind::Par(None))
// Text attributes
} else if let Some(_strong) = elem.to_packed::<StrongElem>() {
push_text_attr(tree, elem, TextAttr::Strong)
} else if let Some(_emph) = elem.to_packed::<EmphElem>() {
push_text_attr(tree, elem, TextAttr::Emph)
} else if let Some(sub) = elem.to_packed::<SubElem>() {
push_text_attr(tree, elem, TextAttr::SubScript(sub.clone()))
} else if let Some(sup) = elem.to_packed::<SuperElem>() {
push_text_attr(tree, elem, TextAttr::SuperScript(sup.clone()))
} else if let Some(highlight) = elem.to_packed::<HighlightElem>() {
push_text_attr(tree, elem, TextAttr::Highlight(highlight.clone()))
} else if let Some(underline) = elem.to_packed::<UnderlineElem>() {
push_text_attr(tree, elem, TextAttr::Underline(underline.clone()))
} else if let Some(overline) = elem.to_packed::<OverlineElem>() {
push_text_attr(tree, elem, TextAttr::Overline(overline.clone()))
} else if let Some(strike) = elem.to_packed::<StrikeElem>() {
push_text_attr(tree, elem, TextAttr::Strike(strike.clone()))
} else {
no_progress(tree)
}
}
fn no_progress(tree: &TreeBuilder) -> GroupId {
tree.current()
}
fn push_tag(tree: &mut TreeBuilder, elem: &Content, tag: impl Into<TagKind>) -> GroupId {
let id = tree.groups.tags.push(tag.into());
push_group(tree, elem, GroupKind::Standard(id, None))
}
fn push_text_attr(tree: &mut TreeBuilder, elem: &Content, attr: TextAttr) -> GroupId {
push_group(tree, elem, GroupKind::TextAttr(attr))
}
fn push_artifact(tree: &mut TreeBuilder, elem: &Content, ty: ArtifactType) -> GroupId {
push_group(tree, elem, GroupKind::Artifact(ty))
}
fn push_group(tree: &mut TreeBuilder, elem: &Content, kind: GroupKind) -> GroupId {
let loc = elem.location().expect("elem to have a location");
let span = elem.span();
let parent = tree.current();
let id = tree.groups.new_virtual(parent, span, kind);
push_stack_entry(tree, Some(loc), id)
}
fn push_located(tree: &mut TreeBuilder, elem: &Content, kind: GroupKind) -> GroupId {
let loc = elem.location().expect("elem to have a location");
let span = elem.span();
let parent = tree.current();
let id = tree.groups.new_located(loc, parent, span, kind);
push_stack_entry(tree, Some(loc), id)
}
fn push_weak(tree: &mut TreeBuilder, elem: &Content, kind: GroupKind) -> GroupId {
let loc = elem.location().expect("elem to have a location");
let span = elem.span();
let parent = tree.current();
let id = tree.groups.new_weak(parent, span, kind);
push_stack_entry(tree, Some(loc), id)
}
fn push_stack_entry(
tree: &mut TreeBuilder,
loc: Option<Location>,
id: GroupId,
) -> GroupId {
let prog_idx = tree.progressions.len() as u32;
let entry = StackEntry { loc, id, prog_idx };
tree.stack.push(entry);
id
}
fn progress_tree_end(tree: &mut TreeBuilder, loc: Location) -> SourceResult<GroupId> {
if tree.stack.pop_if(|e| e.loc == Some(loc)).is_some() {
// The tag nesting was properly closed.
return Ok(tree.parent());
}
// Search for an improperly nested starting tag, that is being closed.
let Some(stack_idx) = (tree.stack.iter().enumerate())
.rev()
.find_map(|(i, e)| (e.loc == Some(loc)).then_some(i))
else {
// The start tag isn't in the tag stack, just ignore the end tag.
return Ok(no_progress(tree));
};
let entry = tree.stack[stack_idx];
let outer = tree.groups.get(entry.id);
// There are overlapping tags in the tag tree. Figure out whether breaking
// up the current tag stack is semantically ok, and how to do it.
let is_pdf_ua = tree.options.is_pdf_ua();
let mut inner_break_priority = Some(BreakPriority::MAX);
let mut inner_non_breakable_span = Span::detached();
let mut inner_non_breakable_in_pdf_ua = false;
for e in tree.stack.iter().skip(stack_idx + 1) {
let group = tree.groups.get(e.id);
let opportunity = tree.groups.breakable(&group.kind);
let Some(priority) = opportunity.get(is_pdf_ua) else {
if inner_non_breakable_span.is_detached() {
inner_non_breakable_span = group.span;
}
if let BreakOpportunity::NoPdfUa(_) = opportunity {
inner_non_breakable_in_pdf_ua = true;
}
inner_break_priority = None;
continue;
};
if let Some(inner) = &mut inner_break_priority {
*inner = (*inner).min(priority)
}
}
let outer_break_opportunity = tree.groups.breakable(&outer.kind);
let outer_break_priority = outer_break_opportunity.get(is_pdf_ua);
match (outer_break_priority, inner_break_priority) {
(Some(outer_priority), Some(inner_priority)) => {
// Prefer splitting up the inner groups.
if inner_priority >= outer_priority {
Ok(split_inner_groups(tree, outer.parent, stack_idx))
} else {
Ok(split_outer_group(tree, outer.parent, stack_idx))
}
}
(Some(_), None) => Ok(split_outer_group(tree, outer.parent, stack_idx)),
(None, Some(_)) => Ok(split_inner_groups(tree, outer.parent, stack_idx)),
(None, None) => {
let non_breakable_span = if inner_non_breakable_span.is_detached() {
outer.span
} else {
inner_non_breakable_span
};
let non_breakable_in_pdf_ua = inner_non_breakable_in_pdf_ua
|| matches!(outer_break_opportunity, BreakOpportunity::NoPdfUa(_));
if non_breakable_in_pdf_ua {
let validator = tree.options.standards.config.validator().as_str();
bail!(
non_breakable_span,
"{validator} error: invalid document structure, \
this element's PDF tag would be split up";
hint: "this is probably caused by paragraph grouping";
hint: "maybe you've used a `parbreak`, `colbreak`, or `pagebreak`";
);
} else {
bail!(
non_breakable_span,
"invalid document structure, \
this element's PDF tag would be split up";
hint: "please report this as a bug";
);
}
}
}
}
/// Consider the following introspection tags:
/// ```txt
/// start a
/// start b
/// start c
/// end a
/// end c
/// end b
/// ```
/// This will split the inner groups, producing the following tag tree:
/// ```yml
/// - a:
/// - b:
/// - c:
/// - b:
/// - c:
/// ```
fn split_inner_groups(
tree: &mut TreeBuilder,
mut parent: GroupId,
stack_idx: usize,
) -> GroupId {
// Since the broken groups won't be visited again in any future progression,
// they'll need to be closed when this progression is visited.
let num_closed = (tree.stack.len() - stack_idx) as u16;
tree.breaks.push(Break {
prog_idx: tree.progressions.len() as u32,
num_closed,
num_opened: num_closed - 1,
});
// Remove the closed entry.
tree.stack.remove(stack_idx);
// Duplicate all broken entries.
for entry in tree.stack.iter_mut().skip(stack_idx) {
let new_id = tree.groups.break_group(entry.id, parent);
*entry = StackEntry {
loc: entry.loc,
id: new_id,
prog_idx: tree.progressions.len() as u32,
};
parent = new_id;
}
// We're now in a new duplicated group
tree.parent()
}
/// Consider the following introspection tags:
/// ```txt
/// OPEN a
/// OPEN b
/// OPEN c
/// END a
/// END c
/// END b
/// ```
/// This will split the outer group, producing the following tag tree:
/// ```yml
/// - a:
/// - b:
/// - a:
/// - c:
/// - a:
/// ```
fn split_outer_group(
tree: &mut TreeBuilder,
parent: GroupId,
stack_idx: usize,
) -> GroupId {
let prev = tree.current();
// Remove the closed entry;
let outer = tree.stack.remove(stack_idx);
// Move the nested group out of the outer entry.
tree.groups.get_mut(tree.stack[stack_idx].id).parent = parent;
let mut entry_iter = tree.stack.iter().skip(stack_idx).peekable();
while let Some(entry) = entry_iter.next() {
let next_entry = entry_iter.peek().map(|e| e.id);
let nested = tree.groups.break_group(outer.id, entry.id);
// Move all children of the stack entry into the nested group.
for (id, group) in tree.groups.list.ids().zip(tree.groups.list.iter_mut()).rev() {
// Avoid searching *all* groups! The children of this group are guaranteed to be
// created after the outer group and thus have a higher ID.
if id == outer.id {
break;
}
// Don't move the nested group into itself, or the next stack entry
// into the nested group.
if group.parent == entry.id && id != nested && Some(id) != next_entry {
group.parent = nested;
}
}
// Update progressions to jump into the inner entry instead.
let prev = tree.progressions[entry.prog_idx as usize];
for prog in tree.progressions[entry.prog_idx as usize..].iter_mut() {
if *prog == prev {
*prog = nested;
}
}
// Either update an existing break, or insert a new one.
let mut break_idx = Some(tree.breaks.len());
for (i, brk) in tree.breaks.iter_mut().enumerate().rev() {
if brk.prog_idx == entry.prog_idx {
brk.num_closed += 1;
brk.num_opened += 1;
break_idx = None;
break;
} else if brk.prog_idx < entry.prog_idx {
break_idx = Some(i + 1);
break;
}
}
if let Some(idx) = break_idx {
// Insert a break to close the previous broken group, and enter
// the new group.
let brk = Break {
prog_idx: entry.prog_idx,
num_closed: 1,
num_opened: 2,
};
tree.breaks.insert(idx, brk);
}
}
// We're still in the same group, but the outer group has been split up.
debug_assert_eq!(tree.parent(), prev);
tree.parent()
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/tree/mod.rs | crates/typst-pdf/src/tags/tree/mod.rs | use crate::PdfOptions;
use crate::tags::GroupId;
use crate::tags::context::{BBoxCtx, BBoxId, Ctx};
use crate::tags::groups::{Group, GroupKind, Groups};
use crate::tags::tree::build::TreeBuilder;
use crate::tags::tree::text::TextAttrs;
use ecow::EcoVec;
use krilla::surface::Surface;
use krilla::tagging::{ArtifactType, ContentTag, Tag};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use typst_library::diag::{HintedStrResult, SourceDiagnostic, assert_internal};
use typst_library::foundations::Packed;
use typst_library::introspection::Location;
use typst_library::layout::{Inherit, PagedDocument};
use typst_library::model::LinkMarker;
pub use build::build;
pub use text::{ResolvedTextAttrs, TextAttr, resolve_text_attrs};
mod build;
mod text;
pub struct Tree {
/// Points at the current group in the `progressions` list.
prog_cursor: usize,
progressions: Vec<GroupId>,
/// Points at the next break in the `breaks` list.
break_cursor: usize,
breaks: Vec<Break>,
/// Points at the next intem in the `unfinished` list.
unfinished_cursor: usize,
unfinished: Vec<Unfinished>,
state: TraversalStates,
pub groups: Groups,
pub ctx: Ctx,
logical_children: FxHashMap<Location, SmallVec<[GroupId; 4]>>,
pub errors: EcoVec<SourceDiagnostic>,
}
impl Tree {
pub fn empty(document: &PagedDocument, options: &PdfOptions) -> Self {
TreeBuilder::new(document, options).finish()
}
pub fn current(&self) -> GroupId {
self.progressions[self.prog_cursor]
}
/// Find the lowest link ancestor in the tree.
pub fn parent_link(&self) -> Option<(GroupId, &Packed<LinkMarker>)> {
let mut current = self.current();
while current != GroupId::INVALID {
let group = self.groups.get(current);
if let Some(link) = group.kind.as_link() {
return Some((current, link));
}
current = group.parent;
}
None
}
/// Find the highest artifact ancestor in the tree.
pub fn parent_artifact(&self) -> Option<ArtifactType> {
let (_, ty) = self.state.current_artifact?;
Some(ty)
}
/// Find the lowest ancestor with a bounding box in the tree.
pub fn parent_bbox(&mut self) -> Option<&mut BBoxCtx> {
let id = *self.state.bbox_stack.last()?;
Some(self.ctx.bboxes.get_mut(id))
}
pub fn assert_finished_traversal(&self) -> HintedStrResult<()> {
assert_internal(
self.prog_cursor + 1 == self.progressions.len(),
"tree traversal didn't complete properly",
)?;
assert_internal(
self.break_cursor == self.breaks.len(),
"tree traversal didn't complete properly",
)?;
assert_internal(
self.unfinished_cursor == self.unfinished.len(),
"tree traversal didn't complete properly",
)?;
Ok(())
}
}
/// A stack of traversal states, the topmost entry represents the current state
/// in the tree. New stack entries are pushed on when entering a logical child
/// and popped off when leaving one.
struct TraversalStates {
/// Always non-empty.
stack: Vec<TraversalState>,
}
impl TraversalStates {
fn new() -> Self {
Self { stack: vec![TraversalState::new()] }
}
fn push(&mut self, state: TraversalState) {
self.stack.push(state);
}
fn pop(&mut self) {
self.stack.pop();
}
}
impl std::ops::Deref for TraversalStates {
type Target = TraversalState;
fn deref(&self) -> &Self::Target {
self.stack.last().unwrap()
}
}
impl std::ops::DerefMut for TraversalStates {
fn deref_mut(&mut self) -> &mut Self::Target {
self.stack.last_mut().unwrap()
}
}
/// Stores frequently accessed properties about the current tree traversal
/// position. This is an optimization to avoid searching all ancestors; instead
/// this is updated on each step.
struct TraversalState {
/// The highest artifact ancestor in the tree.
current_artifact: Option<(GroupId, ArtifactType)>,
/// The stack of ancestors that have a [`GroupKind::bbox`].
bbox_stack: Vec<BBoxId>,
/// The stack of text attributes.
text_attrs: TextAttrs,
}
impl TraversalState {
fn new() -> Self {
Self {
current_artifact: None,
bbox_stack: Vec::new(),
text_attrs: TextAttrs::new(),
}
}
/// Update the traversal state when moving out of a group.
fn pop_group(&mut self, surface: &mut Surface, id: GroupId, group: &Group) {
if self.current_artifact.take_if(|(i, _)| *i == id).is_some() {
surface.end_tagged();
}
if let Some(id) = group.kind.bbox() {
self.bbox_stack.pop_if(|i| *i == id);
}
self.text_attrs.pop(id);
}
}
/// Marks a point where the entries on the stack were split up.
#[derive(Debug, Copy, Clone)]
struct Break {
/// The index of the progression at which point the broken up groups need to
/// be closed.
prog_idx: u32,
/// The number of groups which have to be closed, from the previous
/// group upwards in the parent hierarchy.
num_closed: u16,
/// The number of groups which have to be closed, from the next group
/// upwards in the parent hierarchy.
num_opened: u16,
}
/// Marks a point at the end of a logical child or parent where the stack was
/// not fully closed, and the open groups were handled in the next logical
/// child.
#[derive(Debug, Copy, Clone)]
struct Unfinished {
/// The index of the progression at which point the broken up groups need to
/// be closed.
prog_idx: u32,
group_to_close: GroupId,
}
pub fn step_start_tag(tree: &mut Tree, surface: &mut Surface) {
let Some((prev, next)) = step(tree) else { return };
if let Some(brk) = consume_break(tree) {
step_break(tree, surface, prev, next, brk);
} else {
open_group(&tree.groups, &mut tree.state, surface, next);
}
}
pub fn step_end_tag(tree: &mut Tree, surface: &mut Surface) {
let Some((prev, next)) = step(tree) else { return };
if let Some(brk) = consume_break(tree) {
step_break(tree, surface, prev, next, brk);
} else {
close_group(tree, surface, prev);
}
}
/// This can move to a completely different position in the tree.
pub fn enter_logical_child(tree: &mut Tree, surface: &mut Surface) {
let Some((_, next)) = step(tree) else { return };
// Close any artifact in the previous location.
if tree.parent_artifact().is_some() {
surface.end_tagged();
}
// Compute the traversal state for the new location in the tree and push it.
let mut new_state = TraversalState::new();
let mut current = next;
let rev_iter = std::iter::from_fn(|| {
if current == GroupId::INVALID {
return None;
}
let id = current;
let group = tree.groups.get(id);
current = group.parent;
Some((id, group))
});
open_multiple_groups(&mut new_state, surface, rev_iter);
tree.state.push(new_state);
}
/// This moves back to the previous location in the tree.
pub fn leave_logical_child(tree: &mut Tree, surface: &mut Surface) {
let Some((prev, _)) = step(tree) else { return };
// The stack within a logical child, could also be unfinished, in
// which case a `BreakKind::Unfinished` is inserted to close the
// `LogicalChild` group.
if let Some(unfinished) = consume_unfinished(tree) {
close_group(tree, surface, unfinished.group_to_close);
} else {
close_group(tree, surface, prev);
}
// Close any artifact in the logical child.
if tree.parent_artifact().is_some() {
surface.end_tagged();
}
tree.state.pop();
// Reopen any artifact in the restored location of the tree.
if let Some(ty) = tree.parent_artifact() {
surface.start_tagged(ContentTag::Artifact(ty));
}
}
fn step(tree: &mut Tree) -> Option<(GroupId, GroupId)> {
let prev = tree.current();
tree.prog_cursor += 1;
let next = tree.current();
// We didn't move into a new group, no actions are necessary.
if prev == next {
return None;
}
Some((prev, next))
}
fn consume_break(tree: &mut Tree) -> Option<Break> {
let brk = *tree.breaks.get(tree.break_cursor)?;
if brk.prog_idx as usize == tree.prog_cursor {
tree.break_cursor += 1;
return Some(brk);
}
None
}
fn consume_unfinished(tree: &mut Tree) -> Option<Unfinished> {
let unfinished = *tree.unfinished.get(tree.unfinished_cursor)?;
if unfinished.prog_idx as usize == tree.prog_cursor {
tree.unfinished_cursor += 1;
return Some(unfinished);
}
None
}
fn step_break(
tree: &mut Tree,
surface: &mut Surface,
prev: GroupId,
next: GroupId,
brk: Break,
) {
// Close groups.
let mut current = prev;
for _ in 0..brk.num_closed {
current = close_group(tree, surface, current);
}
// Open groups.
let mut current = next;
let rev_iter = std::iter::from_fn(|| {
let id = current;
let group = tree.groups.get(id);
current = group.parent;
Some((id, group))
});
open_multiple_groups(
&mut tree.state,
surface,
rev_iter.take(brk.num_opened as usize),
);
}
fn open_group(
groups: &Groups,
state: &mut TraversalState,
surface: &mut Surface,
id: GroupId,
) {
let group = groups.get(id);
if state.current_artifact.is_none()
&& let Some(ty) = group.kind.as_artifact()
{
state.current_artifact = Some((id, ty));
surface.start_tagged(ContentTag::Artifact(ty));
}
if let Some(bbox) = &group.kind.bbox() {
state.bbox_stack.push(*bbox);
}
if let GroupKind::TextAttr(attr) = &group.kind {
state.text_attrs.push(id, attr.clone());
}
}
/// Since the groups need to be opened in order, but we can only iterate the
/// parent hierarchy from bottom to top, this cannot simply call [`open_group`].
fn open_multiple_groups<'a>(
state: &mut TraversalState,
surface: &mut Surface,
rev_iter: impl Iterator<Item = (GroupId, &'a Group)>,
) {
let mut new_artifact = None;
let bbox_start = state.bbox_stack.len();
let text_attr_start = state.text_attrs.len();
for (id, group) in rev_iter {
if let Some(ty) = group.kind.as_artifact() {
new_artifact = Some((id, ty));
}
if let Some(bbox) = group.kind.bbox() {
state.bbox_stack.insert(bbox_start, bbox);
}
if let GroupKind::TextAttr(attr) = &group.kind {
state.text_attrs.insert(text_attr_start, id, attr.clone());
}
}
if state.current_artifact.is_none()
&& let Some((_, ty)) = new_artifact
{
state.current_artifact = new_artifact;
surface.start_tagged(ContentTag::Artifact(ty));
}
}
fn close_group(tree: &mut Tree, surface: &mut Surface, id: GroupId) -> GroupId {
let group = tree.groups.get(id);
let direct_parent = group.parent;
let semantic_parent = semantic_parent(tree, direct_parent);
tree.state.pop_group(surface, id, group);
match &group.kind {
GroupKind::Root(_) => unreachable!(),
GroupKind::Artifact(_) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::LogicalParent(elem) => {
let loc = elem.location().unwrap();
// Insert logical children when closing the logical parent, so they
// are at the end of the group. In some cases there might be
// multiple parent groups with the same location, only insert the
// children for the first parent group.
if let Some(located) = tree.groups.by_loc(&loc)
&& located.id == id
&& let Some(children) = tree.logical_children.get(&loc)
{
tree.groups.push_groups(id, children);
}
tree.groups.push_group(direct_parent, id);
}
GroupKind::LogicalChild(inherit, logical_parent) => {
if *inherit == Inherit::No {
// If this logical child doesn't inherit its parent's styles and
// is not inside of an artifact, inserting it into a parent that
// is inside of an artifact would mean the content will be
// discarded. If that's the case, ignore the logical parent
// structure and insert it wherever it appeared in the frame
// tree.
let logical_parent_is_in_artifact = 'artifact: {
let mut current = tree.groups.get(*logical_parent).parent;
while current != GroupId::INVALID {
let group = tree.groups.get(current);
if group.kind.is_artifact() {
break 'artifact true;
}
current = group.parent;
}
false
};
if tree.parent_artifact().is_none() && logical_parent_is_in_artifact {
tree.groups.push_group(direct_parent, id);
}
} else if !matches!(
tree.groups.get(direct_parent).kind,
GroupKind::LogicalParent(_)
) {
// `GroupKind::LogicalParent` handles inserting of children at its
// end, see above. Children of table/grid cells are always ordered
// correctly and are treated a little bit differently.
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::Outline(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::OutlineEntry(entry, _) => {
if let GroupKind::Outline(outline, _) = tree.groups.get(semantic_parent).kind
{
let outline_ctx = tree.ctx.outlines.get_mut(outline);
let entry = entry.clone();
tree.groups.get_mut(id).parent = semantic_parent;
outline_ctx.insert(&mut tree.groups, semantic_parent, entry, id);
} else {
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::Table(..) => {
tree.groups.push_group(direct_parent, id);
}
&GroupKind::TableCell(ref cell, tag, _) => {
let cell = cell.clone();
if let Some(table) = move_into(tree, semantic_parent, id, GroupKind::as_table)
{
let table_ctx = tree.ctx.tables.get_mut(table);
table_ctx.insert(&cell, tag, id);
} else {
// Avoid panicking, the nesting will be validated later.
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::Grid(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::GridCell(cell, _) => {
let cell = cell.clone();
if let Some(grid) = move_into(tree, semantic_parent, id, GroupKind::as_grid) {
let grid_ctx = tree.ctx.grids.get_mut(grid);
grid_ctx.insert(&cell, id);
} else {
// Avoid panicking, the nesting will be validated later.
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::List(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::ListItemLabel(..) => {
if let Some(list) = move_into(tree, semantic_parent, id, GroupKind::as_list) {
let list_ctx = tree.ctx.lists.get_mut(list);
list_ctx.push_label(&mut tree.groups, semantic_parent, id);
} else {
// Avoid panicking, the nesting will be validated later.
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::ListItemBody(..) => {
if let Some(list) = move_into(tree, semantic_parent, id, GroupKind::as_list) {
let list_ctx = tree.ctx.lists.get_mut(list);
list_ctx.push_body(&mut tree.groups, semantic_parent, id);
} else {
// Avoid panicking, the nesting will be validated later.
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::TermsItemLabel(..) => {
if let GroupKind::TermsItemBody(lbl, _) =
&mut tree.groups.get_mut(semantic_parent).kind
{
*lbl = Some(id);
} else {
// Avoid panicking, the nesting will be validated later.
tree.groups.push_group(direct_parent, id);
}
}
&GroupKind::TermsItemBody(lbl, ..) => {
if let Some(list) = move_into(tree, semantic_parent, id, GroupKind::as_list) {
let list_ctx = tree.ctx.lists.get_mut(list);
if let Some(lbl) = lbl {
tree.groups.get_mut(lbl).parent = semantic_parent;
list_ctx.push_label(&mut tree.groups, semantic_parent, lbl);
}
list_ctx.push_body(&mut tree.groups, semantic_parent, id);
} else {
// Avoid panicking, the nesting will be validated later.
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::BibEntry(..) => {
if let Some(list) = move_into(tree, semantic_parent, id, GroupKind::as_list) {
let list_ctx = tree.ctx.lists.get_mut(list);
list_ctx.push_bib_entry(&mut tree.groups, semantic_parent, id);
} else {
// Avoid panicking, the nesting will be validated later.
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::FigureWrapper(..) => unreachable!("only generated below"),
GroupKind::Figure(figure, ..) => {
// Insert the wrapper.
let kind = GroupKind::FigureWrapper(*figure);
let wrapper = tree.groups.new_virtual(direct_parent, group.span, kind);
tree.groups.push_group(direct_parent, wrapper);
// Push the figure into the wrapper.
tree.groups.get_mut(id).parent = wrapper;
tree.groups.push_group(wrapper, id);
}
GroupKind::FigureCaption(..) => {
if let GroupKind::Figure(figure, ..) = tree.groups.get(semantic_parent).kind {
let figure_ctx = tree.ctx.figures.get_mut(figure);
figure_ctx.captions.push(id);
} else {
tree.groups.push_group(direct_parent, id);
}
}
GroupKind::Image(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::Formula(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::Link(..) => {
// Wrap link in reference tag if inside an outline entry.
let mut parent = direct_parent;
if let GroupKind::OutlineEntry(..) = tree.groups.get(direct_parent).kind {
parent = tree.groups.push_tag(parent, Tag::Reference);
}
tree.groups.push_group(parent, id);
}
GroupKind::CodeBlock(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::CodeBlockLine(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::Par(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::TextAttr(..) => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::Transparent => {
tree.groups.push_group(direct_parent, id);
}
GroupKind::Standard(..) => {
tree.groups.push_group(direct_parent, id);
}
};
direct_parent
}
fn move_into<T>(
tree: &mut Tree,
semantic_parent: GroupId,
child: GroupId,
f: impl FnOnce(&GroupKind) -> Option<T>,
) -> Option<T> {
let res = f(&tree.groups.get(semantic_parent).kind);
if res.is_some() {
tree.groups.get_mut(child).parent = semantic_parent;
}
res
}
fn semantic_parent(tree: &Tree, direct_parent: GroupId) -> GroupId {
let mut parent = direct_parent;
loop {
let group = tree.groups.get(parent);
if group.kind.is_semantic() {
return parent;
}
parent = group.parent;
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/context/list.rs | crates/typst-pdf/src/tags/context/list.rs | use krilla::tagging::Tag;
use crate::tags::groups::{GroupId, GroupKind, Groups};
use crate::tags::resolve::TagNode;
#[derive(Debug, Clone)]
pub struct ListCtx {
last_item: Option<ListItem>,
}
#[derive(Debug, Clone)]
struct ListItem {
/// The id of the `LI` tag.
id: GroupId,
}
impl ListCtx {
pub fn new() -> Self {
Self { last_item: None }
}
pub fn push_label(&mut self, groups: &mut Groups, list: GroupId, label: GroupId) {
if let Some(item) = self.last_item.take() {
groups.push_tag(item.id, Tag::LBody);
}
let parent = groups.push_tag(list, Tag::LI);
groups.push_group(parent, label);
self.last_item = Some(ListItem { id: parent });
}
fn ensure_within_item(&mut self, groups: &mut Groups, list: GroupId) -> GroupId {
if let Some(item) = self.last_item.take() {
item.id
} else {
let item = groups.push_tag(list, Tag::LI);
groups.push_tag(item, Tag::Lbl);
item
}
}
pub fn push_body(&mut self, groups: &mut Groups, list: GroupId, body: GroupId) {
let item = self.ensure_within_item(groups, list);
groups.push_group(item, body);
// Nested lists are expected to have the following structure:
//
// Typst code
// ```
// - a
// - b
// - c
// - d
// - e
// ```
//
// Structure tree
// ```
// <L>
// <LI>
// <Lbl> `-`
// <LBody> `a`
// <LI>
// <Lbl> `-`
// <LBody> `b`
// <L>
// <LI>
// <Lbl> `-`
// <LBody> `c`
// <LI>
// <Lbl> `-`
// <LBody> `d`
// <LI>
// <Lbl> `-`
// <LBody> `d`
// ```
//
// So move the nested list out of the list item.
if let &[.., TagNode::Group(id)] = groups.get(body).nodes()
&& let GroupKind::List(..) = groups.get_mut(id).kind
{
groups.get_mut(body).pop_node();
groups.get_mut(id).parent = list;
groups.push_group(list, id);
}
}
pub fn push_bib_entry(
&mut self,
groups: &mut Groups,
list: GroupId,
bib_entry: GroupId,
) {
// Bibliography lists are always flat, so there is no need to check for
// an inner list. If they do contain a list it is semantically unrelated
// and can be left within the list body.
let item = self.ensure_within_item(groups, list);
let body = groups.push_tag(item, Tag::LBody);
groups.push_group(body, bib_entry);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/context/table.rs | crates/typst-pdf/src/tags/context/table.rs | use std::io::Write as _;
use std::num::NonZeroU32;
use std::ops::Range;
use std::sync::Arc;
use az::SaturatingAs;
use krilla::tagging as kt;
use krilla::tagging::{NaiveRgbColor, Tag, TagKind};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use typst_library::foundations::Packed;
use typst_library::layout::resolve::{CellGrid, Line, LinePosition};
use typst_library::layout::{Abs, Sides};
use typst_library::model::{TableCell, TableElem};
use typst_library::pdf::{TableCellKind, TableHeaderScope};
use typst_library::visualize::{FixedStroke, Stroke};
use crate::tags::GroupId;
use crate::tags::context::grid::{CtxCell, GridCells, GridEntry, GridExt};
use crate::tags::context::{TableId, TagId};
use crate::tags::tree::Tree;
use crate::tags::util::{self, PropertyOptRef, PropertyValCopied, TableHeaderScopeExt};
use crate::util::{AbsExt, SidesExt};
#[derive(Debug)]
pub struct TableCtx {
pub group_id: GroupId,
pub table_id: TableId,
pub elem: Packed<TableElem>,
row_kinds: Vec<TableCellKind>,
cells: GridCells<TableCellData>,
border_thickness: Option<f32>,
border_color: Option<NaiveRgbColor>,
}
#[derive(Debug, Clone)]
pub struct TableCellData {
tag: TagId,
kind: TableCellKind,
headers: SmallVec<[kt::TagId; 1]>,
stroke: Sides<PrioritzedStroke>,
}
#[derive(Debug, Clone, Eq, PartialEq)]
struct PrioritzedStroke {
stroke: Option<Arc<Stroke<Abs>>>,
priority: StrokePriority,
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum StrokePriority {
GridStroke = 0,
CellStroke = 1,
ExplicitLine = 2,
}
impl TableCtx {
pub fn new(group_id: GroupId, table_id: TableId, table: Packed<TableElem>) -> Self {
let grid = table.grid.as_ref().unwrap();
let width = grid.non_gutter_column_count();
let height = grid.non_gutter_row_count();
// Generate the default row kinds.
let mut grid_headers = grid.headers.iter().peekable();
let default_row_kinds = (0..height as u32)
.map(|y| {
let grid_y = grid.to_effective(y);
// Find current header
while grid_headers.next_if(|h| h.range.end <= grid_y).is_some() {}
if let Some(header) = grid_headers.peek()
&& header.range.contains(&grid_y)
{
return TableCellKind::Header(header.level, TableHeaderScope::Column);
}
if let Some(footer) = &grid.footer
&& footer.range().contains(&grid_y)
{
return TableCellKind::Footer;
}
TableCellKind::Data
})
.collect::<Vec<_>>();
Self {
group_id,
table_id,
elem: table,
row_kinds: default_row_kinds,
cells: GridCells::new(width, height),
border_thickness: None,
border_color: None,
}
}
pub fn insert(&mut self, cell: &Packed<TableCell>, tag: TagId, id: GroupId) {
let x = cell.x.val().unwrap_or_else(|| unreachable!()).saturating_as();
let y = cell.y.val().unwrap_or_else(|| unreachable!()).saturating_as();
let rowspan = cell.rowspan.val();
let colspan = cell.colspan.val();
let grid = self.elem.grid.as_deref().unwrap();
let kind = cell.kind.val().unwrap_or(self.row_kinds[y as usize]);
let [grid_x, grid_y] = [x, y].map(|i| grid.to_effective(i));
let grid_cell = grid.cell(grid_x, grid_y).unwrap();
let stroke = grid_cell.stroke.clone().zip(grid_cell.stroke_overridden).map(
|(stroke, overridden)| {
let priority = if overridden {
StrokePriority::CellStroke
} else {
StrokePriority::GridStroke
};
PrioritzedStroke { stroke, priority }
},
);
self.cells.insert(CtxCell {
data: TableCellData { tag, kind, headers: SmallVec::new(), stroke },
x,
y,
rowspan: rowspan.try_into().unwrap_or(NonZeroU32::MAX),
colspan: colspan.try_into().unwrap_or(NonZeroU32::MAX),
id,
});
}
pub fn build_tag(&self) -> TagKind {
Tag::Table
.with_summary(self.elem.summary.opt_ref().map(Into::into))
.with_border_thickness(self.border_thickness.map(kt::Sides::uniform))
.with_border_color(self.border_color.map(kt::Sides::uniform))
.into()
}
}
pub fn build_table(tree: &mut Tree, table_id: TableId) {
let table_ctx = tree.ctx.tables.get_mut(table_id);
// Table layouting ensures that there are no overlapping cells, and that
// any gaps left by the user are filled with empty cells.
// A show rule, can prevent the table from being properly laid out, in which
// case cells will be missing.
if table_ctx.cells.is_empty() || table_ctx.cells.iter().any(GridEntry::is_missing) {
// Insert all children, so the content is included in the tag tree,
// otherwise krilla might panic.
for cell in table_ctx.cells.iter().filter_map(GridEntry::as_cell) {
tree.groups.push_group(table_ctx.group_id, cell.id);
}
return;
}
let width = table_ctx.cells.width();
let height = table_ctx.cells.height();
let grid = table_ctx.elem.grid.as_deref().unwrap();
// Only generate row groups such as `THead`, `TFoot`, and `TBody` if
// there are no rows with mixed cell kinds, and there is at least one
// header or a footer.
let gen_row_groups = {
let mut uniform_rows = true;
let mut has_header_or_footer = false;
let mut has_body = false;
'outer: for (row, row_kind) in
table_ctx.cells.rows().zip(table_ctx.row_kinds.iter_mut())
{
let first_cell = table_ctx.cells.resolve(row.first().unwrap()).unwrap();
let first_kind = first_cell.data.kind;
for cell in row.iter().filter_map(|cell| table_ctx.cells.resolve(cell)) {
if let TableCellKind::Header(_, scope) = cell.data.kind
&& scope != TableHeaderScope::Column
{
uniform_rows = false;
break 'outer;
}
if first_kind != cell.data.kind {
uniform_rows = false;
break 'outer;
}
}
// If all cells in the row have the same custom kind, the row
// kind is overwritten.
*row_kind = first_kind;
has_header_or_footer |= *row_kind != TableCellKind::Data;
has_body |= *row_kind == TableCellKind::Data;
}
uniform_rows && has_header_or_footer && has_body
};
// Compute the headers attribute column-wise.
for x in 0..width {
let mut column_headers = Vec::new();
let mut grid_headers = grid.headers.iter().peekable();
for y in 0..height {
// Find current header region
let grid_y = grid.to_effective(y);
while grid_headers.next_if(|h| h.range.end <= grid_y).is_some() {}
let region_range = grid_headers.peek().and_then(|header| {
if !header.range.contains(&grid_y) {
return None;
}
// Convert from the `CellGrid` coordinates to normal ones.
let start = grid.from_effective(header.range.start);
let end = grid.from_effective(header.range.end);
Some(start..end)
});
resolve_cell_headers(
table_ctx.table_id,
&mut table_ctx.cells,
&mut column_headers,
region_range,
TableHeaderScope::refers_to_column,
(x, y),
);
}
}
// Compute the headers attribute row-wise.
for y in 0..height {
let mut row_headers = Vec::new();
for x in 0..width {
resolve_cell_headers(
table_ctx.table_id,
&mut table_ctx.cells,
&mut row_headers,
None,
TableHeaderScope::refers_to_row,
(x, y),
);
}
}
// Place h-lines, overwriting the cells stroke.
place_explicit_lines(
&mut table_ctx.cells,
&grid.hlines,
height,
width,
|cells, (y, x), pos| {
let cell = cells.cell_mut(x, y)?;
Some(match pos {
LinePosition::Before => &mut cell.data.stroke.bottom,
LinePosition::After => &mut cell.data.stroke.top,
})
},
);
// Place v-lines, overwriting the cells stroke.
place_explicit_lines(
&mut table_ctx.cells,
&grid.vlines,
width,
height,
|cells, (x, y), pos| {
let cell = cells.cell_mut(x, y)?;
Some(match pos {
LinePosition::Before => &mut cell.data.stroke.right,
LinePosition::After => &mut cell.data.stroke.left,
})
},
);
// Remove overlapping border strokes between cells.
for y in 0..height {
for x in 0..width.saturating_sub(1) {
prioritize_strokes(&mut table_ctx.cells, (x, y), (x + 1, y), |a, b| {
(&mut a.stroke.right, &mut b.stroke.left)
});
}
}
for x in 0..width {
for y in 0..height.saturating_sub(1) {
prioritize_strokes(&mut table_ctx.cells, (x, y), (x, y + 1), |a, b| {
(&mut a.stroke.bottom, &mut b.stroke.top)
});
}
}
(table_ctx.border_thickness, table_ctx.border_color) =
try_resolve_table_stroke(&table_ctx.cells);
let mut chunk_kind = table_ctx.row_kinds[0];
let mut chunk_id = GroupId::INVALID;
for (row, y) in table_ctx.cells.rows_mut().zip(0..) {
let parent = if gen_row_groups {
let row_kind = table_ctx.row_kinds[y as usize];
let is_first = chunk_id == GroupId::INVALID;
if is_first || !should_group_rows(chunk_kind, row_kind) {
let tag: TagKind = match row_kind {
// Only one `THead` group at the start of the table is permitted.
TableCellKind::Header(..) if is_first => Tag::THead.into(),
TableCellKind::Header(..) => Tag::TBody.into(),
TableCellKind::Footer => Tag::TFoot.into(),
TableCellKind::Data => Tag::TBody.into(),
};
chunk_kind = row_kind;
chunk_id = tree.groups.push_tag(table_ctx.group_id, tag);
}
chunk_id
} else {
table_ctx.group_id
};
let row_id = tree.groups.push_tag(parent, Tag::TR);
let row_nodes = row
.iter_mut()
.filter_map(|entry| {
let cell = entry.as_cell_mut()?;
let rowspan = (cell.rowspan.get() != 1).then_some(cell.rowspan);
let colspan = (cell.colspan.get() != 1).then_some(cell.colspan);
let cell_kind = cell.data.kind;
let headers = std::mem::take(&mut cell.data.headers);
let mut tag: TagKind = match cell_kind {
TableCellKind::Header(_, scope) => {
let id = table_cell_id(table_ctx.table_id, cell.x, cell.y);
Tag::TH(scope.to_krilla())
.with_id(Some(id))
.with_headers(Some(headers))
.with_row_span(rowspan)
.with_col_span(colspan)
.into()
}
TableCellKind::Footer | TableCellKind::Data => Tag::TD
.with_headers(Some(headers))
.with_row_span(rowspan)
.with_col_span(colspan)
.into(),
};
resolve_cell_border_and_background(
grid,
table_ctx.border_thickness,
table_ctx.border_color,
[cell.x, cell.y],
&cell.data.stroke,
&mut tag,
);
tree.groups.tags.set(cell.data.tag, tag);
Some(cell.id)
})
.collect::<Vec<_>>();
tree.groups.push_groups(row_id, &row_nodes);
}
}
fn should_group_rows(a: TableCellKind, b: TableCellKind) -> bool {
match (a, b) {
(TableCellKind::Header(..), TableCellKind::Header(..)) => true,
(TableCellKind::Footer, TableCellKind::Footer) => true,
(TableCellKind::Data, TableCellKind::Data) => true,
(_, _) => false,
}
}
struct HeaderCells {
/// If this header is inside a table header regions defined by a
/// `table.header()` call, this is the range of that region.
/// Currently this is only supported for multi row headers.
region_range: Option<Range<u32>>,
level: NonZeroU32,
cell_ids: SmallVec<[kt::TagId; 1]>,
}
fn resolve_cell_headers<F>(
table_id: TableId,
cells: &mut GridCells<TableCellData>,
header_stack: &mut Vec<HeaderCells>,
region_range: Option<Range<u32>>,
refers_to_dir: F,
(x, y): (u32, u32),
) where
F: Fn(&TableHeaderScope) -> bool,
{
let Some(cell) = cells.cell_mut(x, y) else { return };
let cell_ids = resolve_cell_header_ids(
table_id,
header_stack,
region_range,
refers_to_dir,
cell,
);
if let Some(header) = cell_ids {
for id in header.cell_ids.iter() {
if !cell.data.headers.contains(id) {
cell.data.headers.push(id.clone());
}
}
}
}
fn resolve_cell_header_ids<'a, F>(
table_id: TableId,
header_stack: &'a mut Vec<HeaderCells>,
region_range: Option<Range<u32>>,
refers_to_dir: F,
cell: &CtxCell<TableCellData>,
) -> Option<&'a HeaderCells>
where
F: Fn(&TableHeaderScope) -> bool,
{
let TableCellKind::Header(level, scope) = cell.data.kind else {
return header_stack.last();
};
if !refers_to_dir(&scope) {
return header_stack.last();
}
// Remove all headers with a higher level.
while header_stack.pop_if(|h| h.level > level).is_some() {}
let tag_id = table_cell_id(table_id, cell.x, cell.y);
// Check for multi-row header regions with the same level.
let Some(prev) = header_stack.last_mut().filter(|h| h.level == level) else {
header_stack.push(HeaderCells {
region_range,
level,
cell_ids: SmallVec::from_buf([tag_id]),
});
return header_stack.iter().rev().nth(1);
};
// If the current header region encompasses the cell, add the cell id to
// the header. This way multiple consecutive header cells in a single header
// region will be listed for the next cells.
if prev.region_range.clone().is_some_and(|r| r.contains(&cell.y)) {
prev.cell_ids.push(tag_id);
} else {
// The current region doesn't encompass the cell.
// Replace the previous heading that had the same level.
*prev = HeaderCells {
region_range,
level,
cell_ids: SmallVec::from_buf([tag_id]),
};
}
header_stack.iter().rev().nth(1)
}
fn table_cell_id(table_id: TableId, x: u32, y: u32) -> kt::TagId {
// 32 bytes is the maximum length the ID string can have.
let mut buf = SmallVec::<[u8; 32]>::new();
_ = write!(&mut buf, "{}x{x}y{y}", table_id.get() + 1);
kt::TagId::from(buf)
}
fn place_explicit_lines<F>(
cells: &mut GridCells<TableCellData>,
lines: &[Vec<Line>],
block_end: u32,
inline_end: u32,
get_side: F,
) where
F: Fn(
&mut GridCells<TableCellData>,
(u32, u32),
LinePosition,
) -> Option<&mut PrioritzedStroke>,
{
for line in lines.iter().flat_map(|lines| lines.iter()) {
let end = line.end.map(|n| n.get() as u32).unwrap_or(inline_end).min(inline_end);
let explicit_stroke = || PrioritzedStroke {
stroke: line.stroke.clone(),
priority: StrokePriority::ExplicitLine,
};
// Fixup line positions before the first, or after the last cell.
let mut pos = line.position;
if line.index == 0 {
pos = LinePosition::After;
} else if line.index + 1 == block_end as usize {
pos = LinePosition::Before;
};
let block_idx = match pos {
LinePosition::Before => (line.index - 1) as u32,
LinePosition::After => line.index as u32,
};
for inline_idx in line.start as u32..end {
if let Some(side) = get_side(cells, (block_idx, inline_idx), pos) {
*side = explicit_stroke();
}
}
}
}
/// PDF tables don't support gutters, remove all overlapping strokes,
/// that aren't equal. Leave strokes that would overlap but are the same
/// because then only a single value has to be written for `BorderStyle`,
/// `BorderThickness`, and `BorderColor` instead of an array for each.
fn prioritize_strokes<F>(
cells: &mut GridCells<TableCellData>,
a: (u32, u32),
b: (u32, u32),
get_sides: F,
) where
F: for<'a> Fn(
&'a mut TableCellData,
&'a mut TableCellData,
) -> (&'a mut PrioritzedStroke, &'a mut PrioritzedStroke),
{
let Some([a, b]) = cells.cells_disjoint_mut([a, b]) else { return };
let (a, b) = get_sides(&mut a.data, &mut b.data);
// Only remove contesting (different) edge strokes.
if a.stroke != b.stroke {
// Prefer the right stroke on same priorities.
if a.priority <= b.priority {
a.stroke = b.stroke.clone();
} else {
b.stroke = a.stroke.clone();
}
}
}
/// Try to resolve a table border stroke color and thickness that is inherited
/// by the cells. In Acrobat cells cannot override the border thickness or color
/// of the outer border around the table if the thickness is set.
fn try_resolve_table_stroke(
cells: &GridCells<TableCellData>,
) -> (Option<f32>, Option<NaiveRgbColor>) {
// Omitted strokes are counted too for reasons explained above.
let mut strokes = FxHashMap::<_, usize>::default();
for cell in cells.iter().filter_map(GridEntry::as_cell) {
for stroke in cell.data.stroke.iter() {
*strokes.entry(stroke.stroke.as_ref()).or_default() += 1;
}
}
let uniform_stroke = strokes.len() == 1;
// Find the most used stroke and convert it to a fixed stroke.
let stroke = strokes.into_iter().max_by_key(|(_, num)| *num).and_then(|(s, _)| {
let s = (**s?).clone();
Some(s.unwrap_or_default())
});
let Some(stroke) = stroke else { return (None, None) };
// Only set a parent stroke width if the table uses one uniform stroke.
let thickness = uniform_stroke.then_some(stroke.thickness.to_f32());
let color = util::paint_to_color(&stroke.paint);
(thickness, color)
}
fn resolve_cell_border_and_background(
grid: &CellGrid,
parent_border_thickness: Option<f32>,
parent_border_color: Option<NaiveRgbColor>,
pos: [u32; 2],
stroke: &Sides<PrioritzedStroke>,
tag: &mut TagKind,
) {
// Resolve border attributes.
let fixed = stroke
.as_ref()
.map(|s| s.stroke.as_ref().map(|s| (**s).clone().unwrap_or_default()));
// Acrobat completely ignores the border style attribute, but the spec
// defines `BorderStyle::None` as the default. So make sure to write
// the correct border styles.
let border_style = resolve_sides(&fixed, None, Some(kt::BorderStyle::None), |s| {
s.map(|s| match s.dash {
Some(_) => kt::BorderStyle::Dashed,
None => kt::BorderStyle::Solid,
})
});
// In Acrobat `BorderThickness` takes precedence over `BorderStyle`. If
// A `BorderThickness != 0` is specified for a side the border is drawn
// even if `BorderStyle::None` is set. So explicitly write zeros for
// sides that should be omitted.
let border_thickness =
resolve_sides(&fixed, parent_border_thickness, Some(0.0), |s| {
s.map(|s| s.thickness.to_f32())
});
let border_color = resolve_sides(&fixed, parent_border_color, None, |s| {
s.and_then(|s| util::paint_to_color(&s.paint))
});
tag.set_border_style(border_style);
tag.set_border_thickness(border_thickness);
tag.set_border_color(border_color);
let [grid_x, grid_y] = pos.map(|i| grid.to_effective(i));
let grid_cell = grid.cell(grid_x, grid_y).unwrap();
let background_color = grid_cell.fill.as_ref().and_then(util::paint_to_color);
tag.set_background_color(background_color);
}
/// Try to minimize the attributes written per cell.
/// The parent value will be set on the table tag and is inherited by all table
/// cells. If all present values match the parent or all are missing, the
/// attribute can be omitted, and thus `None` is returned.
/// If one of the present values differs from the parent value, the the cell
/// attribute needs to override the parent attribute, fill up the remaining
/// sides with a `default` value if provided, or any other present value.
///
/// Using an already present value has the benefit of saving storage space in
/// the resulting PDF, if all sides have the same value, because then a
/// [kt::Sides::uniform] value can be written instead of an 4-element array.
fn resolve_sides<F, T>(
sides: &Sides<Option<FixedStroke>>,
parent: Option<T>,
default: Option<T>,
map: F,
) -> Option<kt::Sides<T>>
where
T: Copy + PartialEq,
F: Copy + Fn(Option<&FixedStroke>) -> Option<T>,
{
let mapped = sides.as_ref().map(|s| map(s.as_ref()));
if mapped.iter().flatten().all(|v| Some(*v) == parent) {
// All present values are equal to the parent value.
return None;
}
let Some(first) = mapped.iter().flatten().next() else {
// All values are missing
return None;
};
// At least one value is different from the parent, fill up the remaining
// sides with a replacement value.
let replacement = default.unwrap_or(*first);
let sides = mapped.unwrap_or(replacement);
// TODO(accessibility): handle `text(dir: rtl)`
Some(sides.to_lrtb_krilla())
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/context/grid.rs | crates/typst-pdf/src/tags/context/grid.rs | use std::num::NonZeroU32;
use az::SaturatingAs;
use typst_library::foundations::Packed;
use typst_library::layout::resolve::CellGrid;
use typst_library::layout::{GridCell, GridElem};
use crate::tags::context::GridId;
use crate::tags::groups::GroupId;
use crate::tags::tree::Tree;
use crate::tags::util::PropertyValCopied;
pub(super) trait GridExt {
/// Convert from "effective" positions inside the cell grid, which may
/// include gutter tracks in addition to the cells, to conventional
/// positions.
#[allow(clippy::wrong_self_convention)]
fn from_effective(&self, i: usize) -> u32;
/// Convert from conventional positions to "effective" positions inside the
/// cell grid, which may include gutter tracks in addition to the cells.
fn to_effective(&self, i: u32) -> usize;
}
impl GridExt for CellGrid {
fn from_effective(&self, i: usize) -> u32 {
if self.has_gutter { (i / 2) as u32 } else { i as u32 }
}
fn to_effective(&self, i: u32) -> usize {
if self.has_gutter { 2 * i as usize } else { i as usize }
}
}
#[derive(Debug)]
pub struct GridCtx {
group_id: GroupId,
cells: GridCells<()>,
}
impl GridCtx {
pub fn new(group_id: GroupId, grid: &Packed<GridElem>) -> Self {
let grid = grid.grid.as_ref().unwrap();
let width = grid.non_gutter_column_count();
let height = grid.non_gutter_row_count();
Self { group_id, cells: GridCells::new(width, height) }
}
pub fn insert(&mut self, cell: &Packed<GridCell>, id: GroupId) {
let x = cell.x.val().unwrap_or_else(|| unreachable!());
let y = cell.y.val().unwrap_or_else(|| unreachable!());
let rowspan = cell.rowspan.val();
let colspan = cell.colspan.val();
self.cells.insert(CtxCell {
data: (),
x: x.saturating_as(),
y: y.saturating_as(),
rowspan: rowspan.try_into().unwrap_or(NonZeroU32::MAX),
colspan: colspan.try_into().unwrap_or(NonZeroU32::MAX),
id,
});
}
}
pub fn build_grid(tree: &mut Tree, grid_id: GridId) {
let grid_ctx = tree.ctx.grids.get_mut(grid_id);
for cell in grid_ctx.cells.entries.iter().filter_map(GridEntry::as_cell) {
tree.groups.push_group(grid_ctx.group_id, cell.id);
}
}
#[derive(Debug, Clone)]
pub(super) struct GridCells<T> {
width: usize,
entries: Vec<GridEntry<T>>,
}
impl<T: Clone> GridCells<T> {
pub fn new(width: usize, height: usize) -> Self {
Self {
width,
entries: vec![GridEntry::Missing; width * height],
}
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn width(&self) -> u32 {
self.width as u32
}
pub fn height(&self) -> u32 {
(self.entries.len() / self.width) as u32
}
pub fn iter(&self) -> impl Iterator<Item = &GridEntry<T>> {
self.entries.iter()
}
pub fn rows(&self) -> impl Iterator<Item = &[GridEntry<T>]> {
self.entries.chunks(self.width)
}
pub fn rows_mut(&mut self) -> impl Iterator<Item = &mut [GridEntry<T>]> {
self.entries.chunks_mut(self.width)
}
pub fn cell_mut(&mut self, x: u32, y: u32) -> Option<&mut CtxCell<T>> {
let idx = self.cell_idx(x, y);
let cell = &mut self.entries[idx];
match cell {
// Reborrow here, so the borrow of `cell` doesn't get returned from
// the function. Otherwise the borrow checker assumes `cell` borrows
// `self.rows` for the entirety of the function, not just this match
// arm, and doesn't allow the second mutable borrow in the match arm
// below.
GridEntry::Cell(_) => self.entries[idx].as_cell_mut(),
&mut GridEntry::Spanned(idx) => self.entries[idx].as_cell_mut(),
GridEntry::Missing => None,
}
}
/// Mutably borrows disjoint cells. Cells are considered disjoint if their
/// positions don't resolve to the same parent cell in case of a
/// [`GridEntry::Cell`] or indirectly through a [`GridEntry::Spanned`].
///
/// # Panics
///
/// If one of the positions points to a [`GridEntry::Missing`].
pub fn cells_disjoint_mut<const N: usize>(
&mut self,
positions: [(u32, u32); N],
) -> Option<[&mut CtxCell<T>; N]> {
let indices = positions.map(|(x, y)| {
let idx = self.cell_idx(x, y);
let cell = &self.entries[idx];
match cell {
GridEntry::Cell(_) => idx,
&GridEntry::Spanned(idx) => idx,
GridEntry::Missing => unreachable!(),
}
});
let entries = self.entries.get_disjoint_mut(indices).ok()?;
Some(entries.map(|entry| entry.as_cell_mut().unwrap()))
}
pub fn resolve<'a>(&'a self, cell: &'a GridEntry<T>) -> Option<&'a CtxCell<T>> {
match cell {
GridEntry::Cell(cell) => Some(cell),
&GridEntry::Spanned(idx) => self.entries[idx].as_cell(),
GridEntry::Missing => None,
}
}
pub fn insert(&mut self, cell: CtxCell<T>) {
let x = cell.x;
let y = cell.y;
let rowspan = cell.rowspan.get();
let colspan = cell.colspan.get();
let parent_idx = self.cell_idx(x, y);
assert!(self.entries[parent_idx].is_missing());
// Store references to the cell for all spanned cells.
for j in y..y + rowspan {
for i in x..x + colspan {
let idx = self.cell_idx(i, j);
self.entries[idx] = GridEntry::Spanned(parent_idx);
}
}
self.entries[parent_idx] = GridEntry::Cell(cell);
}
fn cell_idx(&self, x: u32, y: u32) -> usize {
y as usize * self.width + x as usize
}
}
#[derive(Debug, Default, Clone)]
pub(super) enum GridEntry<D> {
Cell(CtxCell<D>),
Spanned(usize),
#[default]
Missing,
}
impl<D> GridEntry<D> {
pub fn as_cell(&self) -> Option<&CtxCell<D>> {
if let Self::Cell(v) = self { Some(v) } else { None }
}
pub fn as_cell_mut(&mut self) -> Option<&mut CtxCell<D>> {
if let Self::Cell(v) = self { Some(v) } else { None }
}
pub fn is_missing(&self) -> bool {
matches!(self, Self::Missing)
}
}
#[derive(Debug, Clone)]
pub(super) struct CtxCell<D> {
pub data: D,
pub x: u32,
pub y: u32,
pub rowspan: NonZeroU32,
pub colspan: NonZeroU32,
pub id: GroupId,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/context/mod.rs | crates/typst-pdf/src/tags/context/mod.rs | use std::cell::OnceCell;
use krilla::geom as kg;
use krilla::tagging::{BBox, Identifier, Node, TagKind};
use typst_library::layout::{Abs, Point, Rect};
use crate::convert::FrameContext;
use crate::tags::context::figure::build_figure;
use crate::tags::context::grid::build_grid;
use crate::tags::context::table::build_table;
use crate::tags::groups::GroupKind;
use crate::tags::tree::ResolvedTextAttrs;
use crate::tags::tree::Tree;
use crate::tags::util::{Id, IdVec};
use crate::util::AbsExt;
pub use crate::tags::context::figure::FigureCtx;
pub use crate::tags::context::grid::GridCtx;
pub use crate::tags::context::list::ListCtx;
pub use crate::tags::context::outline::OutlineCtx;
pub use crate::tags::context::table::TableCtx;
mod figure;
mod grid;
mod list;
mod outline;
mod table;
pub type TableId = Id<TableCtx>;
pub type GridId = Id<GridCtx>;
pub type FigureId = Id<FigureCtx>;
pub type ListId = Id<ListCtx>;
pub type OutlineId = Id<OutlineCtx>;
pub type BBoxId = Id<BBoxCtx>;
pub type TagId = Id<TagKind>;
pub type AnnotationId = Id<krilla::annotation::Annotation>;
pub struct Tags {
pub in_tiling: bool,
pub tree: Tree,
/// A list of placeholders for annotations in the tag tree.
pub annotations: Annotations,
}
impl Tags {
pub fn new(tree: Tree) -> Self {
Self {
in_tiling: false,
tree,
annotations: Annotations::new(),
}
}
pub fn push_leaf(&mut self, id: Identifier) {
let group = self.tree.groups.get_mut(self.tree.current());
group.push_leaf(id);
}
pub fn push_text(&mut self, new_attrs: ResolvedTextAttrs, text_id: Identifier) {
let group = self.tree.groups.get_mut(self.tree.current());
group.push_text(new_attrs, text_id);
}
}
pub struct Ctx {
pub tables: IdVec<TableCtx>,
pub grids: IdVec<GridCtx>,
pub figures: IdVec<FigureCtx>,
pub lists: IdVec<ListCtx>,
pub outlines: IdVec<OutlineCtx>,
pub bboxes: IdVec<BBoxCtx>,
}
impl Ctx {
pub const fn new() -> Self {
Self {
tables: IdVec::new(),
grids: IdVec::new(),
figures: IdVec::new(),
lists: IdVec::new(),
outlines: IdVec::new(),
bboxes: IdVec::new(),
}
}
pub fn new_bbox(&mut self) -> BBoxId {
self.bboxes.push(BBoxCtx::new())
}
pub fn bbox(&self, kind: &GroupKind) -> Option<&BBoxCtx> {
Some(self.bboxes.get(kind.bbox()?))
}
}
pub struct Annotations(Vec<OnceCell<Identifier>>);
impl Annotations {
pub const fn new() -> Self {
Self(Vec::new())
}
pub fn reserve(&mut self) -> AnnotationId {
let id = AnnotationId::new(self.0.len() as u32);
self.0.push(OnceCell::new());
id
}
pub fn init(&mut self, id: AnnotationId, annot: Identifier) {
self.0[id.idx()]
.set(annot)
.map_err(|_| ())
.expect("annotation to be uninitialized");
}
pub fn take(&mut self, id: AnnotationId) -> Node {
let annot = self.0[id.idx()].take().expect("initialized annotation node");
Node::Leaf(annot)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct BBoxCtx {
pub rect: Option<(usize, Rect)>,
pub multi_page: bool,
}
impl BBoxCtx {
pub fn new() -> Self {
Self { rect: None, multi_page: false }
}
/// Expand the bounding box with a `rect` relative to the current frame
/// context transform.
pub fn expand_frame(
&mut self,
fc: &FrameContext,
compute_rect: impl FnOnce() -> Rect,
) {
let Some(page_idx) = fc.page_idx else { return };
if self.multi_page {
return;
}
let (idx, bbox) = self.rect.get_or_insert((
page_idx,
Rect::new(Point::splat(Abs::inf()), Point::splat(-Abs::inf())),
));
if *idx != page_idx {
self.multi_page = true;
self.rect = None;
return;
}
let rect = compute_rect();
let size = rect.size();
for point in [
rect.min,
rect.min + Point::with_x(size.x),
rect.min + Point::with_y(size.y),
rect.max,
] {
let p = point.transform(fc.state().transform());
bbox.min = bbox.min.min(p);
bbox.max = bbox.max.max(p);
}
}
/// Expand the bounding box with a rectangle that's already transformed into
/// page coordinates.
pub fn expand_page(&mut self, inner: &BBoxCtx) {
self.multi_page |= inner.multi_page;
if self.multi_page {
return;
}
let Some((page_idx, rect)) = inner.rect else { return };
let (idx, bbox) = self.rect.get_or_insert((
page_idx,
Rect::new(Point::splat(Abs::inf()), Point::splat(-Abs::inf())),
));
if *idx != page_idx {
self.multi_page = true;
self.rect = None;
return;
}
bbox.min = bbox.min.min(rect.min);
bbox.max = bbox.max.max(rect.max);
}
pub fn to_krilla(&self) -> Option<BBox> {
let (page_idx, rect) = self.rect?;
let rect = kg::Rect::from_ltrb(
rect.min.x.to_f32(),
rect.min.y.to_f32(),
rect.max.x.to_f32(),
rect.max.y.to_f32(),
)
.unwrap();
Some(BBox::new(page_idx, rect))
}
}
pub fn finish(tree: &mut Tree) {
for figure_id in tree.ctx.figures.ids() {
build_figure(tree, figure_id);
}
for table_id in tree.ctx.tables.ids() {
build_table(tree, table_id);
}
for grid_id in tree.ctx.grids.ids() {
build_grid(tree, grid_id);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/context/figure.rs | crates/typst-pdf/src/tags/context/figure.rs | use krilla::tagging::TagKind;
use krilla::tagging::{self as kt, Tag};
use smallvec::SmallVec;
use typst_library::foundations::Packed;
use typst_library::model::FigureElem;
use crate::tags::context::FigureId;
use crate::tags::groups::{Group, GroupId, GroupKind, Groups};
use crate::tags::resolve::TagNode;
use crate::tags::tree::Tree;
use crate::tags::util::PropertyOptRef;
#[derive(Debug, Clone, PartialEq)]
pub struct FigureCtx {
pub group_id: GroupId,
pub elem: Packed<FigureElem>,
pub captions: SmallVec<[GroupId; 1]>,
pub tag_kind: FigureTagKind,
}
/// Which tag should be used to represent this figure in the PDF tag tree.
///
/// There is a fundamental mismatch between Typst figures and PDF figures.
/// In Typst a figure is used to group some illustrative content, optionally give
/// it a caption, and often reference it by labelling it.
/// In PDF a figure is more comparable to an image, and in PDF/UA it *must* have
/// an alternative description. This alternative description *must* describe the
/// entire enclosed content and any AT will not attempt to interpret any content
/// within that tag. This makes the `Figure` tag completely unsuited for figures
/// that contain tables or other structured data.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub enum FigureTagKind {
/// Use a `Figure` tag.
Figure,
/// Use a `Div` tag.
#[default]
Div,
/// Don't use any tag.
None,
}
impl FigureCtx {
pub fn new(group_id: GroupId, elem: Packed<FigureElem>) -> Self {
Self {
group_id,
elem,
captions: SmallVec::new(),
tag_kind: FigureTagKind::default(),
}
}
pub fn build_tag(&self) -> Option<TagKind> {
let alt = self.elem.alt.opt_ref().map(Into::into);
Some(match self.tag_kind {
FigureTagKind::Figure => {
Tag::Figure(alt).with_placement(Some(kt::Placement::Block)).into()
}
FigureTagKind::Div => Tag::Div
.with_alt_text(alt)
.with_placement(Some(kt::Placement::Block))
.into(),
FigureTagKind::None => return None,
})
}
/// Generate an enclosing `Div` tag if there is a caption.
pub fn build_wrapper_tag(&self) -> Option<TagKind> {
(!self.captions.is_empty()).then_some(Tag::Div.into())
}
}
pub fn build_figure(tree: &mut Tree, figure_id: FigureId) {
let figure_ctx = tree.ctx.figures.get_mut(figure_id);
let group = tree.groups.get(figure_ctx.group_id);
let wrapper = group.parent;
if figure_ctx.elem.alt.opt_ref().is_some() {
// If a figure has an alternative description, always use the
// figure tag.
figure_ctx.tag_kind = FigureTagKind::Figure;
} else if let Some(child) = single_semantic_child(&tree.groups, group) {
if let GroupKind::Table(..) = &tree.groups.get(child).kind {
// Move the caption inside the table.
let table = child;
let captions = std::mem::take(&mut figure_ctx.captions);
for caption in captions.iter() {
tree.groups.get_mut(*caption).parent = table;
}
tree.groups.prepend_groups(table, &captions);
}
// Omit an additional wrapping tag.
figure_ctx.tag_kind = FigureTagKind::None;
} else if !group.nodes().iter().any(|n| matches!(n, TagNode::Group(_))) {
// The figure contains only marked content.
figure_ctx.tag_kind = FigureTagKind::Figure;
}
// Insert the captions inside the figure.
// an enclosing element.
if !figure_ctx.captions.is_empty() {
for &caption in figure_ctx.captions.iter() {
tree.groups.get_mut(caption).parent = wrapper;
}
tree.groups.prepend_groups(wrapper, &figure_ctx.captions);
}
}
fn single_semantic_child<'a>(
groups: &'a Groups,
mut group: &'a Group,
) -> Option<GroupId> {
while let [TagNode::Group(id)] = group.nodes() {
group = groups.get(*id);
if group.kind.is_semantic() {
return Some(*id);
}
}
None
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-pdf/src/tags/context/outline.rs | crates/typst-pdf/src/tags/context/outline.rs | use krilla::tagging as kt;
use typst_library::foundations::Packed;
use typst_library::model::OutlineEntry;
use crate::tags::GroupId;
use crate::tags::groups::Groups;
#[derive(Debug, Clone)]
pub struct OutlineCtx {
/// The stack of nested `TOC` entries.
stack: Vec<GroupId>,
}
impl OutlineCtx {
pub fn new() -> Self {
Self { stack: Vec::new() }
}
pub fn insert(
&mut self,
groups: &mut Groups,
outline_id: GroupId,
entry: Packed<OutlineEntry>,
entry_id: GroupId,
) {
let expected_len = entry.level.get() - 1;
let mut parent = self.stack.last().copied().unwrap_or(outline_id);
self.stack.resize_with(expected_len, || {
parent = groups.push_tag(parent, kt::Tag::TOC);
parent
});
let parent = self.stack.last().copied().unwrap_or(outline_id);
groups.push_group(parent, entry_id);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-svg/src/paint.rs | crates/typst-svg/src/paint.rs | use std::f32::consts::TAU;
use ecow::{EcoString, eco_format};
use typst_library::foundations::Repr;
use typst_library::layout::{Angle, Axes, Frame, Quadrant, Ratio, Size, Transform};
use typst_library::visualize::{Color, FillRule, Gradient, Paint, RatioOrAngle, Tiling};
use typst_utils::hash128;
use xmlwriter::XmlWriter;
use crate::{Id, SVGRenderer, State, SvgMatrix, SvgPathBuilder};
/// The number of segments in a conic gradient.
/// This is a heuristic value that seems to work well.
/// Smaller values could be interesting for optimization.
const CONIC_SEGMENT: usize = 360;
impl SVGRenderer<'_> {
/// Render a frame to a string.
pub(super) fn render_tiling_frame(&mut self, state: &State, frame: &Frame) -> String {
let mut xml = XmlWriter::new(xmlwriter::Options::default());
std::mem::swap(&mut self.xml, &mut xml);
self.render_frame(state, frame);
std::mem::swap(&mut self.xml, &mut xml);
xml.end_document()
}
/// Write a fill attribute.
pub(super) fn write_fill(
&mut self,
fill: &Paint,
fill_rule: FillRule,
size: Size,
ts: Transform,
) {
match fill {
Paint::Solid(color) => self.xml.write_attribute("fill", &color.encode()),
Paint::Gradient(gradient) => {
let id = self.push_gradient(gradient, size, ts);
self.xml.write_attribute_fmt("fill", format_args!("url(#{id})"));
}
Paint::Tiling(tiling) => {
let id = self.push_tiling(tiling, size, ts);
self.xml.write_attribute_fmt("fill", format_args!("url(#{id})"));
}
}
match fill_rule {
FillRule::NonZero => self.xml.write_attribute("fill-rule", "nonzero"),
FillRule::EvenOdd => self.xml.write_attribute("fill-rule", "evenodd"),
}
}
/// Pushes a gradient to the list of gradients to write SVG file.
///
/// If the gradient is already present, returns the id of the existing
/// gradient. Otherwise, inserts the gradient and returns the id of the
/// inserted gradient. If the transform of the gradient is the identify
/// matrix, the returned ID will be the ID of the "source" gradient,
/// this is a file size optimization.
pub(super) fn push_gradient(
&mut self,
gradient: &Gradient,
size: Size,
ts: Transform,
) -> Id {
let gradient_id = self
.gradients
.insert_with(hash128(&(gradient, size.aspect_ratio())), || {
(gradient.clone(), size.aspect_ratio())
});
if ts.is_identity() {
return gradient_id;
}
self.gradient_refs
.insert_with(hash128(&(gradient_id, ts)), || GradientRef {
id: gradient_id,
kind: gradient.into(),
transform: ts,
})
}
pub(super) fn push_tiling(
&mut self,
tiling: &Tiling,
size: Size,
ts: Transform,
) -> Id {
let tiling_size = tiling.size() + tiling.spacing();
// Unfortunately due to a limitation of `xmlwriter`, we need to
// render the frame twice: once to allocate all of the resources
// that it needs and once to actually render it.
self.render_tiling_frame(&State::new(tiling_size), tiling.frame());
let tiling_id = self.tilings.insert_with(hash128(tiling), || tiling.clone());
self.tiling_refs.insert_with(hash128(&(tiling_id, ts)), || TilingRef {
id: tiling_id,
transform: ts,
ratio: Axes::new(
Ratio::new(tiling_size.x.to_pt() / size.x.to_pt()),
Ratio::new(tiling_size.y.to_pt() / size.y.to_pt()),
),
})
}
/// Write the raw gradients (without transform) to the SVG file.
pub(super) fn write_gradients(&mut self) {
if self.gradients.is_empty() {
return;
}
self.xml.start_element("defs");
self.xml.write_attribute("id", "gradients");
for (id, (gradient, ratio)) in self.gradients.iter() {
match &gradient {
Gradient::Linear(linear) => {
self.xml.start_element("linearGradient");
self.xml.write_attribute("id", &id);
self.xml.write_attribute("spreadMethod", "pad");
self.xml.write_attribute("gradientUnits", "userSpaceOnUse");
let angle = Gradient::correct_aspect_ratio(linear.angle, *ratio);
let (sin, cos) = (angle.sin(), angle.cos());
let length = sin.abs() + cos.abs();
let (x1, y1, x2, y2) = match angle.quadrant() {
Quadrant::First => (0.0, 0.0, cos * length, sin * length),
Quadrant::Second => (1.0, 0.0, cos * length + 1.0, sin * length),
Quadrant::Third => {
(1.0, 1.0, cos * length + 1.0, sin * length + 1.0)
}
Quadrant::Fourth => (0.0, 1.0, cos * length, sin * length + 1.0),
};
self.xml.write_attribute("x1", &x1);
self.xml.write_attribute("y1", &y1);
self.xml.write_attribute("x2", &x2);
self.xml.write_attribute("y2", &y2);
}
Gradient::Radial(radial) => {
self.xml.start_element("radialGradient");
self.xml.write_attribute("id", &id);
self.xml.write_attribute("spreadMethod", "pad");
self.xml.write_attribute("gradientUnits", "userSpaceOnUse");
self.xml.write_attribute("cx", &radial.center.x.get());
self.xml.write_attribute("cy", &radial.center.y.get());
self.xml.write_attribute("r", &radial.radius.get());
self.xml.write_attribute("fx", &radial.focal_center.x.get());
self.xml.write_attribute("fy", &radial.focal_center.y.get());
self.xml.write_attribute("fr", &radial.focal_radius.get());
}
Gradient::Conic(conic) => {
self.xml.start_element("pattern");
self.xml.write_attribute("id", &id);
self.xml.write_attribute("viewBox", "0 0 1 1");
self.xml.write_attribute("preserveAspectRatio", "none");
self.xml.write_attribute("patternUnits", "userSpaceOnUse");
self.xml.write_attribute("width", "2");
self.xml.write_attribute("height", "2");
self.xml.write_attribute("x", "-0.5");
self.xml.write_attribute("y", "-0.5");
// The rotation angle, negated to match rotation in PNG.
let angle: f32 =
-(Gradient::correct_aspect_ratio(conic.angle, *ratio).to_rad()
as f32)
.rem_euclid(TAU);
let center: (f32, f32) =
(conic.center.x.get() as f32, conic.center.y.get() as f32);
// We build an arg segment for each segment of a circle.
let dtheta = TAU / CONIC_SEGMENT as f32;
for i in 0..CONIC_SEGMENT {
let theta1 = dtheta * i as f32;
let theta2 = dtheta * (i + 1) as f32;
// Create the path for the segment.
let mut builder = SvgPathBuilder::default();
builder.move_to(
correct_tiling_pos(center.0),
correct_tiling_pos(center.1),
);
builder.line_to(
correct_tiling_pos(-2.0 * (theta1 + angle).cos() + center.0),
correct_tiling_pos(2.0 * (theta1 + angle).sin() + center.1),
);
builder.arc(
(2.0, 2.0),
0.0,
0,
1,
(
correct_tiling_pos(
-2.0 * (theta2 + angle).cos() + center.0,
),
correct_tiling_pos(
2.0 * (theta2 + angle).sin() + center.1,
),
),
);
builder.close();
let t1 = (i as f32) / CONIC_SEGMENT as f32;
let t2 = (i + 1) as f32 / CONIC_SEGMENT as f32;
let subgradient = SVGSubGradient {
center: conic.center,
t0: Angle::rad((theta1 + angle) as f64),
t1: Angle::rad((theta2 + angle) as f64),
c0: gradient
.sample(RatioOrAngle::Ratio(Ratio::new(t1 as f64))),
c1: gradient
.sample(RatioOrAngle::Ratio(Ratio::new(t2 as f64))),
};
let id = self
.conic_subgradients
.insert_with(hash128(&subgradient), || subgradient);
// Add the path to the pattern.
self.xml.start_element("path");
self.xml.write_attribute("d", &builder.path);
self.xml.write_attribute_fmt("fill", format_args!("url(#{id})"));
self.xml
.write_attribute_fmt("stroke", format_args!("url(#{id})"));
self.xml.write_attribute("stroke-width", "0");
self.xml.write_attribute("shape-rendering", "optimizeSpeed");
self.xml.end_element();
}
// We skip the default stop generation code.
self.xml.end_element();
continue;
}
}
for window in gradient.stops_ref().windows(2) {
let (start_c, start_t) = window[0];
let (end_c, end_t) = window[1];
self.xml.start_element("stop");
self.xml.write_attribute("offset", &start_t.repr());
self.xml.write_attribute("stop-color", &start_c.to_hex());
self.xml.end_element();
// Generate (256 / len) stops between the two stops.
// This is a workaround for a bug in many readers:
// They tend to just ignore the color space of the gradient.
// The goal is to have smooth gradients but not to balloon the file size
// too much if there are already a lot of stops as in most presets.
let len = if gradient.anti_alias() {
(256 / gradient.stops_ref().len() as u32).max(2)
} else {
2
};
for i in 1..(len - 1) {
let t0 = i as f64 / (len - 1) as f64;
let t = start_t + (end_t - start_t) * t0;
let c = gradient.sample(RatioOrAngle::Ratio(t));
self.xml.start_element("stop");
self.xml.write_attribute("offset", &t.repr());
self.xml.write_attribute("stop-color", &c.to_hex());
self.xml.end_element();
}
self.xml.start_element("stop");
self.xml.write_attribute("offset", &end_t.repr());
self.xml.write_attribute("stop-color", &end_c.to_hex());
self.xml.end_element()
}
self.xml.end_element();
}
self.xml.end_element()
}
/// Write the sub-gradients that are used for conic gradients.
pub(super) fn write_subgradients(&mut self) {
if self.conic_subgradients.is_empty() {
return;
}
self.xml.start_element("defs");
self.xml.write_attribute("id", "subgradients");
for (id, gradient) in self.conic_subgradients.iter() {
let x1 = 2.0 - gradient.t0.cos() as f32 + gradient.center.x.get() as f32;
let y1 = gradient.t0.sin() as f32 + gradient.center.y.get() as f32;
let x2 = 2.0 - gradient.t1.cos() as f32 + gradient.center.x.get() as f32;
let y2 = gradient.t1.sin() as f32 + gradient.center.y.get() as f32;
self.xml.start_element("linearGradient");
self.xml.write_attribute("id", &id);
self.xml.write_attribute("gradientUnits", "objectBoundingBox");
self.xml.write_attribute("x1", &x1);
self.xml.write_attribute("y1", &y1);
self.xml.write_attribute("x2", &x2);
self.xml.write_attribute("y2", &y2);
self.xml.start_element("stop");
self.xml.write_attribute("offset", "0%");
self.xml.write_attribute("stop-color", &gradient.c0.to_hex());
self.xml.end_element();
self.xml.start_element("stop");
self.xml.write_attribute("offset", "100%");
self.xml.write_attribute("stop-color", &gradient.c1.to_hex());
self.xml.end_element();
self.xml.end_element();
}
self.xml.end_element();
}
pub(super) fn write_gradient_refs(&mut self) {
if self.gradient_refs.is_empty() {
return;
}
self.xml.start_element("defs");
self.xml.write_attribute("id", "gradient-refs");
for (id, gradient_ref) in self.gradient_refs.iter() {
match gradient_ref.kind {
GradientKind::Linear => {
self.xml.start_element("linearGradient");
self.xml.write_attribute(
"gradientTransform",
&SvgMatrix(gradient_ref.transform),
);
}
GradientKind::Radial => {
self.xml.start_element("radialGradient");
self.xml.write_attribute(
"gradientTransform",
&SvgMatrix(gradient_ref.transform),
);
}
GradientKind::Conic => {
self.xml.start_element("pattern");
self.xml.write_attribute(
"patternTransform",
&SvgMatrix(gradient_ref.transform),
);
}
}
self.xml.write_attribute("id", &id);
// Writing the href attribute to the "reference" gradient.
self.xml
.write_attribute_fmt("href", format_args!("#{}", gradient_ref.id));
// Also writing the xlink:href attribute for compatibility.
self.xml
.write_attribute_fmt("xlink:href", format_args!("#{}", gradient_ref.id));
self.xml.end_element();
}
self.xml.end_element();
}
/// Write the raw tilings (without transform) to the SVG file.
pub(super) fn write_tilings(&mut self) {
if self.tilings.is_empty() {
return;
}
self.xml.start_element("defs");
self.xml.write_attribute("id", "tilings");
for (id, tiling) in
self.tilings.iter().map(|(i, p)| (i, p.clone())).collect::<Vec<_>>()
{
let size = tiling.size() + tiling.spacing();
self.xml.start_element("pattern");
self.xml.write_attribute("id", &id);
self.xml.write_attribute("width", &size.x.to_pt());
self.xml.write_attribute("height", &size.y.to_pt());
self.xml.write_attribute("patternUnits", "userSpaceOnUse");
self.xml.write_attribute_fmt(
"viewBox",
format_args!("0 0 {:.3} {:.3}", size.x.to_pt(), size.y.to_pt()),
);
// Render the frame.
let state = State::new(size);
self.render_frame(&state, tiling.frame());
self.xml.end_element();
}
self.xml.end_element()
}
/// Writes the references to the deduplicated tilings for each usage site.
pub(super) fn write_tiling_refs(&mut self) {
if self.tiling_refs.is_empty() {
return;
}
self.xml.start_element("defs");
self.xml.write_attribute("id", "tilings-refs");
for (id, tiling_ref) in self.tiling_refs.iter() {
self.xml.start_element("pattern");
self.xml
.write_attribute("patternTransform", &SvgMatrix(tiling_ref.transform));
self.xml.write_attribute("id", &id);
// Writing the href attribute to the "reference" pattern.
self.xml
.write_attribute_fmt("href", format_args!("#{}", tiling_ref.id));
// Also writing the xlink:href attribute for compatibility.
self.xml
.write_attribute_fmt("xlink:href", format_args!("#{}", tiling_ref.id));
self.xml.end_element();
}
self.xml.end_element();
}
}
/// A reference to a deduplicated tiling, with a transform matrix.
///
/// Allows tilings to be reused across multiple invocations, simply by changing
/// the transform matrix.
#[derive(Hash)]
pub struct TilingRef {
/// The ID of the deduplicated gradient
id: Id,
/// The transform matrix to apply to the tiling.
transform: Transform,
/// The ratio of the size of the cell to the size of the filled area.
ratio: Axes<Ratio>,
}
/// A reference to a deduplicated gradient, with a transform matrix.
///
/// Allows gradients to be reused across multiple invocations,
/// simply by changing the transform matrix.
#[derive(Hash)]
pub struct GradientRef {
/// The ID of the deduplicated gradient
id: Id,
/// The gradient kind (used to determine the SVG element to use)
/// but without needing to clone the entire gradient.
kind: GradientKind,
/// The transform matrix to apply to the gradient.
transform: Transform,
}
/// A subgradient for conic gradients.
#[derive(Hash)]
pub struct SVGSubGradient {
/// The center point of the gradient.
center: Axes<Ratio>,
/// The start point of the subgradient.
t0: Angle,
/// The end point of the subgradient.
t1: Angle,
/// The color at the start point of the subgradient.
c0: Color,
/// The color at the end point of the subgradient.
c1: Color,
}
/// The kind of linear gradient.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
enum GradientKind {
/// A linear gradient.
Linear,
/// A radial gradient.
Radial,
/// A conic gradient.
Conic,
}
impl From<&Gradient> for GradientKind {
fn from(value: &Gradient) -> Self {
match value {
Gradient::Linear { .. } => GradientKind::Linear,
Gradient::Radial { .. } => GradientKind::Radial,
Gradient::Conic { .. } => GradientKind::Conic,
}
}
}
/// Encode the color as an SVG color.
pub trait ColorEncode {
/// Encode the color.
fn encode(&self) -> EcoString;
}
impl ColorEncode for Color {
fn encode(&self) -> EcoString {
match *self {
c @ Color::Rgb(_)
| c @ Color::Luma(_)
| c @ Color::Cmyk(_)
| c @ Color::Hsv(_) => c.to_hex(),
Color::LinearRgb(rgb) => {
if rgb.alpha != 1.0 {
eco_format!(
"color(srgb-linear {:.5} {:.5} {:.5} / {:.5})",
rgb.red,
rgb.green,
rgb.blue,
rgb.alpha
)
} else {
eco_format!(
"color(srgb-linear {:.5} {:.5} {:.5})",
rgb.red,
rgb.green,
rgb.blue,
)
}
}
Color::Oklab(oklab) => {
if oklab.alpha != 1.0 {
eco_format!(
"oklab({:.3}% {:.5} {:.5} / {:.5})",
oklab.l * 100.0,
oklab.a,
oklab.b,
oklab.alpha
)
} else {
eco_format!(
"oklab({:.3}% {:.5} {:.5})",
oklab.l * 100.0,
oklab.a,
oklab.b,
)
}
}
Color::Oklch(oklch) => {
if oklch.alpha != 1.0 {
eco_format!(
"oklch({:.3}% {:.5} {:.3}deg / {:.3})",
oklch.l * 100.0,
oklch.chroma,
oklch.hue.into_degrees(),
oklch.alpha
)
} else {
eco_format!(
"oklch({:.3}% {:.5} {:.3}deg)",
oklch.l * 100.0,
oklch.chroma,
oklch.hue.into_degrees(),
)
}
}
Color::Hsl(hsl) => {
if hsl.alpha != 1.0 {
eco_format!(
"hsla({:.3}deg {:.3}% {:.3}% / {:.5})",
hsl.hue.into_degrees(),
hsl.saturation * 100.0,
hsl.lightness * 100.0,
hsl.alpha,
)
} else {
eco_format!(
"hsl({:.3}deg {:.3}% {:.3}%)",
hsl.hue.into_degrees(),
hsl.saturation * 100.0,
hsl.lightness * 100.0,
)
}
}
}
}
}
/// Maps a coordinate in a unit size square to a coordinate in the tiling.
pub fn correct_tiling_pos(x: f32) -> f32 {
(x + 0.5) / 2.0
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-svg/src/shape.rs | crates/typst-svg/src/shape.rs | use ecow::EcoString;
use typst_library::layout::{Abs, Point, Ratio, Size, Transform};
use typst_library::visualize::{
Curve, CurveItem, FixedStroke, Geometry, LineCap, LineJoin, Paint, RelativeTo, Shape,
};
use crate::paint::ColorEncode;
use crate::{SVGRenderer, State, SvgMatrix, SvgPathBuilder};
impl SVGRenderer<'_> {
/// Render a shape element.
pub(super) fn render_shape(&mut self, state: &State, shape: &Shape) {
self.xml.start_element("path");
self.xml.write_attribute("class", "typst-shape");
if let Some(paint) = &shape.fill {
self.write_fill(
paint,
shape.fill_rule,
self.shape_fill_size(state, paint, shape),
self.shape_paint_transform(state, paint, shape),
);
} else {
self.xml.write_attribute("fill", "none");
}
if let Some(stroke) = &shape.stroke {
self.write_stroke(
stroke,
self.shape_fill_size(state, &stroke.paint, shape),
self.shape_paint_transform(state, &stroke.paint, shape),
);
}
if !state.transform.is_identity() {
self.xml.write_attribute("transform", &SvgMatrix(state.transform));
}
let path = convert_geometry_to_path(&shape.geometry);
self.xml.write_attribute("d", &path);
self.xml.end_element();
}
/// Calculate the transform of the shape's fill or stroke.
fn shape_paint_transform(
&self,
state: &State,
paint: &Paint,
shape: &Shape,
) -> Transform {
let mut shape_size = shape.geometry.bbox_size();
// Edge cases for strokes.
if shape_size.x.to_pt() == 0.0 {
shape_size.x = Abs::pt(1.0);
}
if shape_size.y.to_pt() == 0.0 {
shape_size.y = Abs::pt(1.0);
}
if let Paint::Gradient(gradient) = paint {
match gradient.unwrap_relative(false) {
RelativeTo::Self_ => Transform::scale(
Ratio::new(shape_size.x.to_pt()),
Ratio::new(shape_size.y.to_pt()),
),
RelativeTo::Parent => Transform::scale(
Ratio::new(state.size.x.to_pt()),
Ratio::new(state.size.y.to_pt()),
)
.post_concat(state.transform.invert().unwrap()),
}
} else if let Paint::Tiling(tiling) = paint {
match tiling.unwrap_relative(false) {
RelativeTo::Self_ => Transform::identity(),
RelativeTo::Parent => state.transform.invert().unwrap(),
}
} else {
Transform::identity()
}
}
/// Calculate the size of the shape's fill.
fn shape_fill_size(&self, state: &State, paint: &Paint, shape: &Shape) -> Size {
let mut shape_size = shape.geometry.bbox_size();
// Edge cases for strokes.
if shape_size.x.to_pt() == 0.0 {
shape_size.x = Abs::pt(1.0);
}
if shape_size.y.to_pt() == 0.0 {
shape_size.y = Abs::pt(1.0);
}
if let Paint::Gradient(gradient) = paint {
match gradient.unwrap_relative(false) {
RelativeTo::Self_ => shape_size,
RelativeTo::Parent => state.size,
}
} else {
shape_size
}
}
/// Write a stroke attribute.
pub(super) fn write_stroke(
&mut self,
stroke: &FixedStroke,
size: Size,
fill_transform: Transform,
) {
match &stroke.paint {
Paint::Solid(color) => self.xml.write_attribute("stroke", &color.encode()),
Paint::Gradient(gradient) => {
let id = self.push_gradient(gradient, size, fill_transform);
self.xml.write_attribute_fmt("stroke", format_args!("url(#{id})"));
}
Paint::Tiling(tiling) => {
let id = self.push_tiling(tiling, size, fill_transform);
self.xml.write_attribute_fmt("stroke", format_args!("url(#{id})"));
}
}
self.xml.write_attribute("stroke-width", &stroke.thickness.to_pt());
self.xml.write_attribute(
"stroke-linecap",
match stroke.cap {
LineCap::Butt => "butt",
LineCap::Round => "round",
LineCap::Square => "square",
},
);
self.xml.write_attribute(
"stroke-linejoin",
match stroke.join {
LineJoin::Miter => "miter",
LineJoin::Round => "round",
LineJoin::Bevel => "bevel",
},
);
self.xml
.write_attribute("stroke-miterlimit", &stroke.miter_limit.get());
if let Some(dash) = &stroke.dash {
self.xml.write_attribute("stroke-dashoffset", &dash.phase.to_pt());
self.xml.write_attribute(
"stroke-dasharray",
&dash
.array
.iter()
.map(|dash| dash.to_pt().to_string())
.collect::<Vec<_>>()
.join(" "),
);
}
}
}
/// Convert a geometry to an SVG path.
#[comemo::memoize]
fn convert_geometry_to_path(geometry: &Geometry) -> EcoString {
let mut builder =
SvgPathBuilder::with_translate(Point::new(Abs::zero(), Abs::zero()));
match geometry {
Geometry::Line(t) => {
builder.move_to(0.0, 0.0);
builder.line_to(t.x.to_pt() as f32, t.y.to_pt() as f32);
}
Geometry::Rect(rect) => {
let x = rect.x.to_pt() as f32;
let y = rect.y.to_pt() as f32;
builder.rect(x, y);
}
Geometry::Curve(p) => {
return convert_curve(Point::new(Abs::zero(), Abs::zero()), p);
}
};
builder.path
}
pub fn convert_curve(initial_point: Point, curve: &Curve) -> EcoString {
let mut builder = SvgPathBuilder::with_translate(initial_point);
for item in &curve.0 {
match item {
CurveItem::Move(m) => builder.move_to(m.x.to_pt() as f32, m.y.to_pt() as f32),
CurveItem::Line(l) => builder.line_to(l.x.to_pt() as f32, l.y.to_pt() as f32),
CurveItem::Cubic(c1, c2, t) => builder.curve_to(
c1.x.to_pt() as f32,
c1.y.to_pt() as f32,
c2.x.to_pt() as f32,
c2.y.to_pt() as f32,
t.x.to_pt() as f32,
t.y.to_pt() as f32,
),
CurveItem::Close => builder.close(),
}
}
builder.path
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-svg/src/lib.rs | crates/typst-svg/src/lib.rs | //! Rendering of Typst documents into SVG images.
mod image;
mod paint;
mod shape;
mod text;
pub use image::{convert_image_scaling, convert_image_to_base64_url};
use rustc_hash::FxHashMap;
use typst_library::introspection::Introspector;
use typst_library::model::Destination;
use std::fmt::{self, Display, Formatter, Write};
use ecow::EcoString;
use typst_library::layout::{
Abs, Frame, FrameItem, FrameKind, GroupItem, Page, PagedDocument, Point, Ratio, Size,
Transform,
};
use typst_library::visualize::{Geometry, Gradient, Tiling};
use typst_utils::hash128;
use xmlwriter::XmlWriter;
use crate::paint::{GradientRef, SVGSubGradient, TilingRef};
use crate::text::RenderedGlyph;
/// Export a frame into a SVG file.
#[typst_macros::time(name = "svg")]
pub fn svg(page: &Page) -> String {
let mut renderer = SVGRenderer::new();
renderer.write_header(page.frame.size());
let state = State::new(page.frame.size());
renderer.render_page(&state, Transform::identity(), page);
renderer.finalize()
}
/// Export a frame into a SVG file.
#[typst_macros::time(name = "svg frame")]
pub fn svg_frame(frame: &Frame) -> String {
let mut renderer = SVGRenderer::new();
renderer.write_header(frame.size());
let state = State::new(frame.size());
renderer.render_frame(&state, frame);
renderer.finalize()
}
/// Export a frame into an SVG suitable for embedding into HTML.
#[typst_macros::time(name = "svg html frame")]
pub fn svg_html_frame(
frame: &Frame,
text_size: Abs,
id: Option<&str>,
link_points: &[(Point, EcoString)],
introspector: &Introspector,
) -> String {
let mut renderer = SVGRenderer::with_options(
xmlwriter::Options {
indent: xmlwriter::Indent::None,
..Default::default()
},
Some(introspector),
);
renderer.write_header_with_custom_attrs(frame.size(), |xml| {
if let Some(id) = id {
xml.write_attribute("id", id);
}
xml.write_attribute("class", "typst-frame");
xml.write_attribute_fmt(
"style",
format_args!(
"overflow: visible; width: {}em; height: {}em;",
frame.width() / text_size,
frame.height() / text_size,
),
);
});
let state = State::new(frame.size());
renderer.render_frame(&state, frame);
for (pos, id) in link_points {
renderer.render_link_point(*pos, id);
}
renderer.finalize()
}
/// Export a document with potentially multiple pages into a single SVG file.
///
/// The gap will be added between the individual pages.
pub fn svg_merged(document: &PagedDocument, gap: Abs) -> String {
let width = document
.pages
.iter()
.map(|page| page.frame.width())
.max()
.unwrap_or_default();
let height = document.pages.len().saturating_sub(1) as f64 * gap
+ document.pages.iter().map(|page| page.frame.height()).sum::<Abs>();
let mut renderer = SVGRenderer::new();
renderer.write_header(Size::new(width, height));
let mut y = Abs::zero();
for page in &document.pages {
let state = State::new(page.frame.size());
renderer.render_page(&state, Transform::translate(Abs::zero(), y), page);
y += page.frame.height() + gap;
}
renderer.finalize()
}
/// Renders one or multiple frames to an SVG file.
struct SVGRenderer<'a> {
/// The internal XML writer.
xml: XmlWriter,
/// The document's introspector, if we're writing an HTML frame.
introspector: Option<&'a Introspector>,
/// Prepared glyphs.
glyphs: Deduplicator<RenderedGlyph>,
/// Clip paths are used to clip a group. A clip path is a path that defines
/// the clipping region. The clip path is referenced by the `clip-path`
/// attribute of the group. The clip path is in the format of `M x y L x y C
/// x1 y1 x2 y2 x y Z`.
clip_paths: Deduplicator<EcoString>,
/// Deduplicated gradients with transform matrices. They use a reference
/// (`href`) to a "source" gradient instead of being defined inline.
/// This saves a lot of space since gradients are often reused but with
/// different transforms. Therefore this allows us to reuse the same gradient
/// multiple times.
gradient_refs: Deduplicator<GradientRef>,
/// Deduplicated tilings with transform matrices. They use a reference
/// (`href`) to a "source" tiling instead of being defined inline.
/// This saves a lot of space since tilings are often reused but with
/// different transforms. Therefore this allows us to reuse the same gradient
/// multiple times.
tiling_refs: Deduplicator<TilingRef>,
/// These are the actual gradients being written in the SVG file.
/// These gradients are deduplicated because they do not contain the transform
/// matrix, allowing them to be reused across multiple invocations.
///
/// The `Ratio` is the aspect ratio of the gradient, this is used to correct
/// the angle of the gradient.
gradients: Deduplicator<(Gradient, Ratio)>,
/// These are the actual tilings being written in the SVG file.
/// These tilings are deduplicated because they do not contain the transform
/// matrix, allowing them to be reused across multiple invocations.
///
/// The `String` is the rendered tiling frame.
tilings: Deduplicator<Tiling>,
/// These are the gradients that compose a conic gradient.
conic_subgradients: Deduplicator<SVGSubGradient>,
}
/// Contextual information for rendering.
#[derive(Copy, Clone)]
struct State {
/// The transform of the current item.
transform: Transform,
/// The size of the first hard frame in the hierarchy.
size: Size,
}
impl State {
fn new(size: Size) -> Self {
Self { size, transform: Transform::identity() }
}
/// Pre translate the current item's transform.
fn pre_translate(self, pos: Point) -> Self {
self.pre_concat(Transform::translate(pos.x, pos.y))
}
/// Pre concat the current item's transform.
fn pre_concat(self, transform: Transform) -> Self {
Self {
transform: self.transform.pre_concat(transform),
..self
}
}
/// Sets the size of the first hard frame in the hierarchy.
fn with_size(self, size: Size) -> Self {
Self { size, ..self }
}
/// Sets the current item's transform.
fn with_transform(self, transform: Transform) -> Self {
Self { transform, ..self }
}
}
impl<'a> SVGRenderer<'a> {
/// Create a new SVG renderer with empty glyph and clip path.
fn new() -> Self {
Self::with_options(Default::default(), None)
}
/// Create a new SVG renderer with the given configuration.
fn with_options(
options: xmlwriter::Options,
introspector: Option<&'a Introspector>,
) -> Self {
SVGRenderer {
xml: XmlWriter::new(options),
introspector,
glyphs: Deduplicator::new('g'),
clip_paths: Deduplicator::new('c'),
gradient_refs: Deduplicator::new('g'),
gradients: Deduplicator::new('f'),
conic_subgradients: Deduplicator::new('s'),
tiling_refs: Deduplicator::new('p'),
tilings: Deduplicator::new('t'),
}
}
/// Write the default SVG header, including a `typst-doc` class, the
/// `viewBox` and `width` and `height` attributes.
fn write_header(&mut self, size: Size) {
self.write_header_with_custom_attrs(size, |xml| {
xml.write_attribute("class", "typst-doc");
});
}
/// Write the SVG header with additional attributes and standard attributes.
fn write_header_with_custom_attrs(
&mut self,
size: Size,
write_custom_attrs: impl FnOnce(&mut XmlWriter),
) {
self.xml.start_element("svg");
write_custom_attrs(&mut self.xml);
self.xml.write_attribute_fmt(
"viewBox",
format_args!("0 0 {} {}", size.x.to_pt(), size.y.to_pt()),
);
self.xml
.write_attribute_fmt("width", format_args!("{}pt", size.x.to_pt()));
self.xml
.write_attribute_fmt("height", format_args!("{}pt", size.y.to_pt()));
self.xml.write_attribute("xmlns", "http://www.w3.org/2000/svg");
self.xml
.write_attribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
self.xml.write_attribute("xmlns:h5", "http://www.w3.org/1999/xhtml");
}
/// Render a page with the given transform.
fn render_page(&mut self, state: &State, ts: Transform, page: &Page) {
if !ts.is_identity() {
self.xml.start_element("g");
self.xml.write_attribute("transform", &SvgMatrix(ts));
}
if let Some(fill) = page.fill_or_white() {
let shape = Geometry::Rect(page.frame.size()).filled(fill);
self.render_shape(state, &shape);
}
self.render_frame(state, &page.frame);
if !ts.is_identity() {
self.xml.end_element();
}
}
/// Render a frame with the given transform.
fn render_frame(&mut self, state: &State, frame: &Frame) {
self.xml.start_element("g");
for (pos, item) in frame.items() {
let state = state.pre_translate(*pos);
match item {
FrameItem::Group(group) => self.render_group(&state, group),
FrameItem::Text(text) => self.render_text(&state, text),
FrameItem::Shape(shape, _) => self.render_shape(&state, shape),
FrameItem::Image(image, size, _) => {
self.render_image(&state, image, size)
}
FrameItem::Link(dest, size) => self.render_link(&state, dest, *size),
FrameItem::Tag(_) => {}
};
}
self.xml.end_element();
}
/// Render a group. If the group has `clips` set to true, a clip path will
/// be created.
fn render_group(&mut self, state: &State, group: &GroupItem) {
self.xml.start_element("g");
self.xml.write_attribute("class", "typst-group");
let state = match group.frame.kind() {
FrameKind::Soft => state.pre_concat(group.transform),
FrameKind::Hard => {
let transform = state.transform.pre_concat(group.transform);
if !transform.is_identity() {
self.xml.write_attribute("transform", &SvgMatrix(transform));
}
state
.with_transform(Transform::identity())
.with_size(group.frame.size())
}
};
if let Some(label) = group.label {
self.xml.write_attribute("data-typst-label", &label.resolve());
}
if let Some(clip_curve) = &group.clip {
let offset = Point::new(state.transform.tx, state.transform.ty);
let hash = hash128(&(&clip_curve, &offset));
let id = self
.clip_paths
.insert_with(hash, || shape::convert_curve(offset, clip_curve));
self.xml.write_attribute_fmt("clip-path", format_args!("url(#{id})"));
}
self.render_frame(&state, &group.frame);
self.xml.end_element();
}
/// Render a link element.
fn render_link(&mut self, state: &State, dest: &Destination, size: Size) {
self.xml.start_element("a");
if !state.transform.is_identity() {
self.xml.write_attribute("transform", &SvgMatrix(state.transform));
}
match dest {
Destination::Location(loc) => {
// 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}"));
}
}
Destination::Position(_) => {
// TODO: Links on the same page could be supported.
}
Destination::Url(url) => {
self.xml.write_attribute("href", url.as_str());
self.xml.write_attribute("xlink:href", url.as_str());
}
}
self.xml.start_element("rect");
self.xml
.write_attribute_fmt("width", format_args!("{}", size.x.to_pt()));
self.xml
.write_attribute_fmt("height", format_args!("{}", size.y.to_pt()));
self.xml.write_attribute("fill", "transparent");
self.xml.write_attribute("stroke", "none");
self.xml.end_element();
self.xml.end_element();
}
/// Renders a linkable point that can be used to link into an HTML frame.
fn render_link_point(&mut self, pos: Point, id: &str) {
self.xml.start_element("g");
self.xml.write_attribute("id", id);
self.xml.write_attribute_fmt(
"transform",
format_args!("translate({} {})", pos.x.to_pt(), pos.y.to_pt()),
);
self.xml.end_element();
}
/// Finalize the SVG file. This must be called after all rendering is done.
fn finalize(mut self) -> String {
self.write_glyph_defs();
self.write_clip_path_defs();
self.write_gradients();
self.write_gradient_refs();
self.write_subgradients();
self.write_tilings();
self.write_tiling_refs();
self.xml.end_document()
}
/// Build the clip path definitions.
fn write_clip_path_defs(&mut self) {
if self.clip_paths.is_empty() {
return;
}
self.xml.start_element("defs");
self.xml.write_attribute("id", "clip-path");
for (id, path) in self.clip_paths.iter() {
self.xml.start_element("clipPath");
self.xml.write_attribute("id", &id);
self.xml.start_element("path");
self.xml.write_attribute("d", &path);
self.xml.end_element();
self.xml.end_element();
}
self.xml.end_element();
}
}
/// Deduplicates its elements. It is used to deduplicate glyphs and clip paths.
/// The `H` is the hash type, and `T` is the value type. The `PREFIX` is the
/// prefix of the index. This is used to distinguish between glyphs and clip
/// paths.
#[derive(Debug, Clone)]
struct Deduplicator<T> {
kind: char,
vec: Vec<(u128, T)>,
present: FxHashMap<u128, Id>,
}
impl<T> Deduplicator<T> {
fn new(kind: char) -> Self {
Self {
kind,
vec: Vec::new(),
present: FxHashMap::default(),
}
}
/// Inserts a value into the vector. If the hash is already present, returns
/// the index of the existing value and `f` will not be called. Otherwise,
/// inserts the value and returns the id of the inserted value.
#[must_use = "returns the index of the inserted value"]
fn insert_with<F>(&mut self, hash: u128, f: F) -> Id
where
F: FnOnce() -> T,
{
*self.present.entry(hash).or_insert_with(|| {
let index = self.vec.len();
self.vec.push((hash, f()));
Id(self.kind, hash, index)
})
}
/// Iterate over the elements alongside their ids.
fn iter(&self) -> impl Iterator<Item = (Id, &T)> {
self.vec
.iter()
.enumerate()
.map(|(i, (id, v))| (Id(self.kind, *id, i), v))
}
/// Returns true if the deduplicator is empty.
fn is_empty(&self) -> bool {
self.vec.is_empty()
}
}
/// Identifies a `<def>`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
struct Id(char, u128, usize);
impl Display for Id {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}{:0X}", self.0, self.1)
}
}
/// Displays as an SVG matrix.
struct SvgMatrix(Transform);
impl Display for SvgMatrix {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
// Convert a [`Transform`] into a SVG transform string.
// See https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
write!(
f,
"matrix({} {} {} {} {} {})",
self.0.sx.get(),
self.0.ky.get(),
self.0.kx.get(),
self.0.sy.get(),
self.0.tx.to_pt(),
self.0.ty.to_pt()
)
}
}
/// A builder for SVG path using relative coordinates.
struct SvgPathBuilder {
pub path: EcoString,
pub scale: Ratio,
pub last_close_point: Point,
pub last_point: Point,
}
impl SvgPathBuilder {
fn with_translate(pos: Point) -> Self {
// add initial M node to transform the entire path
Self {
path: EcoString::from(format!("M {} {}", pos.x.to_pt(), pos.y.to_pt())),
scale: Ratio::one(),
last_close_point: pos,
last_point: Point::zero(),
}
}
fn with_scale(scale: Ratio) -> Self {
Self {
path: EcoString::from("M 0 0"),
scale,
last_close_point: Point::zero(),
last_point: Point::zero(),
}
}
fn scale(&self) -> f32 {
self.scale.get() as f32
}
fn set_point(&mut self, x: f32, y: f32) {
let point = Point::new(
Abs::pt(f64::from(x * self.scale())),
Abs::pt(f64::from(y * self.scale())),
);
self.last_point = point;
}
fn map_x(&self, x: f32) -> f32 {
x * self.scale() - self.last_point.x.to_pt() as f32
}
fn map_y(&self, y: f32) -> f32 {
y * self.scale() - self.last_point.y.to_pt() as f32
}
/// Create a rectangle path. The rectangle is created with the top-left
/// corner at (0, 0). The width and height are the size of the rectangle.
fn rect(&mut self, width: f32, height: f32) {
self.move_to(0.0, 0.0);
self.line_to(0.0, height);
self.line_to(width, height);
self.line_to(width, 0.0);
self.close();
}
/// Creates an arc path.
fn arc(
&mut self,
radius: (f32, f32),
x_axis_rot: f32,
large_arc_flag: u32,
sweep_flag: u32,
pos: (f32, f32),
) {
let rx = self.map_x(radius.0);
let ry = self.map_y(radius.1);
let x = self.map_x(pos.0);
let y = self.map_y(pos.1);
write!(
&mut self.path,
"a {rx} {ry} {x_axis_rot} {large_arc_flag} {sweep_flag} {x} {y} "
)
.unwrap();
self.set_point(x, y);
}
fn move_to(&mut self, x: f32, y: f32) {
let _x = self.map_x(x);
let _y = self.map_y(y);
if _x != 0.0 || _y != 0.0 {
write!(&mut self.path, "m {_x} {_y} ").unwrap();
}
self.set_point(x, y);
self.last_close_point = self.last_point;
}
fn line_to(&mut self, x: f32, y: f32) {
let _x = self.map_x(x);
let _y = self.map_y(y);
if _x != 0.0 && _y != 0.0 {
write!(&mut self.path, "l {_x} {_y} ").unwrap();
} else if _x != 0.0 {
write!(&mut self.path, "h {_x} ").unwrap();
} else if _y != 0.0 {
write!(&mut self.path, "v {_y} ").unwrap();
}
self.set_point(x, y);
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
let curve = format!(
"c {} {} {} {} {} {} ",
self.map_x(x1),
self.map_y(y1),
self.map_x(x2),
self.map_y(y2),
self.map_x(x),
self.map_y(y)
);
write!(&mut self.path, "{curve}").unwrap();
self.set_point(x, y);
}
fn close(&mut self) {
write!(&mut self.path, "Z ").unwrap();
self.last_point = self.last_close_point;
}
}
/// A builder for SVG path. This is used to build the path for a glyph.
impl ttf_parser::OutlineBuilder for SvgPathBuilder {
fn move_to(&mut self, x: f32, y: f32) {
self.move_to(x, y);
}
fn line_to(&mut self, x: f32, y: f32) {
self.line_to(x, y);
}
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
let _x1 = self.map_x(x1);
let _y1 = self.map_y(y1);
let _x = self.map_x(x);
let _y = self.map_y(y);
write!(&mut self.path, "q {_x1} {_y1} {_x} {_y} ").unwrap();
self.set_point(x, y);
}
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
self.curve_to(x1, y1, x2, y2, x, y);
}
fn close(&mut self) {
self.close();
}
}
impl Default for SvgPathBuilder {
fn default() -> Self {
Self {
path: Default::default(),
scale: Ratio::one(),
last_close_point: Point::zero(),
last_point: Point::zero(),
}
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-svg/src/image.rs | crates/typst-svg/src/image.rs | use std::sync::Arc;
use base64::Engine;
use ecow::{EcoString, eco_format};
use hayro::{FontData, FontQuery, InterpreterSettings, 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, PdfImage, RasterFormat,
};
use crate::{SVGRenderer, State, SvgMatrix};
impl SVGRenderer<'_> {
/// Render an image element.
pub(super) fn render_image(
&mut self,
state: &State,
image: &Image,
size: &Axes<Abs>,
) {
let url = convert_image_to_base64_url(image);
self.xml.start_element("image");
if !state.transform.is_identity() {
self.xml.write_attribute("transform", &SvgMatrix(state.transform));
}
self.xml.write_attribute("xlink:href", &url);
self.xml.write_attribute("width", &size.x.to_pt());
self.xml.write_attribute("height", &size.y.to_pt());
self.xml.write_attribute("preserveAspectRatio", "none");
if let Some(value) = convert_image_scaling(image.scaling()) {
self.xml
.write_attribute("style", &format_args!("image-rendering: {value}"))
}
self.xml.end_element();
}
}
/// Converts an image scaling to a CSS `image-rendering` property value.
pub fn convert_image_scaling(scaling: Smart<ImageScaling>) -> Option<&'static str> {
match scaling {
Smart::Auto => None,
Smart::Custom(ImageScaling::Smooth) => {
// This is still experimental and not implemented in all major browsers.
// https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering#browser_compatibility
Some("smooth")
}
Smart::Custom(ImageScaling::Pixelated) => Some("pixelated"),
}
}
/// Encode an image into a data URL. The format of the URL is
/// `data:image/{format};base64,`.
#[comemo::memoize]
pub fn convert_image_to_base64_url(image: &Image) -> EcoString {
let (mut buf, strbuf);
let (format, data): (&str, &[u8]) = match image.kind() {
ImageKind::Raster(raster) => match raster.format() {
RasterFormat::Exchange(format) => (
match format {
ExchangeFormat::Png => "png",
ExchangeFormat::Jpg => "jpeg",
ExchangeFormat::Gif => "gif",
ExchangeFormat::Webp => "webp",
},
raster.data(),
),
RasterFormat::Pixel(_) => ("png", {
buf = vec![];
let mut encoder = PngEncoder::new(&mut buf);
if let Some(icc_profile) = raster.icc() {
encoder.set_icc_profile(icc_profile.to_vec()).ok();
}
raster.dynamic().write_with_encoder(encoder).unwrap();
buf.as_slice()
}),
},
ImageKind::Svg(svg) => ("svg+xml", svg.data()),
ImageKind::Pdf(pdf) => {
strbuf = pdf_to_svg(pdf);
("svg+xml", strbuf.as_bytes())
}
};
let mut url = eco_format!("data:image/{format};base64,");
let data = base64::engine::general_purpose::STANDARD.encode(data);
url.push_str(&data);
url
}
// Keep this in sync with `typst-png`!
fn pdf_to_svg(pdf: &PdfImage) -> String {
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(|_| {}),
};
hayro_svg::convert(pdf.page(), &interpreter_settings)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-svg/src/text.rs | crates/typst-svg/src/text.rs | use std::io::Read;
use base64::Engine;
use ecow::EcoString;
use ttf_parser::GlyphId;
use typst_library::foundations::Bytes;
use typst_library::layout::{Abs, Point, Ratio, Size, Transform};
use typst_library::text::color::colr_glyph_to_svg;
use typst_library::text::{Font, TextItem};
use typst_library::visualize::{
ExchangeFormat, FillRule, Image, Paint, RasterImage, RelativeTo,
};
use typst_utils::hash128;
use crate::{SVGRenderer, State, SvgMatrix, SvgPathBuilder};
impl SVGRenderer<'_> {
/// Render a text item. The text is rendered as a group of glyphs. We will
/// try to render the text as SVG first, then bitmap, then outline. If none
/// of them works, we will skip the text.
pub(super) fn render_text(&mut self, state: &State, text: &TextItem) {
let scale: f64 = text.size.to_pt() / text.font.units_per_em();
self.xml.start_element("g");
self.xml.write_attribute("class", "typst-text");
self.xml.write_attribute(
"transform",
&format!(
"{}",
&SvgMatrix(
state
.transform
.pre_concat(Transform::scale(Ratio::new(1.0), Ratio::new(-1.0)))
)
),
);
let mut x: f64 = 0.0;
let mut y: f64 = 0.0;
for glyph in &text.glyphs {
let id = GlyphId(glyph.id);
let x_offset = x + glyph.x_offset.at(text.size).to_pt();
let y_offset = y + glyph.y_offset.at(text.size).to_pt();
self.render_colr_glyph(text, id, x_offset, y_offset, scale)
.or_else(|| self.render_svg_glyph(text, id, x_offset, y_offset, scale))
.or_else(|| self.render_bitmap_glyph(text, id, x_offset, y_offset))
.or_else(|| {
self.render_outline_glyph(
state
.pre_concat(Transform::scale(Ratio::one(), -Ratio::one()))
.pre_translate(Point::new(
Abs::pt(x_offset),
Abs::pt(y_offset),
)),
text,
id,
x_offset,
y_offset,
scale,
)
});
x += glyph.x_advance.at(text.size).to_pt();
y += glyph.y_advance.at(text.size).to_pt();
}
self.xml.end_element();
}
/// Render a glyph defined by an SVG.
fn render_svg_glyph(
&mut self,
text: &TextItem,
id: GlyphId,
x_offset: f64,
y_offset: f64,
scale: f64,
) -> Option<()> {
let data_url = convert_svg_glyph_to_base64_url(&text.font, id)?;
let upem = text.font.units_per_em();
let origin_ascender = text.font.metrics().ascender.at(Abs::pt(upem));
let glyph_hash = hash128(&(&text.font, id));
let id = self.glyphs.insert_with(glyph_hash, || RenderedGlyph::Image {
url: data_url,
width: upem,
height: upem,
ts: Transform::translate(Abs::zero(), -origin_ascender)
.post_concat(Transform::scale(Ratio::new(scale), Ratio::new(-scale))),
});
self.xml.start_element("use");
self.xml.write_attribute_fmt("xlink:href", format_args!("#{id}"));
self.xml.write_attribute("x", &x_offset);
self.xml.write_attribute("y", &y_offset);
self.xml.end_element();
Some(())
}
/// Render a glyph defined by COLR glyph descriptions.
fn render_colr_glyph(
&mut self,
text: &TextItem,
id: GlyphId,
x_offset: f64,
y_offset: f64,
scale: f64,
) -> Option<()> {
let ttf = text.font.ttf();
let converted = colr_glyph_to_svg(&text.font, id)?;
let width = ttf.global_bounding_box().width() as f64;
let height = ttf.global_bounding_box().height() as f64;
let data_url = svg_to_base64(&converted);
let x_min = ttf.global_bounding_box().x_min as f64;
let y_max = ttf.global_bounding_box().y_max as f64;
let glyph_hash = hash128(&(&text.font, id));
let id = self.glyphs.insert_with(glyph_hash, || RenderedGlyph::Image {
url: data_url,
width,
height,
ts: Transform::scale(Ratio::new(scale), Ratio::new(-scale))
.pre_concat(Transform::translate(Abs::pt(x_min), -Abs::pt(y_max))),
});
self.xml.start_element("use");
self.xml.write_attribute_fmt("xlink:href", format_args!("#{id}"));
self.xml.write_attribute("x", &(x_offset));
self.xml.write_attribute("y", &(y_offset));
self.xml.end_element();
Some(())
}
/// Render a glyph defined by a bitmap.
fn render_bitmap_glyph(
&mut self,
text: &TextItem,
id: GlyphId,
x_offset: f64,
y_offset: f64,
) -> Option<()> {
let (image, bitmap_x_offset, bitmap_y_offset) =
convert_bitmap_glyph_to_image(&text.font, id)?;
let glyph_hash = hash128(&(&text.font, id));
let id = self.glyphs.insert_with(glyph_hash, || {
let width = image.width();
let height = image.height();
let url = crate::image::convert_image_to_base64_url(&image);
let ts = Transform::translate(
Abs::pt(bitmap_x_offset),
Abs::pt(-height - bitmap_y_offset),
);
RenderedGlyph::Image { url, width, height, ts }
});
let target_height = text.size.to_pt();
self.xml.start_element("use");
self.xml.write_attribute_fmt("xlink:href", format_args!("#{id}"));
// The image is stored with the height of `image.height()`, but we want
// to render it with a height of `target_height`. So we need to scale
// it.
let scale_factor = target_height / image.height();
self.xml.write_attribute("x", &(x_offset / scale_factor));
self.xml.write_attribute("y", &(y_offset / scale_factor));
self.xml.write_attribute_fmt(
"transform",
format_args!("scale({scale_factor} -{scale_factor})",),
);
self.xml.end_element();
Some(())
}
/// Render a glyph defined by an outline.
fn render_outline_glyph(
&mut self,
state: State,
text: &TextItem,
glyph_id: GlyphId,
x_offset: f64,
y_offset: f64,
scale: f64,
) -> Option<()> {
let scale = Ratio::new(scale);
let path = convert_outline_glyph_to_path(&text.font, glyph_id, scale)?;
let hash = hash128(&(&text.font, glyph_id, scale));
let id = self.glyphs.insert_with(hash, || RenderedGlyph::Path(path));
let glyph_size = text.font.ttf().glyph_bounding_box(glyph_id)?;
let width = glyph_size.width() as f64 * scale.get();
let height = glyph_size.height() as f64 * scale.get();
self.xml.start_element("use");
self.xml.write_attribute_fmt("xlink:href", format_args!("#{id}"));
self.xml.write_attribute_fmt("x", format_args!("{x_offset}"));
self.xml.write_attribute_fmt("y", format_args!("{y_offset}"));
self.write_fill(
&text.fill,
FillRule::default(),
Size::new(Abs::pt(width), Abs::pt(height)),
self.text_paint_transform(state, &text.fill),
);
if let Some(stroke) = &text.stroke {
self.write_stroke(
stroke,
Size::new(Abs::pt(width), Abs::pt(height)),
self.text_paint_transform(state, &stroke.paint),
);
}
self.xml.end_element();
Some(())
}
fn text_paint_transform(&self, state: State, paint: &Paint) -> Transform {
match paint {
Paint::Solid(_) => Transform::identity(),
Paint::Gradient(gradient) => match gradient.unwrap_relative(true) {
RelativeTo::Self_ => Transform::identity(),
RelativeTo::Parent => Transform::scale(
Ratio::new(state.size.x.to_pt()),
Ratio::new(state.size.y.to_pt()),
)
.post_concat(state.transform.invert().unwrap()),
},
Paint::Tiling(tiling) => match tiling.unwrap_relative(true) {
RelativeTo::Self_ => Transform::identity(),
RelativeTo::Parent => state.transform.invert().unwrap(),
},
}
}
/// Build the glyph definitions.
pub(super) fn write_glyph_defs(&mut self) {
if self.glyphs.is_empty() {
return;
}
self.xml.start_element("defs");
self.xml.write_attribute("id", "glyph");
for (id, glyph) in self.glyphs.iter() {
self.xml.start_element("symbol");
self.xml.write_attribute("id", &id);
self.xml.write_attribute("overflow", "visible");
match glyph {
RenderedGlyph::Path(path) => {
self.xml.start_element("path");
self.xml.write_attribute("d", &path);
self.xml.end_element();
}
RenderedGlyph::Image { url, width, height, ts } => {
self.xml.start_element("image");
self.xml.write_attribute("xlink:href", &url);
self.xml.write_attribute("width", &width);
self.xml.write_attribute("height", &height);
if !ts.is_identity() {
self.xml.write_attribute("transform", &SvgMatrix(*ts));
}
self.xml.write_attribute("preserveAspectRatio", "none");
self.xml.end_element();
}
}
self.xml.end_element();
}
self.xml.end_element();
}
}
/// Represents a glyph to be rendered.
pub enum RenderedGlyph {
/// A path is a sequence of drawing commands.
///
/// It is in the format of `M x y L x y C x1 y1 x2 y2 x y Z`.
Path(EcoString),
/// An image is a URL to an image file, plus the size and transform.
///
/// The url is in the format of `data:image/{format};base64,`.
Image { url: EcoString, width: f64, height: f64, ts: Transform },
}
/// Convert an outline glyph to an SVG path.
#[comemo::memoize]
fn convert_outline_glyph_to_path(
font: &Font,
id: GlyphId,
scale: Ratio,
) -> Option<EcoString> {
let mut builder = SvgPathBuilder::with_scale(scale);
font.ttf().outline_glyph(id, &mut builder)?;
Some(builder.path)
}
/// Convert a bitmap glyph to an encoded image URL.
#[comemo::memoize]
fn convert_bitmap_glyph_to_image(font: &Font, id: GlyphId) -> Option<(Image, f64, f64)> {
let raster = font.ttf().glyph_raster_image(id, u16::MAX)?;
if raster.format != ttf_parser::RasterImageFormat::PNG {
return None;
}
let image = Image::plain(
RasterImage::plain(Bytes::new(raster.data.to_vec()), ExchangeFormat::Png).ok()?,
);
Some((image, raster.x as f64, raster.y as f64))
}
/// Convert an SVG glyph to an encoded image URL.
#[comemo::memoize]
fn convert_svg_glyph_to_base64_url(font: &Font, id: GlyphId) -> Option<EcoString> {
let mut data = font.ttf().glyph_svg_image(id)?.data;
// Decompress SVGZ.
let mut decoded = vec![];
if data.starts_with(&[0x1f, 0x8b]) {
let mut decoder = flate2::read::GzDecoder::new(data);
decoder.read_to_end(&mut decoded).ok()?;
data = &decoded;
}
let upem = font.units_per_em();
let width = upem;
let height = upem;
let origin_ascender = font.metrics().ascender.at(Abs::pt(upem));
// Parse XML.
let mut svg_str = std::str::from_utf8(data).ok()?.to_owned();
let mut start_span = None;
let mut last_viewbox = None;
// Parse xml and find the viewBox of the svg element.
// <svg viewBox="0 0 1000 1000">...</svg>
// ~~~~~^~~~~~~
for n in xmlparser::Tokenizer::from(svg_str.as_str()) {
let tok = n.unwrap();
match tok {
xmlparser::Token::ElementStart { span, local, .. } => {
if local.as_str() == "svg" {
start_span = Some(span);
break;
}
}
xmlparser::Token::Attribute { span, local, value, .. } => {
if local.as_str() == "viewBox" {
last_viewbox = Some((span, value));
}
}
xmlparser::Token::ElementEnd { .. } => break,
_ => {}
}
}
if last_viewbox.is_none() {
// Correct the viewbox if it is not present. `-origin_ascender` is to
// make sure the glyph is rendered at the correct position
svg_str.insert_str(
start_span.unwrap().range().end,
format!(r#" viewBox="0 {} {width} {height}""#, -origin_ascender.to_pt())
.as_str(),
);
}
Some(svg_to_base64(&svg_str))
}
fn svg_to_base64(svg_str: &str) -> EcoString {
let mut url: EcoString = "data:image/svg+xml;base64,".into();
let b64_encoded =
base64::engine::general_purpose::STANDARD.encode(svg_str.as_bytes());
url.push_str(&b64_encoded);
url
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/complete.rs | crates/typst-ide/src/complete.rs | use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::ffi::OsStr;
use ecow::{EcoString, eco_format};
use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize};
use typst::foundations::{
AutoValue, CastInfo, Func, Label, NativeElement, NoneValue, ParamInfo, Repr,
StyleChain, Styles, Type, Value, fields_on, repr,
};
use typst::layout::{Alignment, Dir};
use typst::syntax::ast::AstNode;
use typst::syntax::{
FileId, LinkedNode, Side, Source, SyntaxKind, ast, is_id_continue, is_id_start,
is_ident,
};
use typst::text::{FontFlags, RawElem};
use typst::visualize::Color;
use typst::{AsDocument, Document};
use unscanny::Scanner;
use crate::utils::{
check_value_recursively, globals, plain_docs_sentence, summarize_font_family,
};
use crate::{IdeWorld, analyze_expr, analyze_import, analyze_labels, named_items};
/// Autocomplete a cursor position in a source file.
///
/// Returns the position from which the completions apply and a list of
/// completions.
///
/// When `explicit` is `true`, the user requested the completion by pressing
/// control and space or something similar.
///
/// Passing a `document` (from a previous compilation) is optional, but enhances
/// the autocompletions. Label completions, for instance, are only generated
/// when the document is available.
pub fn autocomplete(
world: &dyn IdeWorld,
document: Option<impl AsDocument>,
source: &Source,
cursor: usize,
explicit: bool,
) -> Option<(usize, Vec<Completion>)> {
let leaf = LinkedNode::new(source.root()).leaf_at(cursor, Side::Before)?;
let mut ctx = CompletionContext::new(
world,
document.as_ref().map(|v| v.as_document()),
source,
&leaf,
cursor,
explicit,
)?;
let _ = complete_comments(&mut ctx)
|| complete_field_accesses(&mut ctx)
|| complete_open_labels(&mut ctx)
|| complete_imports(&mut ctx)
|| complete_rules(&mut ctx)
|| complete_params(&mut ctx)
|| complete_markup(&mut ctx)
|| complete_math(&mut ctx)
|| complete_code(&mut ctx);
Some((ctx.from, ctx.completions))
}
/// An autocompletion option.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Completion {
/// The kind of item this completes to.
pub kind: CompletionKind,
/// The label the completion is shown with.
pub label: EcoString,
/// The completed version of the input, possibly described with snippet
/// syntax like `${lhs} + ${rhs}`.
///
/// Should default to the `label` if `None`.
pub apply: Option<EcoString>,
/// An optional short description, at most one sentence.
pub detail: Option<EcoString>,
}
/// A kind of item that can be completed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CompletionKind {
/// A syntactical structure.
Syntax,
/// A function.
Func,
/// A type.
Type,
/// A function parameter.
Param,
/// A constant.
Constant,
/// A file path.
Path,
/// A package.
Package,
/// A label.
Label,
/// A font family.
Font,
/// A symbol.
Symbol(EcoString),
}
/// Complete in comments. Or rather, don't!
fn complete_comments(ctx: &mut CompletionContext) -> bool {
matches!(ctx.leaf.kind(), SyntaxKind::LineComment | SyntaxKind::BlockComment)
}
/// Complete in markup mode.
fn complete_markup(ctx: &mut CompletionContext) -> bool {
// Bail if we aren't even in markup.
if !matches!(
ctx.leaf.parent_kind(),
None | Some(SyntaxKind::Markup) | Some(SyntaxKind::Ref)
) {
return false;
}
// Start of an interpolated identifier: "#|".
if ctx.leaf.kind() == SyntaxKind::Hash {
ctx.from = ctx.cursor;
code_completions(ctx, true);
return true;
}
// An existing identifier: "#pa|".
if ctx.leaf.kind() == SyntaxKind::Ident {
ctx.from = ctx.leaf.offset();
code_completions(ctx, true);
return true;
}
// Start of a reference: "@|".
if ctx.leaf.kind() == SyntaxKind::Text && ctx.before.ends_with("@") {
ctx.from = ctx.cursor;
ctx.label_completions();
return true;
}
// An existing reference: "@he|".
if ctx.leaf.kind() == SyntaxKind::RefMarker {
ctx.from = ctx.leaf.offset() + 1;
ctx.label_completions();
return true;
}
// Behind a half-completed binding: "#let x = |".
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 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);
s.jump(ctx.leaf.offset());
if s.eat_if("```") {
s.eat_while('`');
let start = s.cursor();
if s.eat_if(is_id_start) {
s.eat_while(is_id_continue);
}
if s.cursor() == ctx.cursor {
ctx.from = start;
ctx.raw_completions();
}
return true;
}
// Anywhere: "|".
if ctx.explicit {
ctx.from = ctx.cursor;
markup_completions(ctx);
return true;
}
false
}
/// Add completions for markup snippets.
#[rustfmt::skip]
fn markup_completions(ctx: &mut CompletionContext) {
ctx.snippet_completion(
"expression",
"#${}",
"Variables, function calls, blocks, and more.",
);
ctx.snippet_completion(
"linebreak",
"\\\n${}",
"Inserts a forced linebreak.",
);
ctx.snippet_completion(
"strong text",
"*${strong}*",
"Strongly emphasizes content by increasing the font weight.",
);
ctx.snippet_completion(
"emphasized text",
"_${emphasized}_",
"Emphasizes content by setting it in italic font style.",
);
ctx.snippet_completion(
"raw text",
"`${text}`",
"Displays text verbatim, in monospace.",
);
ctx.snippet_completion(
"code listing",
"```${lang}\n${code}\n```",
"Inserts computer code with syntax highlighting.",
);
ctx.snippet_completion(
"hyperlink",
"https://${example.com}",
"Links to a URL.",
);
ctx.snippet_completion(
"label",
"<${name}>",
"Makes the preceding element referenceable.",
);
ctx.snippet_completion(
"reference",
"@${name}",
"Inserts a reference to a label.",
);
ctx.snippet_completion(
"heading",
"= ${title}",
"Inserts a section heading.",
);
ctx.snippet_completion(
"list item",
"- ${item}",
"Inserts an item of a bullet list.",
);
ctx.snippet_completion(
"enumeration item",
"+ ${item}",
"Inserts an item of a numbered list.",
);
ctx.snippet_completion(
"enumeration item (numbered)",
"${number}. ${item}",
"Inserts an explicitly numbered list item.",
);
ctx.snippet_completion(
"term list item",
"/ ${term}: ${description}",
"Inserts an item of a term list.",
);
ctx.snippet_completion(
"math (inline)",
"$${x}$",
"Inserts an inline-level mathematical equation.",
);
ctx.snippet_completion(
"math (block)",
"$ ${sum_x^2} $",
"Inserts a block-level mathematical equation.",
);
}
/// Complete in math mode.
fn complete_math(ctx: &mut CompletionContext) -> bool {
if !matches!(
ctx.leaf.parent_kind(),
Some(SyntaxKind::Equation)
| Some(SyntaxKind::Math)
| Some(SyntaxKind::MathFrac)
| Some(SyntaxKind::MathAttach)
) {
return false;
}
// Start of an interpolated identifier: "$#|$".
if ctx.leaf.kind() == SyntaxKind::Hash {
ctx.from = ctx.cursor;
code_completions(ctx, true);
return true;
}
// Behind existing interpolated identifier: "$#pa|$".
if ctx.leaf.kind() == SyntaxKind::Ident {
ctx.from = ctx.leaf.offset();
code_completions(ctx, true);
return true;
}
// Behind existing atom or identifier: "$a|$" or "$abc|$".
if matches!(
ctx.leaf.kind(),
SyntaxKind::Text | SyntaxKind::MathText | SyntaxKind::MathIdent
) {
ctx.from = ctx.leaf.offset();
math_completions(ctx);
return true;
}
// Anywhere: "$|$".
if ctx.explicit {
ctx.from = ctx.cursor;
math_completions(ctx);
return true;
}
false
}
/// Add completions for math snippets.
#[rustfmt::skip]
fn math_completions(ctx: &mut CompletionContext) {
ctx.scope_completions(true, |_| true);
ctx.snippet_completion(
"subscript",
"${x}_${2:2}",
"Sets something in subscript.",
);
ctx.snippet_completion(
"superscript",
"${x}^${2:2}",
"Sets something in superscript.",
);
ctx.snippet_completion(
"fraction",
"${x}/${y}",
"Inserts a fraction.",
);
}
/// Complete field accesses.
fn complete_field_accesses(ctx: &mut CompletionContext) -> bool {
// Used to determine whether trivia nodes are allowed before '.'.
// During an inline expression in markup mode trivia nodes exit the inline expression.
let in_markup: bool = matches!(
ctx.leaf.parent_kind(),
None | Some(SyntaxKind::Markup) | Some(SyntaxKind::Ref)
);
// Behind an expression plus dot: "emoji.|".
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::<ast::Expr>()
&& (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 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::<ast::Expr>()
&& 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
}
/// Add completions for all fields on a value.
fn field_access_completions(
ctx: &mut CompletionContext,
value: &Value,
styles: &Option<Styles>,
) {
let scopes = {
let ty = value.ty().scope();
let elem = match value {
Value::Content(content) => Some(content.elem().scope()),
_ => None,
};
elem.into_iter().chain(Some(ty))
};
// Autocomplete methods from the element's or type's scope. We only complete
// those which have a `self` parameter.
for (name, binding) in scopes.flat_map(|scope| scope.iter()) {
let Ok(func) = binding.read().clone().cast::<Func>() else { continue };
if func
.params()
.and_then(|params| params.first())
.is_some_and(|param| param.name == "self")
{
ctx.call_completion(name.clone(), binding.read());
}
}
if let Some(scope) = value.scope() {
for (name, binding) in scope.iter() {
ctx.call_completion(name.clone(), binding.read());
}
}
for &field in fields_on(value.ty()) {
// Complete the field name along with its value. Notes:
// 1. No parentheses since function fields cannot currently be called
// with method syntax;
// 2. We can unwrap the field's value since it's a field belonging to
// this value's type, so accessing it should not fail.
ctx.value_completion(field, &value.field(field, ()).unwrap());
}
match value {
Value::Symbol(symbol) => {
for modifier in symbol.modifiers() {
if let Ok(modified) = symbol.clone().modified((), modifier) {
ctx.completions.push(Completion {
kind: CompletionKind::Symbol(modified.get().into()),
label: modifier.into(),
apply: None,
detail: None,
});
}
}
}
Value::Content(content) => {
for (name, value) in content.fields() {
ctx.value_completion(name, &value);
}
}
Value::Dict(dict) => {
for (name, value) in dict.iter() {
ctx.value_completion(name.clone(), value);
}
}
Value::Func(func) => {
// Autocomplete get rules.
if let Some((elem, styles)) = func.to_element().zip(styles.as_ref()) {
for param in elem.params().iter().filter(|param| !param.required) {
if let Some(value) = elem.field_id(param.name).and_then(|id| {
elem.field_from_styles(id, StyleChain::new(styles)).ok()
}) {
ctx.value_completion(param.name, &value);
}
}
}
}
_ => {}
}
}
/// Complete half-finished labels.
fn complete_open_labels(ctx: &mut CompletionContext) -> bool {
// A label anywhere in code: "(<la|".
if ctx.leaf.kind().is_error() && ctx.leaf.text().starts_with('<') {
ctx.from = ctx.leaf.offset() + 1;
ctx.label_completions();
return true;
}
false
}
/// Complete imports.
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()
&& 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;
}
// Behind an import list:
// "#import "path.typ": |",
// "#import "path.typ": a, b, |".
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::<ast::Expr>())
{
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
&& 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::<ast::Expr>())
{
ctx.from = ctx.leaf.offset();
import_item_completions(ctx, items, &source);
return true;
}
false
}
/// Add completions for all exports of a module.
fn import_item_completions<'a>(
ctx: &mut CompletionContext<'a>,
existing: ast::ImportItems<'a>,
source: &LinkedNode,
) {
let Some(value) = analyze_import(ctx.world, source) else { return };
let Some(scope) = value.scope() else { return };
if existing.iter().next().is_none() {
ctx.snippet_completion("*", "*", "Import everything.");
}
for (name, binding) in scope.iter() {
if existing.iter().all(|item| item.original_name().as_str() != name) {
ctx.value_completion(name.clone(), binding.read());
}
}
}
/// Complete set and show rules.
fn complete_rules(ctx: &mut CompletionContext) -> bool {
// We don't want to complete directly behind the keyword.
if !ctx.leaf.kind().is_trivia() {
return false;
}
let Some(prev) = ctx.leaf.prev_leaf() else { return false };
// Behind the set keyword: "set |".
if matches!(prev.kind(), SyntaxKind::Set) {
ctx.from = ctx.cursor;
set_rule_completions(ctx);
return true;
}
// Behind the show keyword: "show |".
if matches!(prev.kind(), SyntaxKind::Show) {
ctx.from = ctx.cursor;
show_rule_selector_completions(ctx);
return true;
}
// Behind a half-completed show rule: "show strong: |".
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
}
/// Add completions for all functions from the global scope.
fn set_rule_completions(ctx: &mut CompletionContext) {
ctx.scope_completions(true, |value| {
matches!(
value,
Value::Func(func) if func.params()
.unwrap_or_default()
.iter()
.any(|param| param.settable),
)
});
}
/// Add completions for selectors.
fn show_rule_selector_completions(ctx: &mut CompletionContext) {
ctx.scope_completions(
false,
|value| matches!(value, Value::Func(func) if func.to_element().is_some()),
);
ctx.enrich("", ": ");
ctx.snippet_completion(
"text selector",
"\"${text}\": ${}",
"Replace occurrences of specific text.",
);
ctx.snippet_completion(
"regex selector",
"regex(\"${regex}\"): ${}",
"Replace matches of a regular expression.",
);
}
/// Add completions for recipes.
fn show_rule_recipe_completions(ctx: &mut CompletionContext) {
ctx.snippet_completion(
"replacement",
"[${content}]",
"Replace the selected element with content.",
);
ctx.snippet_completion(
"replacement (string)",
"\"${text}\"",
"Replace the selected element with a string of text.",
);
ctx.snippet_completion(
"transformation",
"element => [${content}]",
"Transform the element with a function.",
);
ctx.scope_completions(false, |value| matches!(value, Value::Func(_)));
}
/// 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 Some(parent) = match parent.kind() {
SyntaxKind::Named => parent.parent(),
_ => Some(parent),
}
&& let Some(args) = parent.get().cast::<ast::Args>()
&& let Some(grand) = parent.parent()
&& let Some(expr) = grand.get().cast::<ast::Expr>()
&& 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,
} {
(callee, set, args, parent)
} else {
return false;
};
// Find the piece of syntax that decides what we're completing.
let mut deciding = ctx.leaf.clone();
while !matches!(
deciding.kind(),
SyntaxKind::LeftParen
| SyntaxKind::RightParen
| SyntaxKind::Comma
| SyntaxKind::Colon
) {
let Some(prev) = deciding.prev_leaf() else { break };
deciding = prev;
}
// Parameter values: "func(param:|)", "func(param: |)".
if let SyntaxKind::Colon = deciding.kind()
&& let Some(prev) = deciding.prev_leaf()
&& let Some(param) = prev.get().cast::<ast::Ident>()
{
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, |)", "func(12,|)" [explicit mode only]
if let SyntaxKind::LeftParen | SyntaxKind::Comma = deciding.kind()
&& (deciding.kind() != SyntaxKind::Comma
|| deciding.range().end < ctx.cursor
|| ctx.explicit)
{
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
}
/// Add completions for the parameters of a function.
fn param_completions<'a>(
ctx: &mut CompletionContext<'a>,
callee: ast::Expr<'a>,
set: bool,
args: ast::Args<'a>,
args_linked: &'a LinkedNode<'a>,
) {
let Some(func) = resolve_global_callee(ctx, callee) else { return };
let Some(params) = func.params() else { return };
// Determine which arguments are already present.
let mut existing_positional = 0;
let mut existing_named = FxHashSet::default();
for arg in args.items() {
match arg {
ast::Arg::Pos(_) => {
let Some(node) = args_linked.find(arg.span()) else { continue };
if node.range().end < ctx.cursor {
existing_positional += 1;
}
}
ast::Arg::Named(named) => {
existing_named.insert(named.name().as_str());
}
_ => {}
}
}
let mut skipped_positional = 0;
for param in params {
if set && !param.settable {
continue;
}
if param.positional {
if skipped_positional < existing_positional && !param.variadic {
skipped_positional += 1;
continue;
}
param_value_completions(ctx, func, param);
}
if param.named {
if existing_named.contains(¶m.name) {
continue;
}
let apply = if param.name == "caption" {
eco_format!("{}: [${{}}]", param.name)
} else {
eco_format!("{}: ${{}}", param.name)
};
ctx.completions.push(Completion {
kind: CompletionKind::Param,
label: param.name.into(),
apply: Some(apply),
detail: Some(plain_docs_sentence(param.docs)),
});
}
}
if ctx.before.ends_with(',') {
ctx.enrich(" ", "");
}
}
/// Add completions for the values of a named function parameter.
fn named_param_value_completions<'a>(
ctx: &mut CompletionContext<'a>,
callee: ast::Expr<'a>,
name: &str,
) {
let Some(func) = resolve_global_callee(ctx, callee) else { return };
let Some(param) = func.param(name) else { return };
if !param.named {
return;
}
param_value_completions(ctx, func, param);
if ctx.before.ends_with(':') {
ctx.enrich(" ", "");
}
}
/// Add completions for the values of a parameter.
fn param_value_completions<'a>(
ctx: &mut CompletionContext<'a>,
func: &Func,
param: &'a ParamInfo,
) {
if param.name == "font" {
ctx.font_completions();
} else if let Some(extensions) = path_completion(func, param) {
ctx.file_completions_with_extensions(extensions);
} else if func.name() == Some("figure") && param.name == "body" {
ctx.snippet_completion("image", "image(\"${}\"),", "An image in a figure.");
ctx.snippet_completion("table", "table(\n ${}\n),", "A table in a figure.");
}
ctx.cast_completions(¶m.input);
}
/// Returns which file extensions to complete for the given parameter if any.
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", "pdf"]
}
(Some("csv"), "source") => &["csv"],
(Some("plugin"), "source") => &["wasm"],
(Some("cbor"), "source") => &["cbor"],
(Some("json"), "source") => &["json"],
(Some("toml"), "source") => &["toml"],
(Some("xml"), "source") => &["xml"],
(Some("yaml"), "source") => &["yml", "yaml"],
(Some("bibliography"), "sources") => &["bib", "yml", "yaml"],
(Some("bibliography"), "style") => &["csl"],
(Some("cite"), "style") => &["csl"],
(Some("raw"), "syntaxes") => &["sublime-syntax"],
(Some("raw"), "theme") => &["tmtheme"],
(Some("embed"), "path") => &[],
(Some("attach"), "path") if *func == typst::pdf::AttachElem::ELEM => &[],
(None, "path") => &[],
_ => return None,
})
}
/// Resolve a callee expression to a global function.
fn resolve_global_callee<'a>(
ctx: &CompletionContext<'a>,
callee: ast::Expr<'a>,
) -> Option<&'a Func> {
let globals = globals(ctx.world, ctx.leaf);
let value = match callee {
ast::Expr::Ident(ident) => globals.get(&ident)?.read(),
ast::Expr::FieldAccess(access) => match access.target() {
ast::Expr::Ident(target) => {
globals.get(&target)?.read().scope()?.get(&access.field())?.read()
}
_ => return None,
},
_ => return None,
};
match value {
Value::Func(func) => Some(func),
_ => None,
}
}
/// Complete in code mode.
fn complete_code(ctx: &mut CompletionContext) -> bool {
if matches!(
ctx.leaf.parent_kind(),
None | Some(SyntaxKind::Markup)
| Some(SyntaxKind::Math)
| Some(SyntaxKind::MathFrac)
| Some(SyntaxKind::MathAttach)
| Some(SyntaxKind::MathRoot)
) {
return false;
}
// An existing identifier: "{ pa| }".
// Ignores named pair keys as they are not variables (as in "(pa|: 23)").
if ctx.leaf.kind() == SyntaxKind::Ident
&& (ctx.leaf.index() > 0 || ctx.leaf.parent_kind() != Some(SyntaxKind::Named))
{
ctx.from = ctx.leaf.offset();
code_completions(ctx, false);
return true;
}
// A potential label (only at the start of an argument list): "(<|".
if ctx.before.ends_with("(<") {
ctx.from = ctx.cursor;
ctx.label_completions();
return true;
}
// Anywhere: "{ | }", "(|)", "(1,|)", "(a:|)".
// But not within or after an expression, and also not part of a dictionary
// key (as in "(pa: |,)")
if ctx.explicit
&& ctx.leaf.parent_kind() != Some(SyntaxKind::Dict)
&& (ctx.leaf.kind().is_trivia()
|| matches!(
ctx.leaf.kind(),
SyntaxKind::LeftParen
| SyntaxKind::LeftBrace
| SyntaxKind::Comma
| SyntaxKind::Colon
))
{
ctx.from = ctx.cursor;
code_completions(ctx, false);
return true;
}
false
}
/// Add completions for expression snippets.
#[rustfmt::skip]
fn code_completions(ctx: &mut CompletionContext, hash: bool) {
if hash {
ctx.scope_completions(true, |value| {
// If we are in markup, ignore colors, directions, and alignments.
// They are useless and bloat the autocomplete results.
let ty = value.ty();
ty != Type::of::<Color>()
&& ty != Type::of::<Dir>()
&& ty != Type::of::<Alignment>()
});
} else {
ctx.scope_completions(true, |_| true);
}
ctx.snippet_completion(
"function call",
"${function}(${arguments})[${body}]",
"Evaluates a function.",
);
ctx.snippet_completion(
"code block",
"{ ${} }",
"Inserts a nested code block.",
);
ctx.snippet_completion(
"content block",
"[${content}]",
"Switches into markup mode.",
);
ctx.snippet_completion(
"set rule",
"set ${}",
"Sets style properties on an element.",
);
ctx.snippet_completion(
"show rule",
"show ${}",
"Redefines the look of an element.",
);
ctx.snippet_completion(
"show rule (everything)",
"show: ${}",
"Transforms everything that follows.",
);
ctx.snippet_completion(
"context expression",
"context ${}",
"Provides contextual data.",
);
ctx.snippet_completion(
"let binding",
"let ${name} = ${value}",
"Saves a value in a variable.",
);
ctx.snippet_completion(
"let binding (function)",
"let ${name}(${params}) = ${output}",
"Defines a function.",
);
ctx.snippet_completion(
"if conditional",
"if ${1 < 2} {\n\t${}\n}",
"Computes or inserts something conditionally.",
);
ctx.snippet_completion(
"if-else conditional",
"if ${1 < 2} {\n\t${}\n} else {\n\t${}\n}",
"Computes or inserts different things based on a condition.",
);
ctx.snippet_completion(
"while loop",
"while ${1 < 2} {\n\t${}\n}",
"Computes or inserts something while a condition is met.",
);
ctx.snippet_completion(
"for loop",
"for ${value} in ${(1, 2, 3)} {\n\t${}\n}",
"Computes or inserts something for each value in a collection.",
);
ctx.snippet_completion(
"for loop (with key)",
"for (${key}, ${value}) in ${(a: 1, b: 2)} {\n\t${}\n}",
"Computes or inserts something for each key and value in a collection.",
);
ctx.snippet_completion(
"break",
"break",
"Exits early from a loop.",
);
ctx.snippet_completion(
"continue",
"continue",
"Continues with the next iteration of a loop.",
);
ctx.snippet_completion(
"return",
"return ${output}",
"Returns early from a function.",
);
ctx.snippet_completion(
"import (file)",
"import \"${}\": ${}",
"Imports variables from another file.",
);
ctx.snippet_completion(
"import (package)",
"import \"@${}\": ${}",
"Imports variables from a package.",
);
ctx.snippet_completion(
"include (file)",
"include \"${}\"",
"Includes content from another file.",
);
ctx.snippet_completion(
"array literal",
"(${1, 2, 3})",
"Creates a sequence of values.",
);
ctx.snippet_completion(
"dictionary literal",
"(${a: 1, b: 2})",
"Creates a mapping from names to value.",
);
if !hash {
ctx.snippet_completion(
"function",
"(${params}) => ${output}",
"Creates an unnamed function.",
);
}
}
/// See if the AST node is somewhere within a show rule applying to equations
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::<ast::Expr>()
&& let ast::Expr::ShowRule(show) = expr
&& let Some(ast::Expr::FieldAccess(field)) = show.selector()
&& field.field().as_str() == "equation"
{
return true;
}
node = parent;
}
false
}
/// Context for autocompletion.
struct CompletionContext<'a> {
world: &'a (dyn IdeWorld + 'a),
document: Option<&'a dyn Document>,
text: &'a str,
before: &'a str,
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/analyze.rs | crates/typst-ide/src/analyze.rs | use comemo::Track;
use ecow::{EcoString, EcoVec, eco_vec};
use rustc_hash::FxHashSet;
use typst::AsDocument;
use typst::foundations::{Label, Styles, Value};
use typst::layout::PagedDocument;
use typst::model::{BibliographyElem, FigureElem};
use typst::syntax::{LinkedNode, SyntaxKind, ast};
use crate::IdeWorld;
/// Try to determine a set of possible values for an expression.
pub fn analyze_expr(
world: &dyn IdeWorld,
node: &LinkedNode,
) -> EcoVec<(Value, Option<Styles>)> {
let Some(expr) = node.cast::<ast::Expr>() else {
return eco_vec![];
};
let val = match expr {
ast::Expr::None(_) => Value::None,
ast::Expr::Auto(_) => Value::Auto,
ast::Expr::Bool(v) => Value::Bool(v.get()),
ast::Expr::Int(v) => Value::Int(v.get()),
ast::Expr::Float(v) => Value::Float(v.get()),
ast::Expr::Numeric(v) => Value::numeric(v.get()),
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);
}
if let Some(parent) = node.parent()
&& parent.kind() == SyntaxKind::FieldAccess
&& node.index() > 0
{
return analyze_expr(world, parent);
}
return typst::trace::<PagedDocument>(world.upcast(), node.span());
}
};
eco_vec![(val, None)]
}
/// Tries to load a module from the given `source` node.
pub fn analyze_import(world: &dyn IdeWorld, source: &LinkedNode) -> Option<Value> {
// Use span in the node for resolving imports with relative paths.
let source_span = source.span();
let (source, _) = analyze_expr(world, source).into_iter().next()?;
if source.scope().is_some() {
return Some(source);
}
let Value::Str(path) = source else { return None };
crate::utils::with_engine(world, |engine| {
typst_eval::import(engine, &path, source_span).ok().map(Value::Module)
})
}
/// Find all labels and details for them.
///
/// Returns:
/// - All labels and descriptions for them, if available
/// - A split offset: All labels before this offset belong to nodes, all after
/// belong to a bibliography.
///
/// Note: When multiple labels in the document have the same identifier,
/// this only returns the first one.
pub fn analyze_labels(
document: impl AsDocument,
) -> (Vec<(Label, Option<EcoString>)>, usize) {
let introspector = document.as_document().introspector();
let mut output = vec![];
let mut seen_labels = FxHashSet::default();
// Labels in the document.
for elem in introspector.all() {
let Some(label) = elem.label() else { continue };
if !seen_labels.insert(label) {
continue;
}
let details = elem
.to_packed::<FigureElem>()
.and_then(|figure| match figure.caption.as_option() {
Some(Some(caption)) => Some(caption.pack_ref()),
_ => None,
})
.unwrap_or(elem)
.get_by_name("body")
.ok()
.and_then(|field| match field {
Value::Content(content) => Some(content),
_ => None,
})
.as_ref()
.unwrap_or(elem)
.plain_text();
output.push((label, Some(details)));
}
let split = output.len();
// Bibliography keys.
output.extend(BibliographyElem::keys(introspector.track()));
(output, split)
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/lib.rs | crates/typst-ide/src/lib.rs | //! Capabilities for Typst IDE support.
mod analyze;
mod complete;
mod definition;
mod jump;
mod matchers;
mod tooltip;
mod utils;
pub use self::analyze::{analyze_expr, analyze_import, analyze_labels};
pub use self::complete::{Completion, CompletionKind, autocomplete};
pub use self::definition::{Definition, definition};
pub use self::jump::{Jump, jump_from_click, jump_from_click_in_frame, jump_from_cursor};
pub use self::matchers::{DerefTarget, NamedItem, deref_target, named_items};
pub use self::tooltip::{Tooltip, tooltip};
use ecow::EcoString;
use typst::World;
use typst::syntax::FileId;
use typst::syntax::package::PackageSpec;
/// Extends the `World` for IDE functionality.
pub trait IdeWorld: World {
/// Turn this into a normal [`World`].
///
/// This is necessary because trait upcasting is experimental in Rust.
/// See <https://github.com/rust-lang/rust/issues/65991>.
///
/// Implementors can simply return `self`.
fn upcast(&self) -> &dyn World;
/// A list of all available packages and optionally descriptions for them.
///
/// This function is **optional** to implement. It enhances the user
/// experience by enabling autocompletion for packages. Details about
/// packages from the `@preview` namespace are available from
/// `https://packages.typst.org/preview/index.json`.
fn packages(&self) -> &[(PackageSpec, Option<EcoString>)] {
&[]
}
/// Returns a list of all known files.
///
/// This function is **optional** to implement. It enhances the user
/// experience by enabling autocompletion for file paths.
fn files(&self) -> Vec<FileId> {
vec![]
}
}
#[cfg(test)]
mod tests;
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/tests.rs | crates/typst-ide/src/tests.rs | use std::borrow::Borrow;
use std::sync::Arc;
use ecow::EcoString;
use rustc_hash::FxHashMap;
use typst::diag::{FileError, FileResult};
use typst::foundations::{Bytes, Datetime, Smart};
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::{LazyHash, singleton};
use typst::{Feature, Library, LibraryExt, World};
use crate::IdeWorld;
/// A world for IDE testing.
#[derive(Clone)]
pub struct TestWorld {
pub main: Source,
files: Arc<TestFiles>,
base: &'static TestBase,
}
impl TestWorld {
/// Create a new world for a single test.
///
/// This is cheap because the shared base for all test runs is lazily
/// initialized just once.
pub fn new(text: &str) -> Self {
let main = Source::new(Self::main_id(), text.into());
Self {
main,
files: Arc::new(TestFiles::default()),
base: singleton!(TestBase, TestBase::default()),
}
}
/// Add an additional source file to the test world.
pub fn with_source(mut self, path: &str, text: &str) -> Self {
let id = FileId::new(None, VirtualPath::new(path));
let source = Source::new(id, text.into());
Arc::make_mut(&mut self.files).sources.insert(id, source);
self
}
/// Add an additional asset file to the test world.
#[track_caller]
pub fn with_asset(self, filename: &str) -> Self {
self.with_asset_at(filename, filename)
}
/// Add an additional asset file to the test world.
#[track_caller]
pub fn with_asset_at(mut self, path: &str, filename: &str) -> Self {
let id = FileId::new(None, VirtualPath::new(path));
let data = typst_dev_assets::get_by_name(filename).unwrap();
let bytes = Bytes::new(data);
Arc::make_mut(&mut self.files).assets.insert(id, bytes);
self
}
/// The ID of the main file in a `TestWorld`.
pub fn main_id() -> FileId {
*singleton!(FileId, FileId::new(None, VirtualPath::new("main.typ")))
}
}
impl World for TestWorld {
fn library(&self) -> &LazyHash<Library> {
&self.base.library
}
fn book(&self) -> &LazyHash<FontBook> {
&self.base.book
}
fn main(&self) -> FileId {
self.main.id()
}
fn source(&self, id: FileId) -> FileResult<Source> {
if id == self.main.id() {
Ok(self.main.clone())
} else if let Some(source) = self.files.sources.get(&id) {
Ok(source.clone())
} else {
Err(FileError::NotFound(id.vpath().as_rootless_path().into()))
}
}
fn file(&self, id: FileId) -> FileResult<Bytes> {
match self.files.assets.get(&id) {
Some(bytes) => Ok(bytes.clone()),
None => Err(FileError::NotFound(id.vpath().as_rootless_path().into())),
}
}
fn font(&self, index: usize) -> Option<Font> {
self.base.fonts.get(index).cloned()
}
fn today(&self, _: Option<i64>) -> Option<Datetime> {
None
}
}
impl IdeWorld for TestWorld {
fn upcast(&self) -> &dyn World {
self
}
fn files(&self) -> Vec<FileId> {
std::iter::once(self.main.id())
.chain(self.files.sources.keys().copied())
.chain(self.files.assets.keys().copied())
.collect()
}
fn packages(&self) -> &[(PackageSpec, Option<EcoString>)] {
const LIST: &[(PackageSpec, Option<EcoString>)] = &[(
PackageSpec {
// NOTE: This literal, `"preview"`, should match the const, `DEFAULT_NAMESPACE`,
// defined in `crates/typst-kit/src/package.rs`. However, we should always use the
// literal here, not `DEFAULT_NAMESPACE`, so that this test fails if its value
// changes in an unexpected way.
namespace: EcoString::inline("preview"),
name: EcoString::inline("example"),
version: PackageVersion { major: 0, minor: 1, patch: 0 },
},
None,
)];
LIST
}
}
/// Test-specific files.
#[derive(Default, Clone)]
struct TestFiles {
assets: FxHashMap<FileId, Bytes>,
sources: FxHashMap<FileId, Source>,
}
/// Shared foundation of all test worlds.
struct TestBase {
library: LazyHash<Library>,
book: LazyHash<FontBook>,
fonts: Vec<Font>,
}
impl Default for TestBase {
fn default() -> Self {
let fonts: Vec<_> = typst_assets::fonts()
.chain(typst_dev_assets::fonts())
.flat_map(|data| Font::iter(Bytes::new(data)))
.collect();
Self {
library: LazyHash::new(library()),
book: LazyHash::new(FontBook::from_fonts(&fonts)),
fonts,
}
}
}
/// The extended standard library for testing.
fn library() -> Library {
// Set page width to 120pt with 10pt margins, so that the inner page is
// exactly 100pt wide. Page height is unbounded and font size is 10pt so
// that it multiplies to nice round numbers.
let mut lib = typst::Library::builder()
.with_features([Feature::Html].into_iter().collect())
.build();
lib.styles.set(PageElem::width, Smart::Custom(Abs::pt(120.0).into()));
lib.styles.set(PageElem::height, Smart::Auto);
lib.styles
.set(PageElem::margin, Margin::splat(Some(Smart::Custom(Abs::pt(10.0).into()))));
lib.styles.set(TextElem::size, TextSize(Abs::pt(10.0).into()));
lib
}
/// The input to a test: Either just a string or a full `TestWorld`.
pub trait WorldLike {
type World: Borrow<TestWorld>;
fn acquire(self) -> Self::World;
}
impl<'a> WorldLike for &'a TestWorld {
type World = &'a TestWorld;
fn acquire(self) -> Self::World {
self
}
}
impl WorldLike for &str {
type World = TestWorld;
fn acquire(self) -> Self::World {
TestWorld::new(self)
}
}
/// Specifies a position in a file for a test. Negative numbers index from the
/// back. `-1` is at the very back.
pub trait FilePos {
fn resolve(self, world: &TestWorld) -> (Source, usize);
}
impl FilePos for isize {
#[track_caller]
fn resolve(self, world: &TestWorld) -> (Source, usize) {
(world.main.clone(), cursor(&world.main, self))
}
}
impl FilePos for (&str, isize) {
#[track_caller]
fn resolve(self, world: &TestWorld) -> (Source, usize) {
let id = FileId::new(None, VirtualPath::new(self.0));
let source = world.source(id).unwrap();
let cursor = cursor(&source, self.1);
(source, cursor)
}
}
/// Resolve a signed index (negative from the back) to a unsigned index.
#[track_caller]
fn cursor(source: &Source, cursor: isize) -> usize {
if cursor < 0 {
source.text().len().checked_add_signed(cursor + 1).unwrap()
} else {
cursor as usize
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/tooltip.rs | crates/typst-ide/src/tooltip.rs | use std::fmt::Write;
use ecow::{EcoString, eco_format};
use typst::AsDocument;
use typst::engine::Sink;
use typst::foundations::{Binding, Capturer, CastInfo, Repr, Value, repr};
use typst::layout::Length;
use typst::syntax::ast::AstNode;
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::{IdeWorld, analyze_expr, analyze_import, analyze_labels};
/// Describe the item under the cursor.
///
/// Passing a `document` (from a previous compilation) is optional, but enhances
/// the tooltips. Label tooltips, for instance, are only generated when the
/// document is available.
pub fn tooltip(
world: &dyn IdeWorld,
document: Option<impl AsDocument>,
source: &Source,
cursor: usize,
side: Side,
) -> Option<Tooltip> {
let leaf = LinkedNode::new(source.root()).leaf_at(cursor, side)?;
if leaf.kind().is_trivia() {
return None;
}
named_param_tooltip(world, &leaf)
.or_else(|| font_tooltip(world, &leaf))
.or_else(|| document.and_then(|doc| label_tooltip(doc, &leaf)))
.or_else(|| import_tooltip(world, &leaf))
.or_else(|| expr_tooltip(world, &leaf))
.or_else(|| closure_tooltip(&leaf))
}
/// A hover tooltip.
#[derive(Debug, Clone, PartialEq)]
pub enum Tooltip {
/// A string of text.
Text(EcoString),
/// A string of Typst code.
Code(EcoString),
}
/// Tooltip for a hovered expression.
fn expr_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
let mut ancestor = leaf;
while !ancestor.is::<ast::Expr>() {
ancestor = ancestor.parent()?;
}
let expr = ancestor.cast::<ast::Expr>()?;
if !expr.hash() && !matches!(expr, ast::Expr::MathIdent(_)) {
return None;
}
let values = analyze_expr(world, ancestor);
if let [(value, _)] = values.as_slice() {
if let Some(docs) = value.docs() {
return Some(Tooltip::Text(plain_docs_sentence(docs)));
}
if let &Value::Length(length) = value
&& let Some(tooltip) = length_tooltip(length)
{
return Some(tooltip);
}
}
if expr.is_literal() {
return None;
}
let mut last = None;
let mut pieces: Vec<EcoString> = vec![];
let mut iter = values.iter();
for (value, _) in (&mut iter).take(Sink::MAX_VALUES - 1) {
if let Some((prev, count)) = &mut last {
if *prev == value {
*count += 1;
continue;
} else if *count > 1 {
write!(pieces.last_mut().unwrap(), " (×{count})").unwrap();
}
}
pieces.push(value.repr());
last = Some((value, 1));
}
if let Some((_, count)) = last
&& count > 1
{
write!(pieces.last_mut().unwrap(), " (×{count})").unwrap();
}
if iter.next().is_some() {
pieces.push("...".into());
}
let tooltip = repr::pretty_comma_list(&pieces, false);
(!tooltip.is_empty()).then(|| Tooltip::Code(tooltip.into()))
}
/// Tooltips for imports.
fn import_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
if leaf.kind() == SyntaxKind::Star
&& let Some(parent) = leaf.parent()
&& let Some(import) = parent.cast::<ast::ModuleImport>()
&& 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
}
/// Tooltip for a hovered closure.
fn closure_tooltip(leaf: &LinkedNode) -> Option<Tooltip> {
// Only show this tooltip when hovering over the equals sign or arrow of
// the closure. Showing it across the whole subtree is too noisy.
if !matches!(leaf.kind(), SyntaxKind::Eq | SyntaxKind::Arrow) {
return None;
}
// Find the closure to analyze.
let parent = leaf.parent()?;
if parent.kind() != SyntaxKind::Closure {
return None;
}
// Analyze the closure's captures.
let mut visitor = CapturesVisitor::new(None, Capturer::Function);
visitor.visit(parent);
let captures = visitor.finish();
let mut names: Vec<_> =
captures.iter().map(|(name, ..)| eco_format!("`{name}`")).collect();
if names.is_empty() {
return None;
}
names.sort();
let tooltip = repr::separated_list(&names, "and");
Some(Tooltip::Text(eco_format!("This closure captures {tooltip}")))
}
/// Tooltip text for a hovered length.
fn length_tooltip(length: Length) -> Option<Tooltip> {
length.em.is_zero().then(|| {
Tooltip::Code(eco_format!(
"{}pt = {}mm = {}cm = {}in",
round_with_precision(length.abs.to_pt(), 2),
round_with_precision(length.abs.to_mm(), 2),
round_with_precision(length.abs.to_cm(), 2),
round_with_precision(length.abs.to_inches(), 2),
))
})
}
/// Tooltip for a hovered reference or label.
fn label_tooltip(document: impl AsDocument, leaf: &LinkedNode) -> Option<Tooltip> {
let target = match leaf.kind() {
SyntaxKind::RefMarker => leaf.text().trim_start_matches('@'),
SyntaxKind::Label => leaf.text().trim_start_matches('<').trim_end_matches('>'),
_ => return None,
};
for (label, detail) in analyze_labels(document).0 {
if label.resolve().as_str() == target {
return Some(Tooltip::Text(detail?));
}
}
None
}
/// Tooltips for components of a named parameter.
fn named_param_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
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()
&& let Some(named) = parent.cast::<ast::Named>()
&& let Some(grand) = parent.parent()
&& matches!(grand.kind(), SyntaxKind::Args)
&& let Some(grand_grand) = grand.parent()
&& let Some(expr) = grand_grand.cast::<ast::Expr>()
&& 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.
&& let Some(Value::Func(func)) = world
.library()
.global
.scope()
.get(&callee)
.map(Binding::read)
{ (func, named) }
else { return None; };
// Hovering over the parameter name.
if leaf.index() == 0
&& let Some(ident) = leaf.cast::<ast::Ident>()
&& let Some(param) = func.param(&ident)
{
return Some(Tooltip::Text(plain_docs_sentence(param.docs)));
}
// Hovering over a string parameter value.
if let Some(string) = leaf.cast::<ast::Str>()
&& let Some(param) = func.param(&named.name())
&& let Some(docs) = find_string_doc(¶m.input, &string.get())
{
return Some(Tooltip::Text(docs.into()));
}
None
}
/// Find documentation for a castable string.
fn find_string_doc(info: &CastInfo, string: &str) -> Option<&'static str> {
match info {
CastInfo::Value(Value::Str(s), docs) if s.as_str() == string => Some(docs),
CastInfo::Union(options) => {
options.iter().find_map(|option| find_string_doc(option, string))
}
_ => None,
}
}
/// Tooltip for font.
fn font_tooltip(world: &dyn IdeWorld, leaf: &LinkedNode) -> Option<Tooltip> {
// Ensure that we are on top of a string.
if let Some(string) = leaf.cast::<ast::Str>()
&& let lower = string.get().to_lowercase()
// Ensure that we are in the arguments to the text function.
&& let Some(parent) = leaf.parent()
&& let Some(named) = parent.cast::<ast::Named>()
&& named.name().as_str() == "font"
// Find the font family.
&& let Some((_, iter)) = world
.book()
.families()
.find(|&(family, _)| family.to_lowercase().as_str() == lower.as_str())
{
let detail = summarize_font_family(iter.collect());
return Some(Tooltip::Text(detail));
}
None
}
#[cfg(test)]
mod tests {
use std::borrow::Borrow;
use typst::layout::PagedDocument;
use typst::syntax::Side;
use super::{Tooltip, tooltip};
use crate::tests::{FilePos, TestWorld, WorldLike};
type Response = Option<Tooltip>;
trait ResponseExt {
fn must_be_none(&self) -> &Self;
fn must_be_text(&self, text: &str) -> &Self;
fn must_be_code(&self, code: &str) -> &Self;
}
impl ResponseExt for Response {
#[track_caller]
fn must_be_none(&self) -> &Self {
assert_eq!(*self, None);
self
}
#[track_caller]
fn must_be_text(&self, text: &str) -> &Self {
assert_eq!(*self, Some(Tooltip::Text(text.into())));
self
}
#[track_caller]
fn must_be_code(&self, code: &str) -> &Self {
assert_eq!(*self, Some(Tooltip::Code(code.into())));
self
}
}
#[track_caller]
fn test(world: impl WorldLike, pos: impl FilePos, side: Side) -> Response {
let world = world.acquire();
let world = world.borrow();
let (source, cursor) = pos.resolve(world);
let doc = typst::compile::<PagedDocument>(world).output.ok();
tooltip(world, doc.as_ref(), &source, cursor, side)
}
#[test]
fn test_tooltip() {
test("#let x = 1 + 2", -1, Side::After).must_be_none();
test("#let x = 1 + 2", 5, Side::After).must_be_code("3");
test("#let x = 1 + 2", 6, Side::Before).must_be_code("3");
test("#let x = 1 + 2", 6, Side::Before).must_be_code("3");
}
#[test]
fn test_tooltip_empty_contextual() {
test("#{context}", -1, Side::Before).must_be_code("context()");
}
#[test]
fn test_tooltip_closure() {
test("#let f(x) = x + y", 11, Side::Before)
.must_be_text("This closure captures `y`");
// Same tooltip if `y` is defined first.
test("#let y = 10; #let f(x) = x + y", 24, Side::Before)
.must_be_text("This closure captures `y`");
// Names are sorted.
test("#let f(x) = x + y + z + a", 11, Side::Before)
.must_be_text("This closure captures `a`, `y`, and `z`");
// Names are de-duplicated.
test("#let f(x) = x + y + z + y", 11, Side::Before)
.must_be_text("This closure captures `y` and `z`");
// With arrow syntax.
test("#let f = (x) => x + y", 15, Side::Before)
.must_be_text("This closure captures `y`");
// No recursion with arrow syntax.
test("#let f = (x) => x + y + f", 13, Side::After)
.must_be_text("This closure captures `f` and `y`");
}
#[test]
fn test_tooltip_import() {
let world = TestWorld::new("#import \"other.typ\": a, b")
.with_source("other.typ", "#let (a, b, c) = (1, 2, 3)");
test(&world, -5, Side::After).must_be_code("1");
}
#[test]
fn test_tooltip_star_import() {
let world = TestWorld::new("#import \"other.typ\": *")
.with_source("other.typ", "#let (a, b, c) = (1, 2, 3)");
test(&world, -2, Side::Before).must_be_none();
test(&world, -2, Side::After).must_be_text("This star imports `a`, `b`, and `c`");
}
#[test]
fn test_tooltip_field_call() {
let world = TestWorld::new("#import \"other.typ\"\n#other.f()")
.with_source("other.typ", "#let f = (x) => 1");
test(&world, -4, Side::After).must_be_code("(..) => ..");
}
#[test]
fn test_tooltip_reference() {
test("#figure(caption: [Hi])[]<f> @f", -1, Side::Before).must_be_text("Hi");
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/matchers.rs | crates/typst-ide/src/matchers.rs | use ecow::EcoString;
use typst::foundations::{Module, Value};
use typst::syntax::ast::AstNode;
use typst::syntax::{LinkedNode, Span, SyntaxKind, ast};
use crate::{IdeWorld, analyze_import};
/// Find the named items starting from the given position.
pub fn named_items<T>(
world: &dyn IdeWorld,
position: LinkedNode,
mut recv: impl FnMut(NamedItem) -> Option<T>,
) -> Option<T> {
let mut ancestor = Some(position);
while let Some(node) = &ancestor {
let mut sibling = Some(node.clone());
while let Some(node) = &sibling {
if let Some(v) = node.cast::<ast::LetBinding>() {
let kind = if matches!(v.kind(), ast::LetBindingKind::Closure(..)) {
NamedItem::Fn
} else {
NamedItem::Var
};
for ident in v.kind().bindings() {
if let Some(res) = recv(kind(ident)) {
return Some(res);
}
}
}
if let Some(v) = node.cast::<ast::ModuleImport>() {
let imports = v.imports();
let source = v.source();
let source_value = node
.find(source.span())
.and_then(|source| analyze_import(world, &source));
let source_value = source_value.as_ref();
let module = source_value.and_then(|value| match value {
Value::Module(module) => Some(module),
_ => None,
});
let name_and_span = match (imports, v.new_name()) {
// ```plain
// import "foo" as name
// import "foo" as name: ..
// ```
(_, Some(name)) => Some((name.get().clone(), name.span())),
// ```plain
// import "foo"
// ```
(None, None) => v.bare_name().ok().map(|name| (name, source.span())),
// ```plain
// import "foo": ..
// ```
(Some(..), None) => None,
};
// Seeing the module itself.
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 {
// ```plain
// import "foo";
// ```
None => {}
// ```plain
// import "foo": *;
// ```
Some(ast::Imports::Wildcard) => {
if let Some(scope) = source_value.and_then(Value::scope) {
for (name, binding) in scope.iter() {
let item = NamedItem::Import(
name,
binding.span(),
Some(binding.read()),
);
if let Some(res) = recv(item) {
return Some(res);
}
}
}
}
// ```plain
// import "foo": items;
// ```
Some(ast::Imports::Items(items)) => {
for item in items.iter() {
let mut iter = item.path().iter();
let mut binding = source_value
.and_then(Value::scope)
.zip(iter.next())
.and_then(|(scope, first)| scope.get(&first));
for ident in iter {
binding = binding.and_then(|binding| {
binding.read().scope()?.get(&ident)
});
}
let bound = item.bound_name();
let (span, value) = match binding {
Some(binding) => (binding.span(), Some(binding.read())),
None => (bound.span(), None),
};
let item = NamedItem::Import(bound.get(), span, value);
if let Some(res) = recv(item) {
return Some(res);
}
}
}
}
}
sibling = node.prev_sibling();
}
if let Some(parent) = node.parent() {
if let Some(v) = parent.cast::<ast::ForLoop>()
&& 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::<ast::Closure>().filter(|v| {
// Check if the node is in the body of the closure.
let body = parent.find(v.body().span());
body.is_some_and(|n| n.find(node.span()).is_some())
}) {
for param in v.params().children() {
match param {
ast::Param::Pos(pattern) => {
for ident in pattern.bindings() {
if let Some(t) = recv(NamedItem::Var(ident)) {
return Some(t);
}
}
}
ast::Param::Named(n) => {
if let Some(t) = recv(NamedItem::Var(n.name())) {
return Some(t);
}
}
ast::Param::Spread(s) => {
if let Some(sink_ident) = s.sink_ident()
&& let Some(t) = recv(NamedItem::Var(sink_ident))
{
return Some(t);
}
}
}
}
}
ancestor = Some(parent.clone());
continue;
}
break;
}
None
}
/// An item that is named.
pub enum NamedItem<'a> {
/// A variable item.
Var(ast::Ident<'a>),
/// A function item.
Fn(ast::Ident<'a>),
/// A (imported) module.
Module(&'a EcoString, Span, Option<&'a Module>),
/// An imported item.
Import(&'a EcoString, Span, Option<&'a Value>),
}
impl<'a> NamedItem<'a> {
pub(crate) fn name(&self) -> &'a EcoString {
match self {
NamedItem::Var(ident) => ident.get(),
NamedItem::Fn(ident) => ident.get(),
NamedItem::Module(name, _, _) => name,
NamedItem::Import(name, _, _) => name,
}
}
pub(crate) fn value(&self) -> Option<Value> {
match self {
NamedItem::Var(..) | NamedItem::Fn(..) => None,
NamedItem::Module(_, _, value) => value.cloned().map(Value::Module),
NamedItem::Import(_, _, value) => value.cloned(),
}
}
pub(crate) fn span(&self) -> Span {
match *self {
NamedItem::Var(name) | NamedItem::Fn(name) => name.span(),
NamedItem::Module(_, span, _) => span,
NamedItem::Import(_, span, _) => span,
}
}
}
/// Categorize an expression into common classes IDE functionality can operate
/// on.
pub fn deref_target(node: LinkedNode<'_>) -> Option<DerefTarget<'_>> {
// Move to the first ancestor that is an expression.
let mut ancestor = node;
while !ancestor.is::<ast::Expr>() {
ancestor = ancestor.parent()?.clone();
}
// Identify convenient expression kinds.
let expr_node = ancestor;
let expr = expr_node.cast::<ast::Expr>()?;
Some(match expr {
ast::Expr::Label(_) => DerefTarget::Label(expr_node),
ast::Expr::Ref(_) => DerefTarget::Ref(expr_node),
ast::Expr::FuncCall(call) => {
DerefTarget::Callee(expr_node.find(call.callee().span())?)
}
ast::Expr::SetRule(set) => {
DerefTarget::Callee(expr_node.find(set.target().span())?)
}
ast::Expr::Ident(_) | ast::Expr::MathIdent(_) | ast::Expr::FieldAccess(_) => {
DerefTarget::VarAccess(expr_node)
}
ast::Expr::Str(_) => {
let parent = expr_node.parent()?;
if parent.kind() == SyntaxKind::ModuleImport {
DerefTarget::ImportPath(expr_node)
} else if parent.kind() == SyntaxKind::ModuleInclude {
DerefTarget::IncludePath(expr_node)
} else {
DerefTarget::Code(expr_node)
}
}
_ if expr.hash()
|| matches!(expr_node.kind(), SyntaxKind::MathIdent | SyntaxKind::Error) =>
{
DerefTarget::Code(expr_node)
}
_ => return None,
})
}
/// Classes of expressions that can be operated on by IDE functionality.
#[derive(Debug, Clone)]
pub enum DerefTarget<'a> {
/// A variable access expression.
///
/// It can be either an identifier or a field access.
VarAccess(LinkedNode<'a>),
/// A function call expression.
Callee(LinkedNode<'a>),
/// An import path expression.
ImportPath(LinkedNode<'a>),
/// An include path expression.
IncludePath(LinkedNode<'a>),
/// Any code expression.
Code(LinkedNode<'a>),
/// A label expression.
Label(LinkedNode<'a>),
/// A reference expression.
Ref(LinkedNode<'a>),
}
#[cfg(test)]
mod tests {
use std::borrow::Borrow;
use ecow::EcoString;
use typst::foundations::Value;
use typst::syntax::{LinkedNode, Side};
use super::named_items;
use crate::tests::{FilePos, TestWorld, WorldLike};
type Response = Vec<(EcoString, Option<Value>)>;
trait ResponseExt {
fn must_include<'a>(&self, includes: impl IntoIterator<Item = &'a str>) -> &Self;
fn must_exclude<'a>(&self, excludes: impl IntoIterator<Item = &'a str>) -> &Self;
fn must_include_value(&self, name_value: (&str, Option<&Value>)) -> &Self;
}
impl ResponseExt for Response {
#[track_caller]
fn must_include<'a>(&self, includes: impl IntoIterator<Item = &'a str>) -> &Self {
for item in includes {
assert!(
self.iter().any(|v| v.0 == item),
"{item:?} was not contained in {self:?}",
);
}
self
}
#[track_caller]
fn must_exclude<'a>(&self, excludes: impl IntoIterator<Item = &'a str>) -> &Self {
for item in excludes {
assert!(
!self.iter().any(|v| v.0 == item),
"{item:?} was wrongly contained in {self:?}",
);
}
self
}
#[track_caller]
fn must_include_value(&self, name_value: (&str, Option<&Value>)) -> &Self {
assert!(
self.iter().any(|v| (v.0.as_str(), v.1.as_ref()) == name_value),
"{name_value:?} was not contained in {self:?}",
);
self
}
}
#[track_caller]
fn test(world: impl WorldLike, pos: impl FilePos) -> Response {
let world = world.acquire();
let world = world.borrow();
let (source, cursor) = pos.resolve(world);
let node = LinkedNode::new(source.root());
let leaf = node.leaf_at(cursor, Side::After).unwrap();
let mut items = vec![];
named_items(world, leaf, |s| {
items.push((s.name().clone(), s.value().clone()));
None::<()>
});
items
}
#[test]
fn test_named_items_simple() {
let s = "#let a = 1;#let b = 2;";
test(s, 8).must_include(["a"]).must_exclude(["b"]);
test(s, 15).must_include(["b"]);
}
#[test]
fn test_named_items_param() {
let pos = "#let f(a) = 1;#let b = 2;";
test(pos, 12).must_include(["a"]);
test(pos, 19).must_include(["b", "f"]).must_exclude(["a"]);
let named = "#let f(a: b) = 1;#let b = 2;";
test(named, 15).must_include(["a", "f"]).must_exclude(["b"]);
}
#[test]
fn test_named_items_import() {
test("#import \"foo.typ\"", 2).must_include(["foo"]);
test("#import \"foo.typ\" as bar", 2)
.must_include(["bar"])
.must_exclude(["foo"]);
}
#[test]
fn test_named_items_import_items() {
test("#import \"foo.typ\": a; #(a);", 2)
.must_include(["a"])
.must_exclude(["foo"]);
let world = TestWorld::new("#import \"foo.typ\": a.b; #(b);")
.with_source("foo.typ", "#import \"a.typ\"")
.with_source("a.typ", "#let b = 1;");
test(&world, 2).must_include_value(("b", Some(&Value::Int(1))));
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/jump.rs | crates/typst-ide/src/jump.rs | use ecow::EcoVec;
use typst::introspection::{DocumentPosition, HtmlPosition};
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::{AsDocument, WorldExt};
use typst_html::{HtmlDocument, HtmlElement, HtmlNode, HtmlSliceExt};
use crate::IdeWorld;
/// Where to [jump](jump_from_click) to.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Jump {
/// Jump to a position in a file.
File(FileId, usize),
/// Jump to an external URL.
Url(Url),
/// Jump to a point on a page.
Position(Position),
}
impl Jump {
fn from_span(world: &dyn IdeWorld, span: Span) -> Option<Self> {
let id = span.id()?;
let offset = world.range(span)?.start;
Some(Self::File(id, offset))
}
}
/// Determine where to jump to, based on a click in a rendered document.
pub fn jump_from_click<D: JumpFromDocument>(
world: &dyn IdeWorld,
document: &D,
position: &D::Position,
) -> Option<Jump> {
document.resolve_position(world, position)
}
/// Maps a position in a document to a [jump destination][`Jump`], allowing for
/// click-to-jump functionality.
pub trait JumpFromDocument: jump_from_document_sealed::JumpFromDocument {}
// The actual implementations are in the sealed trait.
impl JumpFromDocument for PagedDocument {}
impl JumpFromDocument for HtmlDocument {}
mod jump_from_document_sealed {
use typst::introspection::{HtmlPosition, InnerHtmlPosition};
use typst::layout::{PagedDocument, Position};
use typst_html::{HtmlDocument, HtmlNode, HtmlSliceExt};
use super::{Jump, jump_from_click_in_frame};
use crate::IdeWorld;
/// See [`super::JumpFromDocument`].
pub trait JumpFromDocument {
type Position;
fn resolve_position(
&self,
world: &dyn IdeWorld,
position: &Self::Position,
) -> Option<Jump>;
}
impl JumpFromDocument for PagedDocument {
type Position = Position;
fn resolve_position(
&self,
world: &dyn IdeWorld,
position: &Self::Position,
) -> Option<Jump> {
let page = self.pages.get(position.page.get() - 1)?;
let click = position.point;
jump_from_click_in_frame(world, self, &page.frame, click)
}
}
impl JumpFromDocument for HtmlDocument {
type Position = HtmlPosition;
fn resolve_position(
&self,
world: &dyn IdeWorld,
position: &Self::Position,
) -> Option<Jump> {
let mut current_node: &HtmlNode = &HtmlNode::Element(self.root.clone());
let mut prefix_len = 0;
let indices_count = position.element().count();
for (i, index) in position.element().enumerate() {
let reached_leaf_node = i == indices_count - 1;
match current_node {
HtmlNode::Element(html_element) => {
let (child_index, (mut child, _)) = html_element
.children
.iter_with_dom_indices()
.enumerate()
.find(|(_, (child, dom_index))| {
!matches!(child, HtmlNode::Tag(_)) && dom_index == index
})?;
// In some scenarios, Typst will emit multiple
// consecutive text nodes (called text node parts below),
// the firsts of which may have detached spans. This is
// for example the case with the default figure
// captions: the supplement, counter, and separator will
// be individual spanless text nodes (and only the actual
// caption body will have a span).
//
// Because the HTML document as parsed by an external
// program will probably contain a single text node for
// all that, jumping from the caption body will ask for
// a jump from the 0-th child of the <figcaption>, at a
// certain offset. Because `nth_child` doesn't take this
// offset into account, it will then pick the first text
// node: in the previous example, the spanless
// supplement.
//
// Below, we compensate for that, and make sure the
// position can be correctly resolved by picking another
// text node if needed.
if reached_leaf_node
&& let HtmlNode::Text(_, _) = child
&& let Some(InnerHtmlPosition::Character(offset)) =
position.details()
{
let mut text_char_count = 0;
let mut text_node_part = child;
let mut text_node_offset = 0;
// The requested offset is expressed as a character
// index (not a byte offset).
while text_char_count < *offset {
prefix_len = text_char_count;
// Get the current text node part
text_node_part = html_element
.children
.get(child_index + text_node_offset)?;
// And measure its length (in characters), to be
// able to tell if we are far enough to have
// reached the character to which we want to
// jump to.
let text_node_part_len =
if let HtmlNode::Text(text, _) = text_node_part {
text.chars().count()
} else {
0
};
// Prepare the iteration to the next text node,
// that will happen if we have not yet reached
// the requested character offset.
text_char_count += text_node_part_len;
text_node_offset += 1;
}
child = text_node_part
}
current_node = child;
}
HtmlNode::Tag(_) | HtmlNode::Text(_, _) | HtmlNode::Frame(_) => {
return None;
}
}
}
let span = current_node.span();
let id = span.id()?;
let source = world.source(id).ok()?;
let ast_node = source.find(span);
let is_text_node =
ast_node.is_some_and(|x| x.is::<typst::syntax::ast::Text>());
if let (HtmlNode::Frame(frame), Some(InnerHtmlPosition::Frame(point))) =
(current_node, &position.details())
{
return jump_from_click_in_frame(world, self, &frame.inner, *point);
}
let source_range = source.range(span)?;
Some(Jump::File(
id,
source_range.start
+ match (is_text_node, &position.details()) {
(true, Some(InnerHtmlPosition::Character(i))) => {
let source_text = &source.text()[source_range];
let slice: String = source_text
.chars()
.take(i.saturating_sub(prefix_len))
.collect();
slice.len()
}
_ => 0,
},
))
}
}
}
/// Determine where to jump to based on a click in a frame.
pub fn jump_from_click_in_frame(
world: &dyn IdeWorld,
document: impl AsDocument,
frame: &Frame,
click: Point,
) -> Option<Jump> {
let document = document.as_document();
// 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)
{
match dest {
Destination::Url(url) => return Some(Jump::Url(url.clone())),
Destination::Position(pos) => return Some(Jump::Position(*pos)),
Destination::Location(loc) => {
if let DocumentPosition::Paged(pos) =
document.introspector().position(*loc)
{
return Some(Jump::Position(pos));
}
}
}
}
}
// If there's no link, search for a jump target.
for &(mut pos, ref item) in frame.items().rev() {
match item {
FrameItem::Group(group) => {
let pos = click - 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.
let Some(inv_transform) = group.transform.invert() else {
continue;
};
let pos = pos.transform_inf(inv_transform);
if let Some(span) =
jump_from_click_in_frame(world, document, &group.frame, pos)
{
return Some(span);
}
}
FrameItem::Text(text) => {
for glyph in &text.glyphs {
let width = glyph.x_advance.at(text.size);
if is_in_rect(
Point::new(pos.x, pos.y - text.size),
Size::new(width, text.size),
click,
) {
let (span, span_offset) = glyph.span;
let Some(id) = span.id() else { continue };
let source = world.source(id).ok()?;
let node = source.find(span)?;
let pos = if matches!(
node.kind(),
SyntaxKind::Text | SyntaxKind::MathText
) {
let range = node.range();
let mut offset = range.start + usize::from(span_offset);
if (click.x - pos.x) > width / 2.0 {
offset += glyph.range().len();
}
offset.min(range.end)
} else {
node.offset()
};
return Some(Jump::File(source.id(), pos));
}
pos.x += width;
}
}
FrameItem::Shape(shape, span) => {
if shape.fill.is_some() {
let within = match &shape.geometry {
Geometry::Line(..) => false,
Geometry::Rect(size) => is_in_rect(pos, *size, click),
Geometry::Curve(curve) => {
curve.contains(shape.fill_rule, click - pos)
}
};
if within {
return Jump::from_span(world, *span);
}
}
if let Some(stroke) = &shape.stroke {
let within = !stroke.thickness.approx_empty() && {
// This curve is rooted at (0, 0), not `pos`.
let base_curve = match &shape.geometry {
Geometry::Line(to) => &Curve(vec![CurveItem::Line(*to)]),
Geometry::Rect(size) => &Curve::rect(*size),
Geometry::Curve(curve) => curve,
};
base_curve.stroke_contains(stroke, click - pos)
};
if within {
return Jump::from_span(world, *span);
}
}
}
FrameItem::Image(_, size, span) if is_in_rect(pos, *size, click) => {
return Jump::from_span(world, *span);
}
_ => {}
}
}
None
}
/// Whether a rectangle with the given size at the given position contains the
/// click position.
fn is_in_rect(pos: Point, size: Size, click: Point) -> bool {
pos.x <= click.x
&& pos.x + size.x >= click.x
&& pos.y <= click.y
&& pos.y + size.y >= click.y
}
/// Find the output location in the document for a cursor position.
pub fn jump_from_cursor<D: JumpInDocument>(
document: &D,
source: &Source,
cursor: usize,
) -> Vec<D::Position> {
fn is_text(node: &LinkedNode) -> bool {
matches!(node.kind(), SyntaxKind::Text | SyntaxKind::MathText)
}
let root = LinkedNode::new(source.root());
let Some(node) = root
.leaf_at(cursor, Side::Before)
.filter(is_text)
.or_else(|| root.leaf_at(cursor, Side::After).filter(is_text))
else {
return vec![];
};
let span = node.span();
document.find_span(span)
}
/// Jump to a position in the document, given a cursor position in a source
/// file.
pub trait JumpInDocument: jump_in_document_sealed::JumpInDocument {}
// The actual implementations are in the sealed trait.
impl JumpInDocument for PagedDocument {}
impl JumpInDocument for HtmlDocument {}
/// Sealing for [`JumpInDocument`].
mod jump_in_document_sealed {
use std::num::NonZeroUsize;
use ecow::EcoVec;
use typst::introspection::HtmlPosition;
use typst::layout::{PagedDocument, Position};
use typst::syntax::Span;
use typst_html::HtmlDocument;
use super::{find_in_elem, find_in_frame};
/// See [`super::JumpInDocument`].
pub trait JumpInDocument {
type Position;
fn find_span(&self, span: Span) -> Vec<Self::Position>;
}
impl JumpInDocument for PagedDocument {
type Position = Position;
fn find_span(&self, span: Span) -> Vec<Self::Position> {
self.pages
.iter()
.enumerate()
.filter_map(|(i, page)| {
find_in_frame(&page.frame, span).map(|point| Position {
page: NonZeroUsize::new(i + 1).unwrap(),
point,
})
})
.collect()
}
}
impl JumpInDocument for HtmlDocument {
type Position = HtmlPosition;
fn find_span(&self, span: Span) -> Vec<Self::Position> {
find_in_elem(&self.root, span, &mut EcoVec::new())
}
}
}
/// Find the position of a span in a frame.
fn find_in_frame(frame: &Frame, span: Span) -> Option<Point> {
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));
}
if let FrameItem::Text(text) = item {
for glyph in &text.glyphs {
if glyph.span.0 == span {
return Some(pos);
}
pos.x += glyph.x_advance.at(text.size);
}
}
}
None
}
/// Find the position of a span in an HTML element.
fn find_in_elem(
elem: &HtmlElement,
span: Span,
current_position: &mut EcoVec<usize>,
) -> Vec<HtmlPosition> {
let mut result = Vec::new();
for (child, dom_index) in elem.children.iter_with_dom_indices() {
match child {
HtmlNode::Tag(_) => {}
HtmlNode::Element(e) => {
current_position.push(dom_index);
result.extend(find_in_elem(e, span, current_position));
current_position.pop();
}
HtmlNode::Text(_, node_span) => {
if *node_span == span {
return vec![HtmlPosition::new(current_position.clone())];
}
}
HtmlNode::Frame(frame) => {
if let Some(frame_pos) = find_in_frame(&frame.inner, span) {
let mut position = current_position.clone();
position.push(dom_index);
return vec![HtmlPosition::new(position).in_frame(frame_pos)];
}
}
}
}
result
}
#[cfg(test)]
mod tests {
//! This can be used in a normal test to determine positions:
//! ```
//! #set page(background: place(
//! dx: 10pt,
//! dy: 10pt,
//! square(size: 2pt, fill: red),
//! ))
//! ```
use std::borrow::Borrow;
use std::num::NonZeroUsize;
use ecow::eco_vec;
use typst::introspection::HtmlPosition;
use typst::layout::{Abs, PagedDocument, Point, Position};
use typst::utils::NonZeroExt;
use typst_html::HtmlDocument;
use super::{Jump, jump_from_click, jump_from_cursor};
use crate::tests::{FilePos, TestWorld, WorldLike};
fn point(x: f64, y: f64) -> Point {
Point::new(Abs::pt(x), Abs::pt(y))
}
fn cursor(cursor: usize) -> Option<Jump> {
Some(Jump::File(TestWorld::main_id(), cursor))
}
fn pos(page: usize, x: f64, y: f64) -> Option<Position> {
Some(Position {
page: NonZeroUsize::new(page).unwrap(),
point: point(x, y),
})
}
macro_rules! assert_approx_eq {
($l:expr, $r:expr) => {
assert!(($l - $r).abs() < Abs::pt(0.1), "{:?} ≉ {:?}", $l, $r);
};
}
#[track_caller]
fn assert_jump_eq(jump: Option<Jump>, expected: Option<Jump>) {
if let (Some(Jump::Position(pos)), Some(Jump::Position(expected))) =
(&jump, &expected)
{
assert_eq!(pos.page, expected.page);
assert_approx_eq!(pos.point.x, expected.point.x);
assert_approx_eq!(pos.point.y, expected.point.y);
} else {
assert_eq!(jump, expected);
}
}
#[track_caller]
fn test_click(world: impl WorldLike, click: Point, expected: Option<Jump>) {
let world = world.acquire();
let world = world.borrow();
let doc: PagedDocument = typst::compile(world).output.unwrap();
let jump = jump_from_click(
world,
&doc,
&Position { page: NonZeroUsize::ONE, point: click },
);
assert_jump_eq(jump, expected);
}
#[track_caller]
fn test_click_html(
world: impl WorldLike,
click: HtmlPosition,
expected: Option<Jump>,
) {
let world = world.acquire();
let world = world.borrow();
let doc: HtmlDocument = typst::compile(world).output.unwrap();
let jump = jump_from_click(world, &doc, &click);
assert_jump_eq(jump, expected);
}
#[track_caller]
fn test_cursor(world: impl WorldLike, pos: impl FilePos, expected: Option<Position>) {
let world = world.acquire();
let world = world.borrow();
let doc: PagedDocument = typst::compile(world).output.unwrap();
let (source, cursor) = pos.resolve(world);
let pos = jump_from_cursor(&doc, &source, cursor);
assert_eq!(!pos.is_empty(), expected.is_some());
if let (Some(pos), Some(expected)) = (pos.first(), expected) {
assert_eq!(pos.page, expected.page);
assert_approx_eq!(pos.point.x, expected.point.x);
assert_approx_eq!(pos.point.y, expected.point.y);
}
}
#[test]
fn test_jump_from_click() {
let s = "*Hello* #box[ABC] World";
test_click(s, point(0.0, 0.0), None);
test_click(s, point(70.0, 5.0), None);
test_click(s, point(45.0, 15.0), cursor(14));
test_click(s, point(48.0, 15.0), cursor(15));
test_click(s, point(72.0, 10.0), cursor(20));
}
#[test]
fn test_jump_from_click_par_indents() {
// There was a bug with span mapping due to indents generating
// extra spacing.
let s = "#set par(first-line-indent: 1cm, hanging-indent: 1cm);Hello";
test_click(s, point(21.0, 12.0), cursor(56));
}
#[test]
fn test_jump_from_click_math() {
test_click("$a + b$", point(28.0, 14.0), cursor(5));
}
#[test]
fn test_jump_from_click_transform_clip() {
let margin = point(10.0, 10.0);
test_click(
"#rect(width: 20pt, height: 20pt, fill: black)",
point(10.0, 10.0) + margin,
cursor(1),
);
test_click(
"#rect(width: 60pt, height: 10pt, fill: black)",
point(5.0, 30.0) + margin,
None,
);
test_click(
"#rotate(90deg, origin: bottom + left, rect(width: 60pt, height: 10pt, fill: black))",
point(5.0, 30.0) + margin,
cursor(38),
);
test_click(
"#scale(x: 300%, y: 300%, origin: top + left, rect(width: 10pt, height: 10pt, fill: black))",
point(20.0, 20.0) + margin,
cursor(45),
);
test_click(
"#box(width: 10pt, height: 10pt, clip: true, scale(x: 300%, y: 300%, \
origin: top + left, rect(width: 10pt, height: 10pt, fill: black)))",
point(20.0, 20.0) + margin,
None,
);
test_click(
"#box(width: 10pt, height: 10pt, clip: false, rect(width: 30pt, height: 30pt, fill: black))",
point(20.0, 20.0) + margin,
cursor(45),
);
test_click(
"#box(width: 10pt, height: 10pt, clip: true, rect(width: 30pt, height: 30pt, fill: black))",
point(20.0, 20.0) + margin,
None,
);
test_click(
"#rotate(90deg, origin: bottom + left)[hello world]",
point(5.0, 15.0) + margin,
cursor(40),
);
}
#[test]
fn test_jump_from_click_shapes() {
let margin = point(10.0, 10.0);
test_click(
"#rect(width: 30pt, height: 30pt, fill: black)",
point(15.0, 15.0) + margin,
cursor(1),
);
let circle = "#circle(width: 30pt, height: 30pt, fill: black)";
test_click(circle, point(15.0, 15.0) + margin, cursor(1));
test_click(circle, point(1.0, 1.0) + margin, None);
let bowtie =
"#polygon(fill: black, (0pt, 0pt), (20pt, 20pt), (20pt, 0pt), (0pt, 20pt))";
test_click(bowtie, point(1.0, 2.0) + margin, cursor(1));
test_click(bowtie, point(2.0, 1.0) + margin, None);
test_click(bowtie, point(19.0, 10.0) + margin, cursor(1));
let evenodd = r#"#polygon(fill: black, fill-rule: "even-odd",
(0pt, 10pt), (30pt, 10pt), (30pt, 20pt), (20pt, 20pt),
(20pt, 0pt), (10pt, 0pt), (10pt, 30pt), (20pt, 30pt),
(20pt, 20pt), (0pt, 20pt))"#;
test_click(evenodd, point(15.0, 15.0) + margin, None);
test_click(evenodd, point(5.0, 15.0) + margin, cursor(1));
test_click(evenodd, point(15.0, 5.0) + margin, cursor(1));
}
#[test]
fn test_jump_from_click_shapes_stroke() {
let margin = point(10.0, 10.0);
let rect =
"#place(dx: 10pt, dy: 10pt, rect(width: 10pt, height: 10pt, stroke: 5pt))";
test_click(rect, point(15.0, 15.0) + margin, None);
test_click(rect, point(10.0, 15.0) + margin, cursor(27));
test_click(
"#line(angle: 45deg, length: 10pt, stroke: 2pt)",
point(2.0, 2.0) + margin,
cursor(1),
);
}
#[test]
fn test_jump_from_click_html() {
test_click_html(
"This is a test.\n\nWith multiple elements.\n\nAnd some *formatting*.",
// Click in the middle of "some"
HtmlPosition::new(eco_vec![1, 2, 0]).at_char(6),
cursor(48),
);
}
#[test]
fn test_jump_from_click_html_introspection() {
test_click_html(
// Raw blocks have introspection tags around them, check that they
// are ignored.
"This is a test.\n\n```\nwith some code\n```\n\nAnd `some` *formatting*.",
// Click in the middle of "some"
HtmlPosition::new(eco_vec![1, 2, 1, 0]).at_char(2),
cursor(48),
);
}
#[test]
fn test_jump_from_click_html_frame() {
test_click_html(
"A math formula:\n\n#html.frame($a x + b = 0$)",
// Click on the "b" in the math formula
HtmlPosition::new(eco_vec![1, 1]).in_frame(point(27.0, 5.0)),
cursor(37),
);
}
#[test]
fn test_jump_from_click_html_bindings() {
let src = "#let a = [This]; #let b = [exists]; #a#b";
test_click_html(
src,
// Click at "exis|ts"
HtmlPosition::new(eco_vec![1, 0, 0]).at_char(8),
cursor(src.find("ts];").unwrap()),
);
}
#[test]
fn test_jump_from_click_html_figcaption() {
let src = "#figure([Hello, world!], caption: [Output of the program.])";
test_click_html(
src,
// Click on the first "t" in the caption
HtmlPosition::new(eco_vec![1, 0, 1, 0])
.at_char("Fig. 1 — Out".chars().count()),
cursor(src.find("tput of").unwrap()),
);
}
// Make sure that the jump_from_click function uses character indices for
// the click, and bytes for the returned jump location and not other units
// to express text offsets.
#[test]
fn test_jump_from_click_html_offset_units() {
test_click_html(
"Ça va ?",
// Clicking on the "Ç" in the emitted <p> should map to the "Ç" in
// the source.
HtmlPosition::new(eco_vec![1, 0]).at_char(1),
cursor(2),
);
}
#[test]
fn test_jump_from_cursor() {
let s = "*Hello* #box[ABC] World";
test_cursor(s, 12, None);
test_cursor(s, 14, pos(1, 37.55, 16.58));
}
#[test]
fn test_jump_from_cursor_math() {
test_cursor("$a + b$", -3, pos(1, 27.51, 16.83));
}
#[test]
fn test_jump_from_cursor_transform() {
test_cursor(
r#"#rotate(90deg, origin: bottom + left, [hello world])"#,
-5,
pos(1, 10.0, 16.58),
);
}
#[test]
fn test_footnote_links() {
let s = "#footnote[Hi]";
test_click(s, point(10.0, 10.0), pos(1, 10.0, 31.58).map(Jump::Position));
test_click(s, point(19.0, 33.0), pos(1, 10.0, 16.58).map(Jump::Position));
}
#[test]
fn test_footnote_link_entry_customized() {
let s = "#show footnote.entry: [Replaced]; #footnote[Hi]";
test_click(s, point(10.0, 10.0), pos(1, 10.0, 31.58).map(Jump::Position));
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/utils.rs | crates/typst-ide/src/utils.rs | use std::fmt::Write;
use std::ops::ControlFlow;
use comemo::Track;
use ecow::{EcoString, eco_format};
use typst::engine::{Engine, Route, Sink, Traced};
use typst::foundations::{Scope, Value};
use typst::introspection::Introspector;
use typst::syntax::{LinkedNode, SyntaxKind};
use typst::text::{FontInfo, FontStyle};
use typst::utils::Protected;
use crate::IdeWorld;
/// Create a temporary engine and run a task on it.
pub fn with_engine<F, T>(world: &dyn IdeWorld, f: F) -> T
where
F: FnOnce(&mut Engine) -> T,
{
let introspector = Introspector::default();
let traced = Traced::default();
let mut sink = Sink::new();
let mut engine = Engine {
routines: &typst::ROUTINES,
world: world.upcast().track(),
introspector: Protected::new(introspector.track()),
traced: traced.track(),
sink: sink.track_mut(),
route: Route::default(),
};
f(&mut engine)
}
/// Extract the first sentence of plain text of a piece of documentation.
///
/// Removes Markdown formatting.
pub fn plain_docs_sentence(docs: &str) -> EcoString {
let mut s = unscanny::Scanner::new(docs);
let mut output = EcoString::new();
let mut link = false;
while let Some(c) = s.eat() {
match c {
'`' => {
let mut raw = s.eat_until('`');
if (raw.starts_with('{') && raw.ends_with('}'))
|| (raw.starts_with('[') && raw.ends_with(']'))
{
raw = &raw[1..raw.len() - 1];
}
s.eat();
output.push('`');
output.push_str(raw);
output.push('`');
}
'[' => link = true,
']' if link => {
if s.eat_if('(') {
s.eat_until(')');
s.eat();
} else if s.eat_if('[') {
s.eat_until(']');
s.eat();
}
link = false
}
'*' | '_' => {}
'.' => {
output.push('.');
break;
}
_ => output.push(c),
}
}
output
}
/// Create a short description of a font family.
pub fn summarize_font_family(mut variants: Vec<&FontInfo>) -> EcoString {
variants.sort_by_key(|info| info.variant);
let mut has_italic = false;
let mut min_weight = u16::MAX;
let mut max_weight = 0;
for info in &variants {
let weight = info.variant.weight.to_number();
has_italic |= info.variant.style == FontStyle::Italic;
min_weight = min_weight.min(weight);
max_weight = min_weight.max(weight);
}
let count = variants.len();
let mut detail = eco_format!("{count} variant{}.", if count == 1 { "" } else { "s" });
if min_weight == max_weight {
write!(detail, " Weight {min_weight}.").unwrap();
} else {
write!(detail, " Weights {min_weight}–{max_weight}.").unwrap();
}
if has_italic {
detail.push_str(" Has italics.");
}
detail
}
/// The global definitions at the given node.
pub fn globals<'a>(world: &'a dyn IdeWorld, leaf: &LinkedNode) -> &'a Scope {
let in_math = matches!(
leaf.parent_kind(),
Some(SyntaxKind::Equation)
| Some(SyntaxKind::Math)
| Some(SyntaxKind::MathFrac)
| Some(SyntaxKind::MathAttach)
) && leaf
.prev_leaf()
.is_none_or(|prev| !matches!(prev.kind(), SyntaxKind::Hash));
let library = world.library();
if in_math { library.math.scope() } else { library.global.scope() }
}
/// Checks whether the given value or any of its constituent parts satisfy the
/// predicate.
pub fn check_value_recursively(
value: &Value,
predicate: impl Fn(&Value) -> bool,
) -> bool {
let mut searcher = Searcher { steps: 0, predicate, max_steps: 1000 };
match searcher.find(value) {
ControlFlow::Break(matching) => matching,
ControlFlow::Continue(_) => false,
}
}
/// Recursively searches for a value that passes the filter, but without
/// exceeding a maximum number of search steps.
struct Searcher<F> {
max_steps: usize,
steps: usize,
predicate: F,
}
impl<F> Searcher<F>
where
F: Fn(&Value) -> bool,
{
fn find(&mut self, value: &Value) -> ControlFlow<bool> {
if (self.predicate)(value) {
return ControlFlow::Break(true);
}
if self.steps > self.max_steps {
return ControlFlow::Break(false);
}
self.steps += 1;
match value {
Value::Dict(dict) => {
self.find_iter(dict.iter().map(|(_, v)| v))?;
}
Value::Content(content) => {
self.find_iter(content.fields().iter().map(|(_, v)| v))?;
}
Value::Module(module) => {
self.find_iter(module.scope().iter().map(|(_, b)| b.read()))?;
}
_ => {}
}
ControlFlow::Continue(())
}
fn find_iter<'a>(
&mut self,
iter: impl Iterator<Item = &'a Value>,
) -> ControlFlow<bool> {
for item in iter {
self.find(item)?;
}
ControlFlow::Continue(())
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/crates/typst-ide/src/definition.rs | crates/typst-ide/src/definition.rs | use typst::AsDocument;
use typst::foundations::{Label, Selector, Value};
use typst::syntax::{LinkedNode, Side, Source, Span, ast};
use typst::utils::PicoStr;
use crate::utils::globals;
use crate::{
DerefTarget, IdeWorld, NamedItem, analyze_expr, analyze_import, deref_target,
named_items,
};
/// A definition of some item.
#[derive(Debug, Clone)]
pub enum Definition {
/// The item is defined at the given span.
Span(Span),
/// The item is defined in the standard library.
Std(Value),
}
/// Find the definition of the item under the cursor.
///
/// Passing a `document` (from a previous compilation) is optional, but enhances
/// the definition search. Label definitions, for instance, are only generated
/// when the document is available.
pub fn definition(
world: &dyn IdeWorld,
document: Option<impl AsDocument>,
source: &Source,
cursor: usize,
side: Side,
) -> Option<Definition> {
let root = LinkedNode::new(source.root());
let leaf = root.leaf_at(cursor, side)?;
match deref_target(leaf.clone())? {
// Try to find a named item (defined in this file or an imported file)
// or fall back to a standard library item.
DerefTarget::VarAccess(node) | DerefTarget::Callee(node) => {
let name = node.cast::<ast::Ident>()?.get().clone();
if let Some(src) = named_items(world, node.clone(), |item: NamedItem| {
(*item.name() == name).then(|| Definition::Span(item.span()))
}) {
return Some(src);
};
if let Some((value, _)) = analyze_expr(world, &node).first() {
let span = match value {
Value::Content(content) => content.span(),
Value::Func(func) => func.span(),
_ => Span::detached(),
};
if !span.is_detached() && span != node.span() {
return Some(Definition::Span(span));
}
}
if let Some(binding) = globals(world, &leaf).get(&name) {
return Some(Definition::Std(binding.read().clone()));
}
}
// Try to jump to the an imported file or package.
DerefTarget::ImportPath(node) | DerefTarget::IncludePath(node) => {
let Some(Value::Module(module)) = analyze_import(world, &node) else {
return None;
};
let id = module.file_id()?;
let span = Span::from_range(id, 0..0);
return Some(Definition::Span(span));
}
// Try to jump to the referenced content.
DerefTarget::Ref(node) => {
let label = Label::new(PicoStr::intern(node.cast::<ast::Ref>()?.target()))
.expect("unexpected empty reference");
let selector = Selector::Label(label);
let elem = document?.as_document().introspector().query_first(&selector)?;
return Some(Definition::Span(elem.span()));
}
_ => {}
}
None
}
#[cfg(test)]
mod tests {
use std::borrow::Borrow;
use std::ops::Range;
use typst::WorldExt;
use typst::foundations::{IntoValue, NativeElement};
use typst::layout::PagedDocument;
use typst::syntax::Side;
use super::{Definition, definition};
use crate::tests::{FilePos, TestWorld, WorldLike};
type Response = (TestWorld, Option<Definition>);
trait ResponseExt {
fn must_be_at(&self, path: &str, range: Range<usize>) -> &Self;
fn must_be_value(&self, value: impl IntoValue) -> &Self;
}
impl ResponseExt for Response {
#[track_caller]
fn must_be_at(&self, path: &str, expected: Range<usize>) -> &Self {
match self.1 {
Some(Definition::Span(span)) => {
let range = self.0.range(span);
assert_eq!(
span.id().unwrap().vpath().as_rootless_path().to_string_lossy(),
path
);
assert_eq!(range, Some(expected));
}
_ => panic!("expected span definition"),
}
self
}
#[track_caller]
fn must_be_value(&self, expected: impl IntoValue) -> &Self {
match &self.1 {
Some(Definition::Std(value)) => {
assert_eq!(*value, expected.into_value())
}
_ => panic!("expected std definition"),
}
self
}
}
#[track_caller]
fn test(world: impl WorldLike, pos: impl FilePos, side: Side) -> Response {
let world = world.acquire();
let world = world.borrow();
let doc = typst::compile::<PagedDocument>(world).output.ok();
let (source, cursor) = pos.resolve(world);
let def = definition(world, doc.as_ref(), &source, cursor, side);
(world.clone(), def)
}
#[test]
fn test_definition_let() {
test("#let x; #x", -2, Side::After).must_be_at("main.typ", 5..6);
test("#let x() = {}; #x", -2, Side::After).must_be_at("main.typ", 5..6);
}
#[test]
fn test_definition_field_access_function() {
let world = TestWorld::new("#import \"other.typ\"; #other.foo")
.with_source("other.typ", "#let foo(x) = x + 1");
// The span is at the args here because that's what the function value's
// span is. Not ideal, but also not too big of a big deal.
test(&world, -2, Side::Before).must_be_at("other.typ", 8..11);
}
#[test]
fn test_definition_cross_file() {
let world = TestWorld::new("#import \"other.typ\": x; #x")
.with_source("other.typ", "#let x = 1");
test(&world, -2, Side::After).must_be_at("other.typ", 5..6);
}
#[test]
fn test_definition_import() {
let world = TestWorld::new("#import \"other.typ\" as o: x")
.with_source("other.typ", "#let x = 1");
test(&world, 14, Side::Before).must_be_at("other.typ", 0..0);
}
#[test]
fn test_definition_include() {
let world = TestWorld::new("#include \"other.typ\"")
.with_source("other.typ", "Hello there");
test(&world, 14, Side::Before).must_be_at("other.typ", 0..0);
}
#[test]
fn test_definition_ref() {
test("#figure[] <hi> See @hi", -2, Side::After).must_be_at("main.typ", 1..9);
}
#[test]
fn test_definition_std() {
test("#table", 1, Side::After).must_be_value(typst::model::TableElem::ELEM);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/docs/src/link.rs | docs/src/link.rs | use regex::Regex;
use typst::diag::{StrResult, bail};
use typst::foundations::{Binding, Func, Type};
use crate::{GROUPS, LIBRARY, get_module};
/// Resolve an intra-doc link.
pub fn resolve(link: &str, base: &str) -> StrResult<String> {
if link.starts_with('#') || link.starts_with("http") {
return Ok(link.to_string());
}
if let Some(cap) =
typst_utils::singleton!(Regex, Regex::new(r"^\$((\w+)\/(\w+))?#(\d+)$").unwrap())
.captures(link)
{
let org = cap.get(2).map(|m| m.as_str()).unwrap_or("typst");
let repo = cap.get(3).map(|m| m.as_str()).unwrap_or("typst");
let nr = &cap[4];
return Ok(format!("https://github.com/{org}/{repo}/issues/{nr}"));
}
let (head, tail) = split_link(link);
let mut route = match resolve_known(head, base) {
Some(route) => route,
None => resolve_definition(head, base)?,
};
if !tail.is_empty() {
route.push('/');
route.push_str(tail);
}
if !route.contains(['#', '?']) && !route.ends_with('/') {
route.push('/');
}
Ok(route)
}
/// Split a link at the first slash.
fn split_link(link: &str) -> (&str, &str) {
let first = link.split('/').next().unwrap_or(link);
let rest = link[first.len()..].trim_start_matches('/');
(first, rest)
}
/// Resolve a `$` link head to a known destination.
fn resolve_known(head: &str, base: &str) -> Option<String> {
Some(match head {
"$tutorial" => format!("{base}tutorial"),
"$reference" => format!("{base}reference"),
"$category" => format!("{base}reference"),
"$syntax" => format!("{base}reference/syntax"),
"$styling" => format!("{base}reference/styling"),
"$scripting" => format!("{base}reference/scripting"),
"$context" => format!("{base}reference/context"),
"$html" => format!("{base}reference/html"),
"$pdf" => format!("{base}reference/pdf"),
"$guides" => format!("{base}guides"),
"$changelog" => format!("{base}changelog"),
"$universe" => "https://typst.app/universe".into(),
_ => return None,
})
}
/// Resolve a `$` link to a global definition.
fn resolve_definition(head: &str, base: &str) -> StrResult<String> {
let mut parts = head.trim_start_matches('$').split('.').peekable();
let mut focus = &LIBRARY.global;
let mut category = None;
while let Some(name) = parts.peek() {
if category.is_none() {
category = focus.scope().get(name).and_then(Binding::category);
}
let Ok(module) = get_module(focus, name) else { break };
focus = module;
parts.next();
}
let Some(category) = category else { bail!("{head} has no category") };
let name = parts.next().ok_or("link is missing first part")?;
let value = focus.field(name, ())?;
// Handle grouped functions.
if let Some(group) = GROUPS.iter().find(|group| {
group.category == category && group.filter.iter().any(|func| func == name)
}) {
let mut route = format!(
"{}reference/{}/{}/#functions-{}",
base,
group.category.name(),
group.name,
name
);
if let Some(param) = parts.next() {
route.push('-');
route.push_str(param);
}
return Ok(route);
}
let mut route = format!("{}reference/{}/{name}", base, category.name());
if let Some(next) = parts.next() {
if let Ok(field) = value.field(next, ()) {
// For top-level definitions
route.push_str("/#definitions-");
route.push_str(next);
let mut focus = field;
// For subsequent parameters, definitions, or definitions’ parameters
for next in parts.by_ref() {
if let Ok(field) = focus.field(next, ()) {
// For definitions
route.push_str("-definitions-");
route.push_str(next);
focus = field.clone();
} else if focus
.clone()
.cast::<Func>()
.is_ok_and(|func| func.param(next).is_some())
{
// For parameters
route.push('-');
route.push_str(next);
}
}
} else if let Ok(ty) = value.clone().cast::<Type>()
&& let Ok(func) = ty.constructor()
&& func.param(next).is_some()
{
// For parameters of a constructor function
route.push_str("/#constructor-");
route.push_str(next);
} else if value
.clone()
.cast::<Func>()
.is_ok_and(|func| func.param(next).is_some())
{
// For parameters of a function (except for constructor functions)
route.push_str("/#parameters-");
route.push_str(next);
} else {
bail!("field {next} not found");
}
if let Some(next) = parts.next() {
bail!("found redundant field {next}");
}
}
Ok(route)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_function() {
assert_eq!(
resolve_definition("$figure", "/"),
Ok("/reference/model/figure".into())
);
assert_eq!(
resolve_definition("$figure.body", "/"),
Ok("/reference/model/figure/#parameters-body".into())
);
assert_eq!(
resolve_definition("$figure.caption", "/"),
Ok("/reference/model/figure/#definitions-caption".into())
);
assert_eq!(
resolve_definition("$figure.caption.position", "/"),
Ok("/reference/model/figure/#definitions-caption-position".into())
);
}
#[test]
fn test_function_definition() {
assert_eq!(
resolve_definition("$outline", "/"),
Ok("/reference/model/outline".into())
);
assert_eq!(
resolve_definition("$outline.title", "/"),
Ok("/reference/model/outline/#parameters-title".into())
);
assert_eq!(
resolve_definition("$outline.entry", "/"),
Ok("/reference/model/outline/#definitions-entry".into())
);
assert_eq!(
resolve_definition("$outline.entry.fill", "/"),
Ok("/reference/model/outline/#definitions-entry-fill".into())
);
}
#[test]
fn test_function_definition_definition() {
assert_eq!(
resolve_definition("$outline.entry.indented", "/"),
Ok("/reference/model/outline/#definitions-entry-definitions-indented".into())
);
assert_eq!(
resolve_definition("$outline.entry.indented.prefix", "/"),
Ok("/reference/model/outline/#definitions-entry-definitions-indented-prefix"
.into())
);
}
#[test]
fn test_type() {
assert_eq!(
resolve_definition("$array", "/"),
Ok("/reference/foundations/array".into())
);
assert_eq!(
resolve_definition("$array.at", "/"),
Ok("/reference/foundations/array/#definitions-at".into())
);
assert_eq!(
resolve_definition("$array.at.index", "/"),
Ok("/reference/foundations/array/#definitions-at-index".into())
);
}
#[test]
fn test_type_constructor() {
assert_eq!(
resolve_definition("$str.base", "/"),
Ok("/reference/foundations/str/#constructor-base".into())
);
assert_eq!(
resolve_definition("$tiling.relative", "/"),
Ok("/reference/visualize/tiling/#constructor-relative".into())
);
}
#[test]
fn test_group() {
assert_eq!(
resolve_definition("$calc.abs", "/"),
Ok("/reference/foundations/calc/#functions-abs".into())
);
assert_eq!(
resolve_definition("$calc.pow.exponent", "/"),
Ok("/reference/foundations/calc/#functions-pow-exponent".into())
);
}
#[test]
fn test_redundant_field() {
assert_eq!(
resolve_definition("$figure.body.anything", "/"),
Err("found redundant field anything".into())
);
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/docs/src/html.rs | docs/src/html.rs | use std::fmt::{self, Debug, Formatter};
use std::ops::Range;
use ecow::EcoString;
use heck::{ToKebabCase, ToTitleCase};
use pulldown_cmark as md;
use serde::{Deserialize, Serialize};
use typed_arena::Arena;
use typst::diag::{FileError, FileResult, StrResult};
use typst::foundations::{Bytes, Datetime};
use typst::layout::{Abs, PagedDocument, Point, Size};
use typst::syntax::{FileId, Source, VirtualPath};
use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Library, World};
use unscanny::Scanner;
use yaml_front_matter::YamlFrontMatter;
use crate::{FONTS, LIBRARY, OutlineItem, Resolver, contributors};
/// HTML documentation.
#[derive(Serialize)]
#[serde(transparent)]
pub struct Html {
raw: String,
#[serde(skip)]
md: String,
#[serde(skip)]
outline: Vec<OutlineItem>,
#[serde(skip)]
title: Option<EcoString>,
#[serde(skip)]
description: Option<EcoString>,
}
impl Html {
/// Create HTML from a raw string.
pub fn new(raw: String) -> Self {
Self {
md: String::new(),
raw,
outline: vec![],
title: None,
description: None,
}
}
/// Convert markdown to HTML.
#[track_caller]
pub fn markdown(resolver: &dyn Resolver, md: &str, nesting: Option<usize>) -> Self {
let mut text = md;
let mut description = None;
let mut title = None;
let document = YamlFrontMatter::parse::<Metadata>(md);
if let Ok(document) = &document {
text = &document.content;
title = document.metadata.title.clone();
description = document.metadata.description.clone();
}
let options = md::Options::ENABLE_TABLES
| md::Options::ENABLE_FOOTNOTES
| md::Options::ENABLE_STRIKETHROUGH
| md::Options::ENABLE_HEADING_ATTRIBUTES;
// Convert `[foo]` to `[foo]($foo)`.
let mut link = |broken: md::BrokenLink| {
assert_eq!(
broken.link_type,
md::LinkType::Shortcut,
"unsupported link type: {:?}",
broken.link_type,
);
Some((
format!("${}", broken.reference.trim_matches('`')).into(),
broken.reference.into_string().into(),
))
};
let ids = Arena::new();
let mut handler = Handler::new(text, resolver, nesting, &ids);
let mut events =
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 mut raw = String::new();
md::html::push_html(&mut raw, iter);
raw.truncate(raw.trim_end().len());
Html {
md: text.into(),
raw,
outline: handler.outline,
title,
description,
}
}
/// The raw HTML.
pub fn as_str(&self) -> &str {
&self.raw
}
/// The original Markdown, if any.
pub fn md(&self) -> &str {
&self.md
}
/// The outline of the HTML.
pub fn outline(&self) -> Vec<OutlineItem> {
self.outline.clone()
}
/// The title of the HTML.
///
/// Returns `None` if the HTML doesn't start with an `h1` tag.
pub fn title(&self) -> Option<&str> {
self.title.as_deref().or_else(|| {
let mut s = Scanner::new(&self.raw);
s.eat_if("<h1").then(|| {
s.eat_until('>');
s.eat_if('>');
s.eat_until("</h1>")
})
})
}
/// The description from the front matter.
pub fn description(&self) -> Option<EcoString> {
self.description.clone()
}
}
impl Debug for Html {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Html({:?})", self.title().unwrap_or(".."))
}
}
/// Front matter metadata.
#[derive(Deserialize)]
struct Metadata {
title: Option<EcoString>,
description: Option<EcoString>,
}
struct Handler<'a> {
text: &'a str,
resolver: &'a dyn Resolver,
peeked: Option<md::CowStr<'a>>,
lang: Option<EcoString>,
code: EcoString,
outline: Vec<OutlineItem>,
nesting: Option<usize>,
ids: &'a Arena<String>,
}
impl<'a> Handler<'a> {
fn new(
text: &'a str,
resolver: &'a dyn Resolver,
nesting: Option<usize>,
ids: &'a Arena<String>,
) -> Self {
Self {
text,
resolver,
peeked: None,
lang: None,
code: EcoString::new(),
outline: vec![],
nesting,
ids,
}
}
fn handle(&mut self, event: &mut md::Event<'a>) -> bool {
match event {
// Rewrite Markdown images.
md::Event::Start(md::Tag::Image(_, path, _)) => {
*path = self.handle_image(path).into();
}
// Rewrite HTML images.
md::Event::Html(html) if html.starts_with("<img") => {
let range = html_attr_range(html, "src").unwrap();
let path = &html[range.clone()];
let mut buf = html.to_string();
buf.replace_range(range, &self.handle_image(path));
*html = buf.into();
}
// Register HTML headings for the outline.
md::Event::Start(md::Tag::Heading(level, id, _)) => {
self.handle_heading(id, level);
}
// Also handle heading closings.
md::Event::End(md::Tag::Heading(level, _, _)) => {
nest_heading(level, self.nesting());
}
// Rewrite contributor sections.
md::Event::Html(html) if html.starts_with("<contributors") => {
let from = html_attr(html, "from").unwrap();
let to = html_attr(html, "to").unwrap();
let Some(output) = contributors(self.resolver, from, to) else {
return false;
};
*html = output.raw.into();
}
// Rewrite links.
md::Event::Start(md::Tag::Link(ty, dest, _)) => {
assert!(
matches!(
ty,
md::LinkType::Inline
| md::LinkType::Reference
| md::LinkType::ShortcutUnknown
| md::LinkType::Autolink
),
"unsupported link type: {ty:?}",
);
*dest = match self.handle_link(dest) {
Ok(link) => link.into(),
Err(err) => panic!("invalid link: {dest} ({err})"),
};
}
// Inline raw.
md::Event::Code(code) => {
let mut chars = code.chars();
let parser = match (chars.next(), chars.next_back()) {
(Some('['), Some(']')) => typst::syntax::parse,
(Some('{'), Some('}')) => typst::syntax::parse_code,
_ => return true,
};
let root = parser(&code[1..code.len() - 1]);
let html = typst::syntax::highlight_html(&root);
*event = md::Event::Html(html.into());
}
// Code blocks.
md::Event::Start(md::Tag::CodeBlock(md::CodeBlockKind::Fenced(lang))) => {
self.lang = Some(lang.as_ref().into());
self.code = EcoString::new();
return false;
}
md::Event::End(md::Tag::CodeBlock(md::CodeBlockKind::Fenced(_))) => {
let Some(lang) = self.lang.take() else { return false };
let html = code_block(self.resolver, &lang, &self.code);
*event = md::Event::Html(html.raw.into());
}
// Example with preview.
md::Event::Text(text) => {
if self.lang.is_some() {
self.code.push_str(text);
return false;
}
}
_ => {}
}
true
}
fn handle_image(&self, link: &str) -> String {
if let Some(data) = typst_dev_assets::get_by_name(link) {
self.resolver.image(link, data)
} else if let Some(url) = self.resolver.link(link) {
url
} else {
panic!("missing image: {link}")
}
}
fn handle_heading(
&mut self,
id_slot: &mut Option<&'a str>,
level: &mut md::HeadingLevel,
) {
nest_heading(level, self.nesting());
if *level == md::HeadingLevel::H1 {
return;
}
let body = self.peeked.as_ref();
let default = body.map(|text| text.to_kebab_case());
let has_id = id_slot.is_some();
let id: &'a str = match (&id_slot, default) {
(Some(id), default) => {
if Some(*id) == default.as_deref() {
eprintln!("heading id #{id} was specified unnecessarily");
}
id
}
(None, Some(default)) => self.ids.alloc(default).as_str(),
(None, None) => panic!("missing heading id {}", self.text),
};
*id_slot = (!id.is_empty()).then_some(id);
// Special case for things like "v0.3.0".
let name = match &body {
_ if id.starts_with('v') && id.contains('.') => id.into(),
Some(body) if !has_id => body.as_ref().into(),
_ => id.to_title_case().into(),
};
let mut children = &mut self.outline;
let mut depth = *level as usize;
while depth > 2 {
if !children.is_empty() {
children = &mut children.last_mut().unwrap().children;
}
depth -= 1;
}
children.push(OutlineItem { id: id.into(), name, children: vec![] });
}
fn handle_link(&self, link: &str) -> StrResult<String> {
if let Some(link) = self.resolver.link(link) {
return Ok(link);
}
crate::link::resolve(link, self.resolver.base())
}
fn nesting(&self) -> usize {
match self.nesting {
Some(nesting) => nesting,
None => panic!("headings are not allowed here:\n{}", self.text),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ExampleArgs<'a> {
/// The language of the example.
pub lang: &'a str,
/// How to display the example.
pub view: ExampleView,
/// An optional title for the example.
pub title: Option<&'a str>,
}
impl<'a> ExampleArgs<'a> {
/// Parse a language tag.
pub fn from_tag(tag: &'a str) -> Self {
let mut parts = tag.split(':');
let lang = parts.next().unwrap_or(tag);
let mut view = ExampleView::default();
let mut title = None;
for args in parts {
if let Some(inner) =
args.strip_prefix('"').and_then(|rest| rest.strip_suffix('"'))
{
title = Some(inner);
} else if args.contains("single") {
view = ExampleView::Single(None);
} else if args.chars().next().is_some_and(char::is_numeric) {
view = ExampleView::Single(
args.split(',')
.take(4)
.map(|s| Abs::pt(s.parse().unwrap()))
.collect::<Vec<_>>()
.try_into()
.ok(),
)
} else if args == "all" {
// Default.
} else {
panic!("invalid example arguments: {args}");
}
}
Self { lang, view, title }
}
}
#[derive(Debug, Clone, Copy, Default)]
pub enum ExampleView {
/// Display all pages
#[default]
All,
/// Display a single page
Single(Option<[Abs; 4]>),
}
/// Render a code block to HTML.
fn code_block(resolver: &dyn Resolver, tag: &str, text: &str) -> Html {
let mut display = String::new();
let mut compile = String::new();
for line in text.lines() {
if let Some(suffix) = line.strip_prefix(">>>") {
compile.push_str(suffix);
compile.push('\n');
} else if let Some(suffix) = line.strip_prefix("<<< ") {
display.push_str(suffix);
display.push('\n');
} else {
display.push_str(line);
display.push('\n');
compile.push_str(line);
compile.push('\n');
}
}
let args = ExampleArgs::from_tag(tag);
let lang = args.lang;
if lang.is_empty() {
let mut buf = String::from("<pre>");
md::escape::escape_html(&mut buf, &display).unwrap();
buf.push_str("</pre>");
return Html::new(buf);
} else if !matches!(lang, "example" | "typ" | "preview") {
let set = &*typst::text::RAW_SYNTAXES;
let buf = syntect::html::highlighted_html_for_string(
&display,
set,
set.find_syntax_by_token(lang)
.unwrap_or_else(|| panic!("unsupported highlighting language: {lang}")),
&typst::text::RAW_THEME,
)
.expect("failed to highlight code");
return Html::new(buf);
}
let mut highlighted = None;
if matches!(lang, "example" | "typ") {
let root = typst::syntax::parse(&display);
let html = Html::new(typst::syntax::highlight_html(&root));
if lang == "typ" {
return Html::new(format!("<pre>{}</pre>", html.as_str()));
}
highlighted = Some(html);
}
let id = FileId::new(None, VirtualPath::new("main.typ"));
let source = Source::new(id, compile);
let world = DocWorld(source);
let mut document = match typst::compile::<PagedDocument>(&world).output {
Ok(doc) => doc,
Err(err) => {
let msg = &err[0].message;
panic!("while trying to compile:\n{text}:\n\nerror: {msg}");
}
};
if let ExampleView::Single(Some([x, y, w, h])) = args.view {
document.pages[0].frame.translate(Point::new(-x, -y));
*document.pages[0].frame.size_mut() = Size::new(w, h);
}
if let ExampleView::Single(_) = args.view {
document.pages.truncate(1);
}
let hash = typst::utils::hash128(&(lang, text));
resolver.example(hash, highlighted, &document)
}
/// Extract an attribute value from an HTML element.
fn html_attr<'a>(html: &'a str, attr: &str) -> Option<&'a str> {
html.get(html_attr_range(html, attr)?)
}
/// Extract the range of the attribute value of an HTML element.
fn html_attr_range(html: &str, attr: &str) -> Option<Range<usize>> {
let needle = format!("{attr}=\"");
let offset = html.find(&needle)? + needle.len();
let len = html[offset..].find('"')?;
Some(offset..offset + len)
}
/// Increase the nesting level of a Markdown heading.
fn nest_heading(level: &mut md::HeadingLevel, nesting: usize) {
*level = ((*level as usize) + nesting)
.try_into()
.unwrap_or(md::HeadingLevel::H6);
}
/// A world for example compilations.
struct DocWorld(Source);
impl World for DocWorld {
fn library(&self) -> &LazyHash<Library> {
&LIBRARY
}
fn book(&self) -> &LazyHash<FontBook> {
&FONTS.0
}
fn main(&self) -> FileId {
self.0.id()
}
fn source(&self, id: FileId) -> FileResult<Source> {
if id == self.0.id() {
Ok(self.0.clone())
} else {
Err(FileError::NotFound(id.vpath().as_rootless_path().into()))
}
}
fn file(&self, id: FileId) -> FileResult<Bytes> {
assert!(id.package().is_none());
Ok(Bytes::new(
typst_dev_assets::get_by_name(
&id.vpath().as_rootless_path().to_string_lossy(),
)
.unwrap_or_else(|| panic!("failed to load {:?}", id.vpath())),
))
}
fn font(&self, index: usize) -> Option<Font> {
FONTS.1.get(index).cloned()
}
fn today(&self, _: Option<i64>) -> Option<Datetime> {
Some(Datetime::from_ymd(1970, 1, 1).unwrap())
}
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/docs/src/lib.rs | docs/src/lib.rs | //! Documentation provider for Typst.
mod contribs;
mod html;
mod link;
mod model;
pub use self::contribs::*;
pub use self::html::*;
pub use self::model::*;
use ecow::{EcoString, eco_format};
use heck::ToTitleCase;
use rustc_hash::FxHashSet;
use serde::Deserialize;
use serde_yaml as yaml;
use std::sync::LazyLock;
use typst::diag::{StrResult, bail};
use typst::foundations::Deprecation;
use typst::foundations::{
AutoValue, Binding, Bytes, CastInfo, Func, Module, NoneValue, ParamInfo, Repr, Scope,
Smart, Type, Value,
};
use typst::layout::{Abs, Margin, PageElem, PagedDocument};
use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Category, Feature, Library, LibraryExt};
use unicode_math_class::MathClass;
macro_rules! load {
($path:literal) => {
include_str!(concat!("../", $path))
};
}
static GROUPS: LazyLock<Vec<GroupData>> = LazyLock::new(|| {
let mut groups: Vec<GroupData> =
yaml::from_str(load!("reference/groups.yml")).unwrap();
for group in &mut groups {
if group.filter.is_empty() && group.name != "std" {
group.filter = group
.module()
.scope()
.iter()
.filter(|(_, b)| matches!(b.read(), Value::Func(_)))
.map(|(k, _)| k.clone())
.collect();
}
if group.name == "typed" {
group.filter = typst_assets::html::ELEMS
.iter()
.map(|elem| elem.name.into())
.collect();
}
}
groups
});
static LIBRARY: LazyLock<LazyHash<Library>> = LazyLock::new(|| {
let mut lib = Library::builder()
.with_features([Feature::Html, Feature::A11yExtras].into_iter().collect())
.build();
let scope = lib.global.scope_mut();
// Add those types, so that they show up in the docs.
scope.start_category(Category::Foundations);
scope.define_type::<NoneValue>();
scope.define_type::<AutoValue>();
scope.reset_category();
// Adjust the default look.
lib.styles.set(PageElem::width, Smart::Custom(Abs::pt(240.0).into()));
lib.styles.set(PageElem::height, Smart::Auto);
lib.styles
.set(PageElem::margin, Margin::splat(Some(Smart::Custom(Abs::pt(15.0).into()))));
LazyHash::new(lib)
});
static FONTS: LazyLock<(LazyHash<FontBook>, Vec<Font>)> = LazyLock::new(|| {
let fonts: Vec<_> = typst_assets::fonts()
.chain(typst_dev_assets::fonts())
.flat_map(|data| Font::iter(Bytes::new(data)))
.collect();
let book = FontBook::from_fonts(&fonts);
(LazyHash::new(book), fonts)
});
/// Build documentation pages.
pub fn provide(resolver: &dyn Resolver) -> Vec<PageModel> {
let base = resolver.base();
vec![
md_page(resolver, base, load!("overview.md")).with_route(base),
tutorial_pages(resolver),
reference_pages(resolver),
guide_pages(resolver),
changelog_pages(resolver),
]
}
/// Resolve consumer dependencies.
pub trait Resolver {
/// Try to resolve a link. If this returns `None`, the system will try to
/// resolve the link itself.
fn link(&self, link: &str) -> Option<String>;
/// Produce an URL for an image file.
fn image(&self, filename: &str, data: &[u8]) -> String;
/// Produce HTML for an example.
fn example(&self, hash: u128, source: Option<Html>, document: &PagedDocument)
-> Html;
/// Determine the commits between two tags.
fn commits(&self, from: &str, to: &str) -> Vec<Commit>;
/// Get the base URL for the routes and links. This must end with a slash.
fn base(&self) -> &str;
}
/// Create a page from a markdown file.
#[track_caller]
fn md_page(resolver: &dyn Resolver, parent: &str, md: &str) -> PageModel {
md_page_with_title(resolver, parent, md, None)
}
/// Create a page from a markdown file.
#[track_caller]
fn md_page_with_title(
resolver: &dyn Resolver,
parent: &str,
md: &str,
title: Option<&str>,
) -> PageModel {
assert!(parent.starts_with('/') && parent.ends_with('/'));
let html = Html::markdown(resolver, md, Some(0));
let title = title.or(html.title()).expect("chapter lacks a title");
PageModel {
route: eco_format!("{parent}{}/", urlify(title)),
title: title.into(),
description: html.description().expect("chapter lacks a description"),
part: None,
outline: html.outline(),
body: BodyModel::Html(html),
children: vec![],
}
}
/// Build the tutorial.
fn tutorial_pages(resolver: &dyn Resolver) -> PageModel {
let mut page = md_page(resolver, resolver.base(), load!("tutorial/welcome.md"));
let base = format!("{}tutorial/", resolver.base());
page.children = vec![
md_page(resolver, &base, load!("tutorial/1-writing.md")),
md_page(resolver, &base, load!("tutorial/2-formatting.md")),
md_page(resolver, &base, load!("tutorial/3-advanced.md")),
md_page(resolver, &base, load!("tutorial/4-template.md")),
];
page
}
/// Build the reference.
fn reference_pages(resolver: &dyn Resolver) -> PageModel {
let mut page = md_page(resolver, resolver.base(), load!("reference/welcome.md"));
let base = format!("{}reference/", resolver.base());
page.children = vec![
md_page(resolver, &base, load!("reference/language/syntax.md"))
.with_part("Language"),
md_page(resolver, &base, load!("reference/language/styling.md")),
md_page(resolver, &base, load!("reference/language/scripting.md")),
md_page(resolver, &base, load!("reference/language/context.md")),
category_page(resolver, Category::Foundations).with_part("Library"),
category_page(resolver, Category::Model),
category_page(resolver, Category::Text),
category_page(resolver, Category::Math),
category_page(resolver, Category::Symbols),
category_page(resolver, Category::Layout),
category_page(resolver, Category::Visualize),
category_page(resolver, Category::Introspection),
category_page(resolver, Category::DataLoading),
category_page(resolver, Category::Pdf).with_part("Export"),
category_page(resolver, Category::Html),
category_page(resolver, Category::Png),
category_page(resolver, Category::Svg),
];
page
}
/// Build the guides section.
fn guide_pages(resolver: &dyn Resolver) -> PageModel {
let mut page = md_page(resolver, resolver.base(), load!("guides/welcome.md"));
let base = format!("{}guides/", resolver.base());
page.children = vec![
md_page_with_title(
resolver,
&base,
load!("guides/guide-for-latex-users.md"),
Some("For LaTeX Users"),
),
md_page_with_title(
resolver,
&base,
load!("guides/page-setup.md"),
Some("Page Setup"),
),
md_page_with_title(resolver, &base, load!("guides/tables.md"), Some("Tables")),
md_page_with_title(
resolver,
&base,
load!("guides/accessibility.md"),
Some("Accessibility"),
),
];
page
}
/// Build the changelog section.
fn changelog_pages(resolver: &dyn Resolver) -> PageModel {
let mut page = md_page(resolver, resolver.base(), load!("changelog/welcome.md"));
let base = format!("{}changelog/", resolver.base());
page.children = vec![
md_page(resolver, &base, load!("changelog/0.14.2.md")),
md_page(resolver, &base, load!("changelog/0.14.1.md")),
md_page(resolver, &base, load!("changelog/0.14.0.md")),
md_page(resolver, &base, load!("changelog/0.13.1.md")),
md_page(resolver, &base, load!("changelog/0.13.0.md")),
md_page(resolver, &base, load!("changelog/0.12.0.md")),
md_page(resolver, &base, load!("changelog/0.11.1.md")),
md_page(resolver, &base, load!("changelog/0.11.0.md")),
md_page(resolver, &base, load!("changelog/0.10.0.md")),
md_page(resolver, &base, load!("changelog/0.9.0.md")),
md_page(resolver, &base, load!("changelog/0.8.0.md")),
md_page(resolver, &base, load!("changelog/0.7.0.md")),
md_page(resolver, &base, load!("changelog/0.6.0.md")),
md_page(resolver, &base, load!("changelog/0.5.0.md")),
md_page(resolver, &base, load!("changelog/0.4.0.md")),
md_page(resolver, &base, load!("changelog/0.3.0.md")),
md_page(resolver, &base, load!("changelog/0.2.0.md")),
md_page(resolver, &base, load!("changelog/0.1.0.md")),
md_page(resolver, &base, load!("changelog/earlier.md")),
];
page
}
/// Create a page for a category.
#[track_caller]
fn category_page(resolver: &dyn Resolver, category: Category) -> PageModel {
let route = eco_format!("{}reference/{}/", resolver.base(), category.name());
let mut children = vec![];
let mut items = vec![];
let mut shorthands = None;
let mut markup = vec![];
let mut math = vec![];
let docs = category_docs(category);
let (module, path): (&Module, &[&str]) = match category {
Category::Math => (&LIBRARY.math, &["math"]),
Category::Pdf => (get_module(&LIBRARY.global, "pdf").unwrap(), &["pdf"]),
Category::Html => (get_module(&LIBRARY.global, "html").unwrap(), &["html"]),
_ => (&LIBRARY.global, &[]),
};
// Add groups.
for group in GROUPS.iter().filter(|g| g.category == category).cloned() {
if matches!(group.name.as_str(), "sym" | "emoji") {
let subpage = symbols_page(resolver, &route, &group);
let BodyModel::Symbols(model) = &subpage.body else { continue };
let list = &model.list;
markup.extend(
list.iter()
.filter(|symbol| symbol.markup_shorthand.is_some())
.cloned(),
);
math.extend(
list.iter().filter(|symbol| symbol.math_shorthand.is_some()).cloned(),
);
items.push(CategoryItem {
name: group.name.clone(),
route: subpage.route.clone(),
oneliner: oneliner(docs),
code: true,
});
children.push(subpage);
continue;
}
let (child, item) = group_page(resolver, &route, &group);
children.push(child);
items.push(item);
}
// Add symbol pages. These are ordered manually.
if category == Category::Symbols {
shorthands = Some(ShorthandsModel { markup, math });
}
let mut skip: FxHashSet<&str> = GROUPS
.iter()
.filter(|g| g.category == category)
.flat_map(|g| &g.filter)
.map(|s| s.as_str())
.collect();
if category == Category::Math {
// Already documented in the text category.
skip.insert("text");
}
// Tiling would be duplicate otherwise.
if category == Category::Visualize {
skip.insert("pattern");
}
// PDF attach would be duplicate otherwise.
if category == Category::Pdf {
skip.insert("embed");
}
// Add values and types.
let scope = module.scope();
for (name, binding) in scope.iter() {
if binding.category() != Some(category) {
continue;
}
if skip.contains(name.as_str()) {
continue;
}
match binding.read() {
Value::Func(func) => {
let name = func.name().unwrap();
let subpage =
func_page(resolver, &route, func, path, binding.deprecation());
items.push(CategoryItem {
name: name.into(),
route: subpage.route.clone(),
oneliner: oneliner(func.docs().unwrap_or_default()),
code: true,
});
children.push(subpage);
}
Value::Type(ty) => {
let subpage = type_page(resolver, &route, ty);
items.push(CategoryItem {
name: ty.short_name().into(),
route: subpage.route.clone(),
oneliner: oneliner(ty.docs()),
code: true,
});
children.push(subpage);
}
_ => {}
}
}
if category != Category::Symbols {
children.sort_by_cached_key(|child| child.title.clone());
items.sort_by_cached_key(|item| item.name.clone());
}
let title = EcoString::from(match category {
Category::Pdf | Category::Html | Category::Png | Category::Svg => {
category.name().to_uppercase()
}
_ => category.name().to_title_case(),
});
let details = Html::markdown(resolver, docs, Some(1));
let mut outline = vec![OutlineItem::from_name("Summary")];
outline.extend(details.outline());
if !items.is_empty() {
outline.push(OutlineItem::from_name("Definitions"));
}
if shorthands.is_some() {
outline.push(OutlineItem::from_name("Shorthands"));
}
PageModel {
route,
title: title.clone(),
description: eco_format!(
"Documentation for functions related to {title} in Typst."
),
part: None,
outline,
body: BodyModel::Category(CategoryModel {
name: category.name(),
title,
details,
items,
shorthands,
}),
children,
}
}
/// Retrieve the docs for a category.
fn category_docs(category: Category) -> &'static str {
match category {
Category::Foundations => load!("reference/library/foundations.md"),
Category::Introspection => load!("reference/library/introspection.md"),
Category::Layout => load!("reference/library/layout.md"),
Category::DataLoading => load!("reference/library/data-loading.md"),
Category::Math => load!("reference/library/math.md"),
Category::Model => load!("reference/library/model.md"),
Category::Symbols => load!("reference/library/symbols.md"),
Category::Text => load!("reference/library/text.md"),
Category::Visualize => load!("reference/library/visualize.md"),
Category::Pdf => load!("reference/export/pdf.md"),
Category::Html => load!("reference/export/html.md"),
Category::Svg => load!("reference/export/svg.md"),
Category::Png => load!("reference/export/png.md"),
}
}
/// Create a page for a function.
fn func_page(
resolver: &dyn Resolver,
parent: &str,
func: &Func,
path: &[&str],
deprecation: Option<&Deprecation>,
) -> PageModel {
let model = func_model(resolver, func, path, false, deprecation);
let name = func.name().unwrap();
PageModel {
route: eco_format!("{parent}{}/", urlify(name)),
title: func.title().unwrap().into(),
description: eco_format!("Documentation for the `{name}` function."),
part: None,
outline: func_outline(&model, ""),
body: BodyModel::Func(model),
children: vec![],
}
}
/// Produce a function's model.
fn func_model(
resolver: &dyn Resolver,
func: &Func,
path: &[&str],
nested: bool,
deprecation: Option<&Deprecation>,
) -> FuncModel {
let name = func.name().unwrap();
let scope = func.scope().unwrap();
let docs = func.docs().unwrap();
let mut self_ = false;
let mut params = func.params().unwrap();
if params.first().is_some_and(|first| first.name == "self") {
self_ = true;
params = ¶ms[1..];
}
let mut returns = vec![];
let mut strings = vec![];
casts(resolver, &mut returns, &mut strings, func.returns().unwrap());
if !strings.is_empty() && !returns.contains(&"str") {
returns.push("str");
}
returns.sort_by_key(|ty| type_index(ty));
if returns == ["none"] {
returns.clear();
}
let nesting = if nested { None } else { Some(1) };
let items =
if nested { details_blocks(docs) } else { vec![RawDetailsBlock::Markdown(docs)] };
let Some(first_md) = items.iter().find_map(|item| {
if let RawDetailsBlock::Markdown(md) = item { Some(md) } else { None }
}) else {
panic!("function lacks any details")
};
let mut params = params.to_vec();
if func.keywords().contains(&"typed-html") {
params.retain(|param| !is_global_html_attr(param.name));
}
FuncModel {
path: path.iter().copied().map(Into::into).collect(),
name: name.into(),
title: func.title().unwrap(),
keywords: func.keywords(),
oneliner: oneliner(first_md),
element: func.to_element().is_some(),
contextual: func.contextual().unwrap_or(false),
deprecation_message: deprecation.map(Deprecation::message),
deprecation_until: deprecation.and_then(Deprecation::until),
details: items
.into_iter()
.map(|proto| proto.into_model(resolver, nesting))
.collect(),
self_,
params: params.iter().map(|param| param_model(resolver, param)).collect(),
returns,
scope: scope_models(resolver, name, scope),
}
}
/// Produce a parameter's model.
fn param_model(resolver: &dyn Resolver, info: &ParamInfo) -> ParamModel {
let mut types = vec![];
let mut strings = vec![];
casts(resolver, &mut types, &mut strings, &info.input);
if !strings.is_empty() && !types.contains(&"str") {
types.push("str");
}
types.sort_by_key(|ty| type_index(ty));
ParamModel {
name: info.name,
details: details_blocks(info.docs)
.into_iter()
.map(|proto| proto.into_model(resolver, None))
.collect(),
types,
strings,
default: info.default.map(|default| {
let node = typst::syntax::parse_code(&default().repr());
Html::new(typst::syntax::highlight_html(&node))
}),
positional: info.positional,
named: info.named,
required: info.required,
variadic: info.variadic,
settable: info.settable,
}
}
/// A details block that has not yet been processed.
enum RawDetailsBlock<'a> {
/// Raw Markdown.
Markdown(&'a str),
/// An example with an optional title.
Example { body: &'a str, title: Option<&'a str> },
}
impl<'a> RawDetailsBlock<'a> {
fn into_model(self, resolver: &dyn Resolver, nesting: Option<usize>) -> DetailsBlock {
match self {
RawDetailsBlock::Markdown(md) => {
DetailsBlock::Html(Html::markdown(resolver, md, nesting))
}
RawDetailsBlock::Example { body, title } => DetailsBlock::Example {
body: Html::markdown(resolver, body, None),
title: title.map(Into::into),
},
}
}
}
/// Split up documentation into Markdown blocks and examples.
fn details_blocks(docs: &str) -> Vec<RawDetailsBlock<'_>> {
let mut i = 0;
let mut res = Vec::new();
while i < docs.len() {
match find_fence_start(&docs[i..]) {
Some((found, fence_len)) => {
let fence_idx = i + found;
// Find the language tag of the fence, if any.
let lang_tag_end = docs[fence_idx + fence_len..]
.find('\n')
.map(|end| fence_idx + fence_len + end)
.unwrap_or(docs.len());
let tag = &docs[fence_idx + fence_len..lang_tag_end].trim();
let title = ExampleArgs::from_tag(tag).title;
// First, push non-fenced content. It might be all whitespaces
// if it's between two consecutive fences. Therefore, we have to
// trim it before checking.
let content_before_fence = &docs[i..fence_idx];
if !content_before_fence.trim().is_empty() {
res.push(RawDetailsBlock::Markdown(content_before_fence));
}
// Then, find the end of the fence.
let offset = fence_idx + fence_len;
let Some(fence_end) = docs[offset..]
.find(&"`".repeat(fence_len))
.map(|end| offset + end + fence_len)
else {
panic!(
"unclosed code fence in docs at position {}: {}",
fence_idx,
&docs[fence_idx..]
);
};
res.push(RawDetailsBlock::Example {
body: &docs[fence_idx..fence_end],
title,
});
i = fence_end;
}
None => {
// Push the remaining content only if it's non-empty after trimming.
let slice = &docs[i..];
if !slice.trim().is_empty() {
res.push(RawDetailsBlock::Markdown(slice));
}
break;
}
}
}
res
}
/// Returns the start of a code fence and how many backticks it uses.
fn find_fence_start(md: &str) -> Option<(usize, usize)> {
let start = md.find("```")?;
let mut count = 3;
while md[start + count..].starts_with('`') {
count += 1;
}
Some((start, count))
}
/// Process cast information into types and strings.
fn casts(
resolver: &dyn Resolver,
types: &mut Vec<&'static str>,
strings: &mut Vec<StrParam>,
info: &CastInfo,
) {
match info {
CastInfo::Any => types.push("any"),
CastInfo::Value(Value::Str(string), docs) => strings.push(StrParam {
string: string.clone().into(),
details: Html::markdown(resolver, docs, None),
}),
CastInfo::Value(..) => {}
CastInfo::Type(ty) => types.push(ty.short_name()),
CastInfo::Union(options) => {
for option in options {
casts(resolver, types, strings, option);
}
}
}
}
/// Produce models for a function's scope.
fn scope_models(resolver: &dyn Resolver, name: &str, scope: &Scope) -> Vec<FuncModel> {
scope
.iter()
.filter_map(|(_, binding)| {
let Value::Func(func) = binding.read() else { return None };
Some(func_model(resolver, func, &[name], true, binding.deprecation()))
})
.collect()
}
/// Produce an outline for a function page.
fn func_outline(model: &FuncModel, id_base: &str) -> Vec<OutlineItem> {
let mut outline = vec![];
if id_base.is_empty() {
outline.push(OutlineItem::from_name("Summary"));
for block in &model.details {
if let DetailsBlock::Html(html) = block {
outline.extend(html.outline());
}
}
if !model.params.is_empty() {
outline.push(OutlineItem {
id: "parameters".into(),
name: "Parameters".into(),
children: model
.params
.iter()
.map(|param| OutlineItem {
id: eco_format!("parameters-{}", urlify(param.name)),
name: param.name.into(),
children: vec![],
})
.collect(),
});
}
} else {
outline.extend(model.params.iter().map(|param| OutlineItem {
id: eco_format!("{id_base}-{}", urlify(param.name)),
name: param.name.into(),
children: vec![],
}));
}
outline.extend(scope_outline(&model.scope, id_base));
outline
}
/// Produce an outline for a function scope.
fn scope_outline(scope: &[FuncModel], id_base: &str) -> Option<OutlineItem> {
if scope.is_empty() {
return None;
}
let dash = if id_base.is_empty() { "" } else { "-" };
let id = eco_format!("{id_base}{dash}definitions");
let children = scope
.iter()
.map(|func| {
let id = urlify(&eco_format!("{id}-{}", func.name));
let children = func_outline(func, &id);
OutlineItem { id, name: func.title.into(), children }
})
.collect();
Some(OutlineItem { id, name: "Definitions".into(), children })
}
/// Create a page for a group of functions.
fn group_page(
resolver: &dyn Resolver,
parent: &str,
group: &GroupData,
) -> (PageModel, CategoryItem) {
let mut functions = vec![];
let mut outline = vec![OutlineItem::from_name("Summary")];
let path: Vec<_> = group.path.iter().map(|s| s.as_str()).collect();
let details = Html::markdown(resolver, &group.details, Some(1));
outline.extend(details.outline());
let mut outline_items = vec![];
for name in &group.filter {
let binding = group.module().scope().get(name).unwrap();
let Ok(ref func) = binding.read().clone().cast::<Func>() else {
panic!("not a function")
};
let func = func_model(resolver, func, &path, true, binding.deprecation());
let id_base = urlify(&eco_format!("functions-{}", func.name));
let children = func_outline(&func, &id_base);
outline_items.push(OutlineItem {
id: id_base,
name: func.title.into(),
children,
});
functions.push(func);
}
outline.push(OutlineItem {
id: "functions".into(),
name: "Functions".into(),
children: outline_items,
});
let global_attributes = if group.name == "typed" {
let div = group.module().scope().get("div").unwrap();
let func = div.read().clone().cast::<Func>().unwrap();
func.params()
.unwrap()
.iter()
.filter(|param| is_global_html_attr(param.name))
.map(|info| param_model(resolver, info))
.collect()
} else {
vec![]
};
if !global_attributes.is_empty() {
let id = "global-attributes";
outline.push(OutlineItem {
id: id.into(),
name: "Global Attributes".into(),
children: global_attributes
.iter()
.map(|param| OutlineItem {
id: eco_format!("{id}-{}", urlify(param.name)),
name: param.name.into(),
children: vec![],
})
.collect(),
});
}
let model = PageModel {
route: eco_format!("{parent}{}/", group.name),
title: group.title.clone(),
description: eco_format!("Documentation for the {} functions.", group.name),
part: None,
outline,
body: BodyModel::Group(GroupModel {
name: group.name.clone(),
title: group.title.clone(),
details,
functions,
global_attributes,
}),
children: vec![],
};
let item = CategoryItem {
name: group.name.clone(),
route: model.route.clone(),
oneliner: oneliner(&group.details),
code: false,
};
(model, item)
}
/// Whether the given `name` is one of a global HTML attribute (shared by all
/// elements).
fn is_global_html_attr(name: &str) -> bool {
use typst_assets::html as data;
data::ATTRS[..data::ATTRS_GLOBAL]
.iter()
.any(|global| global.name == name)
}
/// Create a page for a type.
fn type_page(resolver: &dyn Resolver, parent: &str, ty: &Type) -> PageModel {
let model = type_model(resolver, ty);
PageModel {
route: eco_format!("{parent}{}/", urlify(ty.short_name())),
title: ty.title().into(),
description: eco_format!("Documentation for the {} type.", ty.title()),
part: None,
outline: type_outline(&model),
body: BodyModel::Type(model),
children: vec![],
}
}
/// Produce a type's model.
fn type_model(resolver: &dyn Resolver, ty: &Type) -> TypeModel {
TypeModel {
name: ty.short_name(),
title: ty.title(),
keywords: ty.keywords(),
oneliner: oneliner(ty.docs()),
details: Html::markdown(resolver, ty.docs(), Some(1)),
constructor: ty
.constructor()
.ok()
.map(|func| func_model(resolver, &func, &[], true, None)),
scope: scope_models(resolver, ty.short_name(), ty.scope()),
}
}
/// Produce an outline for a type page.
fn type_outline(model: &TypeModel) -> Vec<OutlineItem> {
let mut outline = vec![OutlineItem::from_name("Summary")];
outline.extend(model.details.outline());
if let Some(func) = &model.constructor {
outline.push(OutlineItem {
id: "constructor".into(),
name: "Constructor".into(),
children: func_outline(func, "constructor"),
});
}
outline.extend(scope_outline(&model.scope, ""));
outline
}
/// Create a page for symbols.
fn symbols_page(resolver: &dyn Resolver, parent: &str, group: &GroupData) -> PageModel {
let model = symbols_model(resolver, group);
PageModel {
route: eco_format!("{parent}{}/", group.name),
title: group.title.clone(),
description: eco_format!("Documentation for the `{}` module.", group.name),
part: None,
outline: vec![],
body: BodyModel::Symbols(model),
children: vec![],
}
}
/// Produce a symbol list's model.
fn symbols_model(resolver: &dyn Resolver, group: &GroupData) -> SymbolsModel {
let mut list = vec![];
for (name, binding) in group.module().scope().iter() {
let Value::Symbol(symbol) = binding.read() else { continue };
let complete = |variant: codex::ModifierSet<&str>| {
if variant.is_empty() {
name.clone()
} else {
eco_format!("{}.{}", name, variant.as_str())
}
};
for (variant, value, deprecation_message) in symbol.variants() {
let value_char = value.parse::<char>().ok();
let shorthand = |list: &[(&'static str, char)]| {
value_char.and_then(|c| {
list.iter().copied().find(|&(_, x)| x == c).map(|(s, _)| s)
})
};
let name = complete(variant);
list.push(SymbolModel {
name,
markup_shorthand: shorthand(typst::syntax::ast::Shorthand::LIST),
math_shorthand: shorthand(typst::syntax::ast::MathShorthand::LIST),
// Matches `typst_layout::math::GlyphFragment::new`
math_class: value.chars().next().and_then(|c| {
typst_utils::default_math_class(c).map(math_class_name)
}),
value: value.into(),
// Matches casting `Symbol` to `Accent`
accent: typst::math::Accent::combining(value).is_some(),
alternates: symbol
.variants()
.filter(|(other, _, _)| other != &variant)
.map(|(other, _, _)| complete(other))
.collect(),
deprecation_message: deprecation_message
.or_else(|| binding.deprecation().map(Deprecation::message)),
deprecation_until: binding.deprecation().and_then(Deprecation::until),
});
}
}
SymbolsModel {
name: group.name.clone(),
title: group.title.clone(),
details: Html::markdown(resolver, &group.details, Some(1)),
list,
}
}
/// Extract a module from another module.
#[track_caller]
fn get_module<'a>(parent: &'a Module, name: &str) -> StrResult<&'a Module> {
match parent.scope().get(name).map(Binding::read) {
Some(Value::Module(module)) => Ok(module),
_ => bail!("module doesn't contain module `{name}`"),
}
}
/// Turn a title into an URL fragment.
pub fn urlify(title: &str) -> EcoString {
title
.chars()
.map(|c| c.to_ascii_lowercase())
.map(|c| match c {
'a'..='z' | '0'..='9' | '.' => c,
_ => '-',
})
.collect()
}
/// Extract the first line of documentation.
fn oneliner(docs: &str) -> EcoString {
let paragraph = docs.split("\n\n").next().unwrap_or_default();
let mut depth = 0;
let mut period = false;
let mut end = paragraph.len();
for (i, c) in paragraph.char_indices() {
match c {
'(' | '[' | '{' => depth += 1,
')' | ']' | '}' => depth -= 1,
'.' if depth == 0 => period = true,
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | true |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/docs/src/model.rs | docs/src/model.rs | use ecow::EcoString;
use heck::ToKebabCase;
use serde::Serialize;
use crate::html::Html;
/// Details about a documentation page and its children.
#[derive(Debug, Serialize)]
pub struct PageModel {
pub route: EcoString,
pub title: EcoString,
pub description: EcoString,
pub part: Option<&'static str>,
pub outline: Vec<OutlineItem>,
pub body: BodyModel,
pub children: Vec<Self>,
}
impl PageModel {
pub fn with_route(self, route: &str) -> Self {
Self { route: route.into(), ..self }
}
pub fn with_part(self, part: &'static str) -> Self {
Self { part: Some(part), ..self }
}
}
/// An element in the "On This Page" outline.
#[derive(Debug, Clone, Serialize)]
pub struct OutlineItem {
pub id: EcoString,
pub name: EcoString,
pub children: Vec<Self>,
}
impl OutlineItem {
/// Create an outline item from a name with auto-generated id.
pub fn from_name(name: &str) -> Self {
Self {
id: name.to_kebab_case().into(),
name: name.into(),
children: vec![],
}
}
}
/// Details about the body of a documentation page.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "kind", content = "content")]
#[allow(clippy::large_enum_variant)]
pub enum BodyModel {
Html(Html),
Category(CategoryModel),
Func(FuncModel),
Group(GroupModel),
Type(TypeModel),
Symbols(SymbolsModel),
Packages(Html),
}
/// Details about a category.
#[derive(Debug, Serialize)]
pub struct CategoryModel {
pub name: &'static str,
pub title: EcoString,
pub details: Html,
pub items: Vec<CategoryItem>,
pub shorthands: Option<ShorthandsModel>,
}
/// Details about a category item.
#[derive(Debug, Serialize)]
pub struct CategoryItem {
pub name: EcoString,
pub route: EcoString,
pub oneliner: EcoString,
pub code: bool,
}
/// Details about a function.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FuncModel {
pub path: Vec<EcoString>,
pub name: EcoString,
pub title: &'static str,
pub keywords: &'static [&'static str],
pub oneliner: EcoString,
pub element: bool,
pub contextual: bool,
pub deprecation_message: Option<&'static str>,
pub deprecation_until: Option<&'static str>,
pub details: Vec<DetailsBlock>,
#[serde(rename = "self")]
pub self_: bool,
pub params: Vec<ParamModel>,
pub returns: Vec<&'static str>,
pub scope: Vec<FuncModel>,
}
/// Details about a function parameter.
#[derive(Debug, Serialize)]
pub struct ParamModel {
pub name: &'static str,
pub details: Vec<DetailsBlock>,
pub types: Vec<&'static str>,
pub strings: Vec<StrParam>,
pub default: Option<Html>,
pub positional: bool,
pub named: bool,
pub required: bool,
pub variadic: bool,
pub settable: bool,
}
/// A block-level segment in a function's or parameters documentation.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[serde(tag = "kind", content = "content")]
pub enum DetailsBlock {
/// A block of HTML.
Html(Html),
/// An example with an optional title.
Example { body: Html, title: Option<EcoString> },
}
/// A specific string that can be passed as an argument.
#[derive(Debug, Serialize)]
pub struct StrParam {
pub string: EcoString,
pub details: Html,
}
/// Details about a group of functions.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GroupModel {
pub name: EcoString,
pub title: EcoString,
pub details: Html,
pub functions: Vec<FuncModel>,
pub global_attributes: Vec<ParamModel>,
}
/// Details about a type.
#[derive(Debug, Serialize)]
pub struct TypeModel {
pub name: &'static str,
pub title: &'static str,
pub keywords: &'static [&'static str],
pub oneliner: EcoString,
pub details: Html,
pub constructor: Option<FuncModel>,
pub scope: Vec<FuncModel>,
}
/// A collection of symbols.
#[derive(Debug, Serialize)]
pub struct SymbolsModel {
pub name: EcoString,
pub title: EcoString,
pub details: Html,
pub list: Vec<SymbolModel>,
}
/// Details about a symbol.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SymbolModel {
pub name: EcoString,
pub value: EcoString,
pub accent: bool,
pub alternates: Vec<EcoString>,
pub markup_shorthand: Option<&'static str>,
pub math_shorthand: Option<&'static str>,
pub math_class: Option<&'static str>,
pub deprecation_message: Option<&'static str>,
pub deprecation_until: Option<&'static str>,
}
/// Shorthands listed on a category page.
#[derive(Debug, Serialize)]
pub struct ShorthandsModel {
pub markup: Vec<SymbolModel>,
pub math: Vec<SymbolModel>,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/docs/src/contribs.rs | docs/src/contribs.rs | use std::cmp::Reverse;
use std::fmt::Write;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use crate::{Html, Resolver};
/// Build HTML detailing the contributors between two tags.
pub fn contributors(resolver: &dyn Resolver, from: &str, to: &str) -> Option<Html> {
let staff = ["laurmaedje", "reknih"];
let bots = ["dependabot[bot]"];
// Determine number of contributions per person.
let mut contributors = FxHashMap::<String, Contributor>::default();
for commit in resolver.commits(from, to) {
contributors
.entry(commit.author.login.clone())
.or_insert_with(|| Contributor {
login: commit.author.login,
avatar: commit.author.avatar_url,
contributions: 0,
})
.contributions += 1;
}
// Keep only non-staff people.
let mut contributors: Vec<_> = contributors
.into_values()
.filter(|c| {
let login = c.login.as_str();
!staff.contains(&login) && !bots.contains(&login)
})
.collect();
// Sort by highest number of commits.
contributors.sort_by_key(|c| (Reverse(c.contributions), c.login.clone()));
if contributors.is_empty() {
return None;
}
let mut html = "Thanks to everyone who contributed to this release!".to_string();
html += "<ul class=\"contribs\">";
for Contributor { login, avatar, contributions } in contributors {
let login = login.replace('\"', """).replace('&', "&");
let avatar = avatar.replace("?v=", "?s=64&v=");
let s = if contributions > 1 { "s" } else { "" };
write!(
html,
r#"<li>
<a href="https://github.com/{login}" target="_blank">
<img
width="64"
height="64"
src="{avatar}"
alt="GitHub avatar of {login}"
title="@{login} made {contributions} contribution{s}"
crossorigin="anonymous"
>
</a>
</li>"#
)
.unwrap();
}
html += "</ul>";
Some(Html::new(html))
}
#[derive(Debug)]
struct Contributor {
login: String,
avatar: String,
contributions: usize,
}
/// A commit on the `typst` repository.
#[derive(Debug, Serialize, Deserialize)]
pub struct Commit {
author: Author,
}
/// A commit author.
#[derive(Debug, Serialize, Deserialize)]
pub struct Author {
login: String,
avatar_url: String,
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
typst/typst | https://github.com/typst/typst/blob/a87f4b15ca86a0b2f98948d8f393608070ed731e/docs/src/main.rs | docs/src/main.rs | use std::fs;
use std::path::{Path, PathBuf};
use clap::Parser;
use typst::layout::PagedDocument;
use typst_docs::{Html, Resolver, provide};
use typst_render::render;
#[derive(Debug)]
struct CliResolver<'a> {
assets_dir: &'a Path,
verbose: bool,
base: &'a str,
}
impl Resolver for CliResolver<'_> {
fn commits(&self, from: &str, to: &str) -> Vec<typst_docs::Commit> {
if self.verbose {
eprintln!("commits({from}, {to})");
}
vec![]
}
fn example(
&self,
hash: u128,
source: Option<Html>,
document: &PagedDocument,
) -> typst_docs::Html {
if self.verbose {
eprintln!(
"example(0x{hash:x}, {:?} chars, Document)",
source.as_ref().map(|s| s.as_str().len())
);
}
fs::create_dir_all(self.assets_dir).expect("create dir");
let pages = match &document.pages[..] {
[page] => vec![(page, format!("{hash:x}.png"), "Preview".to_string())],
pages => pages
.iter()
.enumerate()
.map(|(i, page)| {
(page, format!("{hash:x}-{i}.png"), format!("Preview page {}", i + 1))
})
.collect(),
}
.iter()
.map(|(page, filename, alt)| {
let pixmap = render(page, 2.0);
let path = self.assets_dir.join(filename);
pixmap.save_png(path.as_path()).expect("save png");
eprintln!("Generated example image {path:?}");
let src = format!("{}assets/{filename}", self.base);
format!(r#"<img src="{src}" alt="{alt}">"#)
})
.collect::<String>();
if let Some(code) = source {
let code_safe = code.as_str();
Html::new(format!(
r#"<div class="previewed-code"><pre>{code_safe}</pre><div class="preview">{pages}</div></div>"#
))
} else {
Html::new(format!(r#"<div class="preview">{pages}</div>"#))
}
}
fn image(&self, filename: &str, data: &[u8]) -> String {
if self.verbose {
eprintln!("image({filename}, {} bytes)", data.len());
}
let path = self.assets_dir.join(filename);
fs::create_dir_all(path.parent().expect("parent")).expect("create dir");
fs::write(&path, data).expect("write image");
eprintln!("Created {} byte image at {path:?}", data.len());
format!("{}assets/{filename}", self.base)
}
fn link(&self, link: &str) -> Option<String> {
if self.verbose {
eprintln!("link({link})");
}
None
}
fn base(&self) -> &str {
self.base
}
}
/// Generates the JSON representation of the documentation. This can be used to
/// generate the HTML yourself. Be warned: the JSON structure is not stable and
/// may change at any time.
#[derive(Debug, Parser)]
#[command(version, about, long_about = None)]
struct Args {
/// The generation process can produce additional assets. Namely images.
/// This option controls where to spit them out. The HTML generation will
/// assume that this output directory is served at `${base_url}/assets/*`.
/// The default is `assets`. For example, if the base URL is `/docs/` then
/// the generated HTML might look like `<img src="/docs/assets/foo.png">`
/// even though the `--assets-dir` was set to `/tmp/images` or something.
#[arg(long, default_value = "assets")]
assets_dir: PathBuf,
/// Write the JSON output to this file. The default is `-` which is a
/// special value that means "write to standard output". If you want to
/// write to a file named `-` then use `./-`.
#[arg(long, default_value = "-")]
out_file: PathBuf,
/// The base URL for the documentation. This can be an absolute URL like
/// `https://example.com/docs/` or a relative URL like `/docs/`. This is
/// used as the base URL for the generated page's `.route` properties as
/// well as cross-page links. The default is `/`. If a `/` trailing slash is
/// not present then it will be added. This option also affects the HTML
/// asset references. For example: `--base /docs/` will generate
/// `<img src="/docs/assets/foo.png">`.
#[arg(long, default_value = "/")]
base: String,
/// Enable verbose logging. This will print out all the calls to the
/// resolver and the paths of the generated assets.
#[arg(long)]
verbose: bool,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
let mut base = args.base.clone();
if !base.ends_with('/') {
base.push('/');
}
let resolver = CliResolver {
assets_dir: &args.assets_dir,
verbose: args.verbose,
base: &base,
};
if args.verbose {
eprintln!("resolver: {resolver:?}");
}
let pages = provide(&resolver);
eprintln!("Be warned: the JSON structure is not stable and may change at any time.");
let json = serde_json::to_string_pretty(&pages)?;
if args.out_file.to_string_lossy() == "-" {
println!("{json}");
} else {
fs::write(&args.out_file, &*json)?;
}
Ok(())
}
| rust | Apache-2.0 | a87f4b15ca86a0b2f98948d8f393608070ed731e | 2026-01-04T15:31:59.400510Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/config.rs | rust/core-lib/src/config.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use serde::de::{self, Deserialize};
use serde_json::{self, Value};
use crate::syntax::{LanguageId, Languages};
use crate::tabs::{BufferId, ViewId};
/// Loads the included base config settings.
fn load_base_config() -> Table {
fn load(default: &str) -> Table {
table_from_toml_str(default).expect("default configs must load")
}
fn platform_overrides() -> Option<Table> {
if cfg!(test) {
// Exit early if we are in tests and never have platform overrides.
// This makes sure we have a stable test environment.
None
} else if cfg!(windows) {
let toml = include_str!("../assets/windows.toml");
Some(load(toml))
} else {
// All other platorms
None
}
}
let base_toml: &str = include_str!("../assets/defaults.toml");
let mut base = load(base_toml);
if let Some(overrides) = platform_overrides() {
for (k, v) in overrides.iter() {
base.insert(k.to_owned(), v.to_owned());
}
}
base
}
/// A map of config keys to settings
pub type Table = serde_json::Map<String, Value>;
/// A `ConfigDomain` describes a level or category of user settings.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfigDomain {
/// The general user preferences
General,
/// The overrides for a particular syntax.
Language(LanguageId),
/// The user overrides for a particular buffer
UserOverride(BufferId),
/// The system's overrides for a particular buffer. Only used internally.
#[serde(skip_deserializing)]
SysOverride(BufferId),
}
/// The external RPC sends `ViewId`s, which we convert to `BufferId`s
/// internally.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfigDomainExternal {
General,
//TODO: remove this old name
Syntax(LanguageId),
Language(LanguageId),
UserOverride(ViewId),
}
/// The errors that can occur when managing configs.
#[derive(Debug)]
pub enum ConfigError {
/// The config domain was not recognized.
UnknownDomain(String),
/// A file-based config could not be loaded or parsed.
Parse(PathBuf, toml::de::Error),
/// The config table contained unexpected values
UnexpectedItem(serde_json::Error),
/// An Io Error
Io(io::Error),
}
/// Represents the common pattern of default settings masked by
/// user settings.
#[derive(Debug)]
pub struct ConfigPair {
/// A static default configuration, which will never change.
base: Option<Arc<Table>>,
/// A variable, user provided configuration. Items here take
/// precedence over items in `base`.
user: Option<Arc<Table>>,
/// A snapshot of base + user.
cache: Arc<Table>,
}
/// The language associated with a given buffer; this is always detected
/// but can also be manually set by the user.
#[derive(Debug, Clone)]
struct LanguageTag {
detected: LanguageId,
user: Option<LanguageId>,
}
#[derive(Debug)]
pub struct ConfigManager {
/// A map of `ConfigPairs` (defaults + overrides) for all in-use domains.
configs: HashMap<ConfigDomain, ConfigPair>,
/// The currently loaded `Languages`.
languages: Languages,
/// The language assigned to each buffer.
buffer_tags: HashMap<BufferId, LanguageTag>,
/// The configs for any open buffers
buffer_configs: HashMap<BufferId, BufferConfig>,
/// If using file-based config, this is the base config directory
/// (perhaps `$HOME/.config/xi`, by default).
config_dir: Option<PathBuf>,
/// An optional client-provided path for bundled resources, such
/// as plugins and themes.
extras_dir: Option<PathBuf>,
}
/// A collection of config tables representing a hierarchy, with each
/// table's keys superseding keys in preceding tables.
#[derive(Debug, Clone, Default)]
struct TableStack(Vec<Arc<Table>>);
/// A frozen collection of settings, and their sources.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config<T> {
/// The underlying set of config tables that contributed to this
/// `Config` instance. Used for diffing.
#[serde(skip)]
source: TableStack,
/// The settings themselves, deserialized into some concrete type.
pub items: T,
}
fn deserialize_tab_size<'de, D>(deserializer: D) -> Result<usize, D::Error>
where
D: serde::Deserializer<'de>,
{
let tab_size = usize::deserialize(deserializer)?;
if tab_size == 0 {
Err(de::Error::invalid_value(
de::Unexpected::Unsigned(tab_size as u64),
&"tab_size must be at least 1",
))
} else {
Ok(tab_size)
}
}
/// The concrete type for buffer-related settings.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
pub struct BufferItems {
pub line_ending: String,
#[serde(deserialize_with = "deserialize_tab_size")]
pub tab_size: usize,
pub translate_tabs_to_spaces: bool,
pub use_tab_stops: bool,
pub font_face: String,
pub font_size: f32,
pub auto_indent: bool,
pub scroll_past_end: bool,
pub wrap_width: usize,
pub word_wrap: bool,
pub autodetect_whitespace: bool,
pub surrounding_pairs: Vec<(String, String)>,
pub save_with_newline: bool,
}
pub type BufferConfig = Config<BufferItems>;
impl ConfigPair {
/// Creates a new `ConfigPair` with the provided base config.
fn with_base<T: Into<Option<Table>>>(table: T) -> Self {
let base = table.into().map(Arc::new);
let cache = base.clone().unwrap_or_default();
ConfigPair { base, cache, user: None }
}
/// Returns a new `ConfigPair` with the provided base and the current
/// user config.
fn new_with_base<T: Into<Option<Table>>>(&self, table: T) -> Self {
let mut new_self = ConfigPair::with_base(table);
new_self.user = self.user.clone();
new_self.rebuild();
new_self
}
fn set_table(&mut self, user: Table) {
self.user = Some(Arc::new(user));
self.rebuild();
}
/// Returns the `Table` produced by updating `self.user` with the contents
/// of `user`, deleting null entries.
fn table_for_update(&self, user: Table) -> Table {
let mut new_user: Table =
self.user.as_ref().map(|arc| arc.as_ref().clone()).unwrap_or_default();
for (k, v) in user {
if v.is_null() {
new_user.remove(&k);
} else {
new_user.insert(k, v);
}
}
new_user
}
fn rebuild(&mut self) {
let mut cache = self.base.clone().unwrap_or_default();
if let Some(ref user) = self.user {
for (k, v) in user.iter() {
Arc::make_mut(&mut cache).insert(k.to_owned(), v.clone());
}
}
self.cache = cache;
}
}
impl ConfigManager {
pub fn new(config_dir: Option<PathBuf>, extras_dir: Option<PathBuf>) -> Self {
let base = load_base_config();
let mut defaults = HashMap::new();
defaults.insert(ConfigDomain::General, ConfigPair::with_base(base));
ConfigManager {
configs: defaults,
buffer_tags: HashMap::new(),
buffer_configs: HashMap::new(),
languages: Languages::default(),
config_dir,
extras_dir,
}
}
/// The path of the user's config file, if present.
pub(crate) fn base_config_file_path(&self) -> Option<PathBuf> {
let config_file = self.config_dir.as_ref().map(|p| p.join("preferences.xiconfig"));
let exists = config_file.as_ref().map(|p| p.exists()).unwrap_or(false);
if exists {
config_file
} else {
None
}
}
pub(crate) fn get_plugin_paths(&self) -> Vec<PathBuf> {
let config_dir = self.config_dir.as_ref().map(|p| p.join("plugins"));
[self.extras_dir.as_ref(), config_dir.as_ref()]
.iter()
.flat_map(|p| p.map(|p| p.to_owned()))
.filter(|p| p.exists())
.collect()
}
/// Adds a new buffer to the config manager, and returns the initial config
/// `Table` for that buffer. The `path` argument is used to determine
/// the buffer's default language.
///
/// # Note: The caller is responsible for ensuring the config manager is
/// notified every time a buffer is added or removed.
///
/// # Panics:
///
/// Panics if `id` already exists.
pub(crate) fn add_buffer(&mut self, id: BufferId, path: Option<&Path>) -> Table {
let lang =
path.and_then(|p| self.language_for_path(p)).unwrap_or(LanguageId::from("Plain Text"));
let lang_tag = LanguageTag::new(lang);
assert!(self.buffer_tags.insert(id, lang_tag).is_none());
self.update_buffer_config(id).expect("new buffer must always have config")
}
/// Updates the default language for the given buffer.
///
/// # Panics:
///
/// Panics if `id` does not exist.
pub(crate) fn update_buffer_path(&mut self, id: BufferId, path: &Path) -> Option<Table> {
assert!(self.buffer_tags.contains_key(&id));
let lang = self.language_for_path(path).unwrap_or_default();
let has_changed = self.buffer_tags.get_mut(&id).map(|tag| tag.set_detected(lang)).unwrap();
if has_changed {
self.update_buffer_config(id)
} else {
None
}
}
/// Instructs the `ConfigManager` to stop tracking a given buffer.
///
/// # Panics:
///
/// Panics if `id` does not exist.
pub(crate) fn remove_buffer(&mut self, id: BufferId) {
self.buffer_tags.remove(&id).expect("remove key must exist");
self.buffer_configs.remove(&id);
// TODO: remove any overrides
}
/// Sets a specific language for the given buffer. This is used if the
/// user selects a specific language in the frontend, for instance.
pub(crate) fn override_language(
&mut self,
id: BufferId,
new_lang: LanguageId,
) -> Option<Table> {
let has_changed = self
.buffer_tags
.get_mut(&id)
.map(|tag| tag.set_user(Some(new_lang)))
.expect("buffer must exist");
if has_changed {
self.update_buffer_config(id)
} else {
None
}
}
fn update_buffer_config(&mut self, id: BufferId) -> Option<Table> {
let new_config = self.generate_buffer_config(id);
let changes = new_config.changes_from(self.buffer_configs.get(&id));
self.buffer_configs.insert(id, new_config);
changes
}
fn update_all_buffer_configs(&mut self) -> Vec<(BufferId, Table)> {
self.buffer_configs
.keys()
.cloned()
.collect::<Vec<_>>()
.into_iter()
.flat_map(|k| self.update_buffer_config(k).map(|c| (k, c)))
.collect::<Vec<_>>()
}
fn generate_buffer_config(&mut self, id: BufferId) -> BufferConfig {
// it's possible for a buffer to be tagged with since-removed language
let lang = self
.buffer_tags
.get(&id)
.map(LanguageTag::resolve)
.and_then(|name| self.languages.language_for_name(name))
.map(|l| l.name.clone());
let mut configs = vec![self.configs.get(&ConfigDomain::General)];
if let Some(s) = lang {
configs.push(self.configs.get(&s.into()))
};
configs.push(self.configs.get(&ConfigDomain::SysOverride(id)));
configs.push(self.configs.get(&ConfigDomain::UserOverride(id)));
let configs = configs
.iter()
.flat_map(Option::iter)
.map(|c| c.cache.clone())
.rev()
.collect::<Vec<_>>();
let stack = TableStack(configs);
stack.into_config()
}
/// Returns a reference to the `BufferConfig` for this buffer.
///
/// # Panics:
///
/// Panics if `id` does not exist. The caller is responsible for ensuring
/// that the `ConfigManager` is kept up to date as buffers are added/removed.
pub(crate) fn get_buffer_config(&self, id: BufferId) -> &BufferConfig {
self.buffer_configs.get(&id).unwrap()
}
/// Returns the language associated with this buffer.
///
/// # Panics:
///
/// Panics if `id` does not exist.
pub(crate) fn get_buffer_language(&self, id: BufferId) -> LanguageId {
self.buffer_tags.get(&id).map(LanguageTag::resolve).unwrap()
}
/// Set the available `LanguageDefinition`s. Overrides any previous values.
pub fn set_languages(&mut self, languages: Languages) {
// remove base configs for any removed languages
self.languages.difference(&languages).iter().for_each(|lang| {
let domain: ConfigDomain = lang.name.clone().into();
if let Some(pair) = self.configs.get_mut(&domain) {
*pair = pair.new_with_base(None);
}
});
for language in languages.iter() {
let lang_id = language.name.clone();
let domain: ConfigDomain = lang_id.into();
let default_config = language.default_config.clone();
self.configs
.entry(domain.clone())
.and_modify(|c| *c = c.new_with_base(default_config.clone()))
.or_insert_with(|| ConfigPair::with_base(default_config));
if let Some(table) = self.load_user_config_file(&domain) {
// we can't report this error because we don't have a
// handle to the peer :|
let _ = self.set_user_config(domain, table);
}
}
//FIXME these changes are happening silently, which won't work once
//languages can by dynamically changed
self.languages = languages;
self.update_all_buffer_configs();
}
fn load_user_config_file(&self, domain: &ConfigDomain) -> Option<Table> {
let path = self
.config_dir
.as_ref()
.map(|p| p.join(domain.file_stem()).with_extension("xiconfig"))?;
if !path.exists() {
return None;
}
match try_load_from_file(&path) {
Ok(t) => Some(t),
Err(e) => {
error!("Error loading config: {:?}", e);
None
}
}
}
pub fn language_for_path(&self, path: &Path) -> Option<LanguageId> {
self.languages.language_for_path(path).map(|lang| lang.name.clone())
}
/// Sets the config for the given domain, removing any existing config.
/// Returns a `Vec` of individual buffer config changes that result from
/// this update, or a `ConfigError` if `config` is poorly formed.
pub fn set_user_config(
&mut self,
domain: ConfigDomain,
config: Table,
) -> Result<Vec<(BufferId, Table)>, ConfigError> {
self.check_table(&config)?;
self.configs.entry(domain).or_insert_with(|| ConfigPair::with_base(None)).set_table(config);
Ok(self.update_all_buffer_configs())
}
/// Returns the `Table` produced by applying `changes` to the current user
/// config for the given `ConfigDomain`.
///
/// # Note:
///
/// When the user modifys a config _file_, the whole file is read,
/// and we can just overwrite any existing user config with the newly
/// loaded one.
///
/// When the client modifies a config via the RPC mechanism, however,
/// this isn't the case. Instead of sending all config settings with
/// each update, the client just sends the keys/values they would like
/// to change. When they would like to remove a previously set key,
/// they send `Null` as the value for that key.
///
/// This function creates a new table which is the product of updating
/// any existing table by applying the client's changes. This new table can
/// then be passed to `Self::set_user_config(..)`, as if it were loaded
/// from disk.
pub(crate) fn table_for_update(&mut self, domain: ConfigDomain, changes: Table) -> Table {
self.configs
.entry(domain)
.or_insert_with(|| ConfigPair::with_base(None))
.table_for_update(changes)
}
/// Returns the `ConfigDomain` relevant to a given file, if one exists.
pub fn domain_for_path(&self, path: &Path) -> Option<ConfigDomain> {
if path.extension().map(|e| e != "xiconfig").unwrap_or(true) {
return None;
}
match path.file_stem().and_then(|s| s.to_str()) {
Some("preferences") => Some(ConfigDomain::General),
Some(name) if self.languages.language_for_name(&name).is_some() => {
let lang =
self.languages.language_for_name(&name).map(|lang| lang.name.clone()).unwrap();
Some(ConfigDomain::Language(lang))
}
//TODO: plugin configs
_ => None,
}
}
fn check_table(&self, table: &Table) -> Result<(), ConfigError> {
let defaults = self
.configs
.get(&ConfigDomain::General)
.and_then(|pair| pair.base.clone())
.expect("general domain must have defaults");
let mut defaults: Table = defaults.as_ref().clone();
for (k, v) in table.iter() {
// changes can include 'null', which means clear field
if v.is_null() {
continue;
}
defaults.insert(k.to_owned(), v.to_owned());
}
let _: BufferItems = serde_json::from_value(defaults.into())?;
Ok(())
}
/// Path to themes sub directory inside config directory.
/// Creates one if not present.
pub(crate) fn get_themes_dir(&self) -> Option<PathBuf> {
let themes_dir = self.config_dir.as_ref().map(|p| p.join("themes"));
if let Some(p) = themes_dir {
if p.exists() {
return Some(p);
}
if fs::DirBuilder::new().create(&p).is_ok() {
return Some(p);
}
}
None
}
/// Path to plugins sub directory inside config directory.
/// Creates one if not present.
pub(crate) fn get_plugins_dir(&self) -> Option<PathBuf> {
let plugins_dir = self.config_dir.as_ref().map(|p| p.join("plugins"));
if let Some(p) = plugins_dir {
if p.exists() {
return Some(p);
}
if fs::DirBuilder::new().create(&p).is_ok() {
return Some(p);
}
}
None
}
}
impl TableStack {
/// Create a single table representing the final config values.
fn collate(&self) -> Table {
// NOTE: This is fairly expensive; a future optimization would borrow
// from the underlying collections.
let mut out = Table::new();
for table in &self.0 {
for (k, v) in table.iter() {
if !out.contains_key(k) {
// cloning these objects feels a bit gross, we could
// improve this by implementing Deserialize for TableStack.
out.insert(k.to_owned(), v.to_owned());
}
}
}
out
}
/// Converts the underlying tables into a static `Config` instance.
fn into_config<T>(self) -> Config<T>
where
for<'de> T: Deserialize<'de>,
{
let out = self.collate();
let items: T = serde_json::from_value(out.into()).unwrap();
let source = self;
Config { source, items }
}
/// Walks the tables in priority order, returning the first
/// occurance of `key`.
fn get<S: AsRef<str>>(&self, key: S) -> Option<&Value> {
for table in &self.0 {
if let Some(v) = table.get(key.as_ref()) {
return Some(v);
}
}
None
}
/// Returns a new `Table` containing only those keys and values in `self`
/// which have changed from `other`.
fn diff(&self, other: &TableStack) -> Option<Table> {
let mut out: Option<Table> = None;
let this = self.collate();
for (k, v) in this.iter() {
if other.get(k) != Some(v) {
let out: &mut Table = out.get_or_insert(Table::new());
out.insert(k.to_owned(), v.to_owned());
}
}
out
}
}
impl<T> Config<T> {
pub fn to_table(&self) -> Table {
self.source.collate()
}
}
impl<'de, T: Deserialize<'de>> Config<T> {
/// Returns a `Table` of all the items in `self` which have different
/// values than in `other`.
pub fn changes_from(&self, other: Option<&Config<T>>) -> Option<Table> {
match other {
Some(other) => self.source.diff(&other.source),
None => self.source.collate().into(),
}
}
}
impl ConfigDomain {
fn file_stem(&self) -> &str {
match self {
ConfigDomain::General => "preferences",
ConfigDomain::Language(lang) => lang.as_ref(),
ConfigDomain::UserOverride(_) | ConfigDomain::SysOverride(_) => "we don't have files",
}
}
}
impl LanguageTag {
fn new(detected: LanguageId) -> Self {
LanguageTag { detected, user: None }
}
fn resolve(&self) -> LanguageId {
self.user.as_ref().unwrap_or(&self.detected).clone()
}
/// Set the detected language. Returns `true` if this changes the resolved
/// language.
fn set_detected(&mut self, detected: LanguageId) -> bool {
let before = self.resolve();
self.detected = detected;
before != self.resolve()
}
/// Set the user-specified language. Returns `true` if this changes
/// the resolved language.
#[allow(dead_code)]
fn set_user(&mut self, new_lang: Option<LanguageId>) -> bool {
let has_changed = self.user != new_lang;
self.user = new_lang;
has_changed
}
}
impl<T: PartialEq> PartialEq for Config<T> {
fn eq(&self, other: &Config<T>) -> bool {
self.items == other.items
}
}
impl From<LanguageId> for ConfigDomain {
fn from(src: LanguageId) -> ConfigDomain {
ConfigDomain::Language(src)
}
}
impl From<BufferId> for ConfigDomain {
fn from(src: BufferId) -> ConfigDomain {
ConfigDomain::UserOverride(src)
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::ConfigError::*;
match *self {
UnknownDomain(ref s) => write!(f, "UnknownDomain: {}", s),
Parse(ref p, ref e) => write!(f, "Parse ({:?}), {}", p, e),
Io(ref e) => write!(f, "error loading config: {}", e),
UnexpectedItem(ref e) => write!(f, "{}", e),
}
}
}
impl Error for ConfigError {}
impl From<io::Error> for ConfigError {
fn from(src: io::Error) -> ConfigError {
ConfigError::Io(src)
}
}
impl From<serde_json::Error> for ConfigError {
fn from(src: serde_json::Error) -> ConfigError {
ConfigError::UnexpectedItem(src)
}
}
/// Creates initial config directory structure
pub(crate) fn init_config_dir(dir: &Path) -> io::Result<()> {
let builder = fs::DirBuilder::new();
builder.create(dir)?;
builder.create(dir.join("plugins"))?;
Ok(())
}
/// Attempts to load a config from a file. The config's domain is determined
/// by the file name.
pub(crate) fn try_load_from_file(path: &Path) -> Result<Table, ConfigError> {
let mut file = fs::File::open(&path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
table_from_toml_str(&contents).map_err(|e| ConfigError::Parse(path.to_owned(), e))
}
pub(crate) fn table_from_toml_str(s: &str) -> Result<Table, toml::de::Error> {
let table = toml::from_str(s)?;
let table = from_toml_value(table).as_object().unwrap().to_owned();
Ok(table)
}
//adapted from https://docs.rs/crate/config/0.7.0/source/src/file/format/toml.rs
/// Converts between toml (used to write config files) and json
/// (used to store config values internally).
fn from_toml_value(value: toml::Value) -> Value {
match value {
toml::Value::String(value) => value.into(),
toml::Value::Float(value) => value.into(),
toml::Value::Integer(value) => value.into(),
toml::Value::Boolean(value) => value.into(),
toml::Value::Datetime(value) => value.to_string().into(),
toml::Value::Table(table) => {
let mut m = Table::new();
for (key, value) in table {
m.insert(key.clone(), from_toml_value(value));
}
m.into()
}
toml::Value::Array(array) => {
let mut l = Vec::new();
for value in array {
l.push(from_toml_value(value));
}
l.into()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::syntax::LanguageDefinition;
#[test]
fn test_overrides() {
let user_config = table_from_toml_str(r#"tab_size = 42"#).unwrap();
let rust_config = table_from_toml_str(r#"tab_size = 31"#).unwrap();
let lang_def = rust_lang_def(None);
let rust_id: LanguageId = "Rust".into();
let buf_id_1 = BufferId(1); // no language
let buf_id_2 = BufferId(2); // just rust
let buf_id_3 = BufferId(3); // rust, + system overrides
let mut manager = ConfigManager::new(None, None);
manager.set_languages(Languages::new(&[lang_def]));
manager.set_user_config(rust_id.into(), rust_config).unwrap();
manager.set_user_config(ConfigDomain::General, user_config).unwrap();
let changes = json!({"tab_size": 67}).as_object().unwrap().to_owned();
manager.set_user_config(ConfigDomain::SysOverride(buf_id_3), changes).unwrap();
manager.add_buffer(buf_id_1, None);
manager.add_buffer(buf_id_2, Some(Path::new("file.rs")));
manager.add_buffer(buf_id_3, Some(Path::new("file2.rs")));
// system override
let config = manager.get_buffer_config(buf_id_1).to_owned();
assert_eq!(config.source.0.len(), 1);
assert_eq!(config.items.tab_size, 42);
let config = manager.get_buffer_config(buf_id_2).to_owned();
assert_eq!(config.items.tab_size, 31);
let config = manager.get_buffer_config(buf_id_3).to_owned();
assert_eq!(config.items.tab_size, 67);
// user override trumps everything
let changes = json!({"tab_size": 85}).as_object().unwrap().to_owned();
manager.set_user_config(ConfigDomain::UserOverride(buf_id_3), changes).unwrap();
let config = manager.get_buffer_config(buf_id_3);
assert_eq!(config.items.tab_size, 85);
}
#[test]
fn test_config_domain_serde() {
assert_eq!(serde_json::to_string(&ConfigDomain::General).unwrap(), "\"general\"");
let d = ConfigDomainExternal::UserOverride(ViewId(1));
assert_eq!(serde_json::to_string(&d).unwrap(), "{\"user_override\":\"view-id-1\"}");
let d = ConfigDomain::Language("Swift".into());
assert_eq!(serde_json::to_string(&d).unwrap(), "{\"language\":\"Swift\"}");
}
#[test]
fn test_diff() {
let conf1 = r#"
tab_size = 42
translate_tabs_to_spaces = true
"#;
let conf1 = table_from_toml_str(conf1).unwrap();
let conf2 = r#"
tab_size = 6
translate_tabs_to_spaces = true
"#;
let conf2 = table_from_toml_str(conf2).unwrap();
let stack1 = TableStack(vec![Arc::new(conf1)]);
let stack2 = TableStack(vec![Arc::new(conf2)]);
let diff = stack1.diff(&stack2).unwrap();
assert!(diff.len() == 1);
assert_eq!(diff.get("tab_size"), Some(&42.into()));
}
#[test]
fn test_updating_in_place() {
let mut manager = ConfigManager::new(None, None);
let buf_id = BufferId(1);
manager.add_buffer(buf_id, None);
assert_eq!(manager.get_buffer_config(buf_id).items.font_size, 14.);
let changes = json!({"font_size": 69, "font_face": "nice"}).as_object().unwrap().to_owned();
let table = manager.table_for_update(ConfigDomain::General, changes);
manager.set_user_config(ConfigDomain::General, table).unwrap();
assert_eq!(manager.get_buffer_config(buf_id).items.font_size, 69.);
// null values in updates removes keys
let changes = json!({ "font_size": Value::Null }).as_object().unwrap().to_owned();
let table = manager.table_for_update(ConfigDomain::General, changes);
manager.set_user_config(ConfigDomain::General, table).unwrap();
assert_eq!(manager.get_buffer_config(buf_id).items.font_size, 14.);
assert_eq!(manager.get_buffer_config(buf_id).items.font_face, "nice");
}
#[test]
fn lang_overrides() {
let mut manager = ConfigManager::new(None, None);
let lang_defaults = json!({"font_size": 69, "font_face": "nice"});
let lang_overrides = json!({"font_size": 420, "font_face": "cool"});
let lang_def = rust_lang_def(lang_defaults.as_object().map(Table::clone));
let lang_id: LanguageId = "Rust".into();
let domain: ConfigDomain = lang_id.into();
manager.set_languages(Languages::new(&[lang_def.clone()]));
assert_eq!(manager.languages.iter().count(), 1);
let buf_id = BufferId(1);
manager.add_buffer(buf_id, Some(Path::new("file.rs")));
let config = manager.get_buffer_config(buf_id).to_owned();
assert_eq!(config.source.0.len(), 2);
assert_eq!(config.items.font_size, 69.);
// removing language should remove default configs
manager.set_languages(Languages::new(&[]));
assert_eq!(manager.languages.iter().count(), 0);
let config = manager.get_buffer_config(buf_id).to_owned();
assert_eq!(config.source.0.len(), 1);
assert_eq!(config.items.font_size, 14.);
manager
.set_user_config(domain.clone(), lang_overrides.as_object().map(Table::clone).unwrap())
.unwrap();
// user config for unknown language is ignored
let config = manager.get_buffer_config(buf_id).to_owned();
assert_eq!(config.items.font_size, 14.);
// user config trumps defaults when language exists
manager.set_languages(Languages::new(&[lang_def]));
let config = manager.get_buffer_config(buf_id).to_owned();
assert_eq!(config.items.font_size, 420.);
let changes = json!({ "font_size": Value::Null }).as_object().unwrap().to_owned();
// null key should void user setting, leave language default
let table = manager.table_for_update(domain.clone(), changes);
manager.set_user_config(domain, table).unwrap();
let config = manager.get_buffer_config(buf_id).to_owned();
assert_eq!(config.items.font_size, 69.);
manager.set_languages(Languages::new(&[]));
let config = manager.get_buffer_config(buf_id);
assert_eq!(config.items.font_size, 14.);
}
fn rust_lang_def<T: Into<Option<Table>>>(defaults: T) -> LanguageDefinition {
LanguageDefinition::simple("Rust", &["rs"], "source.rust", defaults.into())
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/linewrap.rs | rust/core-lib/src/linewrap.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Compute line wrapping breaks for text.
use std::cmp::Ordering;
use std::ops::Range;
use xi_rope::breaks::{BreakBuilder, Breaks, BreaksInfo, BreaksMetric};
use xi_rope::spans::Spans;
use xi_rope::{Cursor, Interval, LinesMetric, Rope, RopeDelta, RopeInfo};
use xi_trace::trace_block;
use xi_unicode::LineBreakLeafIter;
use crate::client::Client;
use crate::styles::{Style, N_RESERVED_STYLES};
use crate::width_cache::{CodepointMono, Token, WidthCache, WidthMeasure};
/// The visual width of the buffer for the purpose of word wrapping.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum WrapWidth {
/// No wrapping in effect.
None,
/// Width in bytes (utf-8 code units).
///
/// Only works well for ASCII, will probably not be maintained long-term.
Bytes(usize),
/// Width in px units, requiring measurement by the front-end.
Width(f64),
}
impl Default for WrapWidth {
fn default() -> Self {
WrapWidth::None
}
}
impl WrapWidth {
fn differs_in_kind(self, other: WrapWidth) -> bool {
use self::WrapWidth::*;
match (self, other) {
(None, None) | (Bytes(_), Bytes(_)) | (Width(_), Width(_)) => false,
_else => true,
}
}
}
/// A range to be rewrapped.
type Task = Interval;
/// Tracks state related to visual lines.
#[derive(Default)]
pub(crate) struct Lines {
breaks: Breaks,
wrap: WrapWidth,
/// Aka the 'frontier'; ranges of lines that still need to be wrapped.
work: Vec<Task>,
}
pub(crate) struct VisualLine {
pub(crate) interval: Interval,
/// The logical line number for this line. Only present when this is the
/// first visual line in a logical line.
pub(crate) line_num: Option<usize>,
}
impl VisualLine {
fn new<I: Into<Interval>, L: Into<Option<usize>>>(iv: I, line: L) -> Self {
VisualLine { interval: iv.into(), line_num: line.into() }
}
}
/// Describes what has changed after a batch of word wrapping; this is used
/// for minimal invalidation.
pub(crate) struct InvalLines {
pub(crate) start_line: usize,
pub(crate) inval_count: usize,
pub(crate) new_count: usize,
}
/// Detailed information about changes to linebreaks, used to generate
/// invalidation information. The logic behind invalidation is different
/// depending on whether we're updating breaks after an edit, or continuing
/// a bulk rewrapping task. This is shared between the two cases, and contains
/// the information relevant to both of them.
struct WrapSummary {
start_line: usize,
/// Total number of invalidated lines; this is meaningless in the after_edit case.
inval_count: usize,
/// The total number of new (hard + soft) breaks in the wrapped region.
new_count: usize,
/// The number of new soft breaks.
new_soft: usize,
}
impl Lines {
pub(crate) fn set_wrap_width(&mut self, text: &Rope, wrap: WrapWidth) {
self.work.clear();
self.add_task(0..text.len());
if self.breaks.is_empty() || self.wrap.differs_in_kind(wrap) {
// we keep breaks while resizing, for more efficient invalidation
self.breaks = Breaks::new_no_break(text.len());
}
self.wrap = wrap;
}
fn add_task<T: Into<Interval>>(&mut self, iv: T) {
let iv = iv.into();
if iv.is_empty() {
return;
}
// keep everything that doesn't intersect. merge things that do.
let split_idx = match self.work.iter().position(|&t| !t.intersect(iv).is_empty()) {
Some(idx) => idx,
None => {
self.work.push(iv);
return;
}
};
let to_update = self.work.split_off(split_idx);
let mut new_task = Some(iv);
for t in &to_update {
match new_task.take() {
Some(new) if !t.intersect(new).is_empty() => new_task = Some(t.union(new)),
Some(new) => {
self.work.push(new);
self.work.push(*t);
}
None => self.work.push(*t),
}
}
if let Some(end) = new_task.take() {
self.work.push(end);
}
}
pub(crate) fn is_converged(&self) -> bool {
self.wrap == WrapWidth::None || self.work.is_empty()
}
/// Returns `true` if this interval is part of an incomplete task.
pub(crate) fn interval_needs_wrap(&self, iv: Interval) -> bool {
self.work.iter().any(|t| !t.intersect(iv).is_empty())
}
pub(crate) fn visual_line_of_offset(&self, text: &Rope, offset: usize) -> usize {
let mut line = text.line_of_offset(offset);
if self.wrap != WrapWidth::None {
line += self.breaks.count::<BreaksMetric>(offset)
}
line
}
/// Returns the byte offset corresponding to the line `line`.
pub(crate) fn offset_of_visual_line(&self, text: &Rope, line: usize) -> usize {
match self.wrap {
WrapWidth::None => {
// sanitize input
let line = line.min(text.measure::<LinesMetric>() + 1);
text.offset_of_line(line)
}
_ => {
let mut cursor = MergedBreaks::new(text, &self.breaks);
cursor.offset_of_line(line)
}
}
}
/// Returns an iterator over [`VisualLine`]s, starting at (and including)
/// `start_line`.
pub(crate) fn iter_lines<'a>(
&'a self,
text: &'a Rope,
start_line: usize,
) -> impl Iterator<Item = VisualLine> + 'a {
let mut cursor = MergedBreaks::new(text, &self.breaks);
let offset = cursor.offset_of_line(start_line);
let logical_line = text.line_of_offset(offset) + 1;
cursor.set_offset(offset);
VisualLines { offset, cursor, len: text.len(), logical_line, eof: false }
}
/// Returns the next task, prioritizing the currently visible region.
/// Does not modify the task list; this is done after the task runs.
fn get_next_task(&self, visible_offset: usize) -> Option<Task> {
// the first task t where t.end > visible_offset is the only task
// that might contain the visible region.
self.work
.iter()
.find(|t| t.end > visible_offset)
.map(|t| Task::new(t.start.max(visible_offset), t.end))
.or(self.work.last().cloned())
}
fn update_tasks_after_wrap<T: Into<Interval>>(&mut self, wrapped_iv: T) {
if self.work.is_empty() {
return;
}
let wrapped_iv = wrapped_iv.into();
let mut work = Vec::new();
for task in &self.work {
if task.is_before(wrapped_iv.start) || task.is_after(wrapped_iv.end) {
work.push(*task);
continue;
}
if wrapped_iv.start > task.start {
work.push(task.prefix(wrapped_iv));
}
if wrapped_iv.end < task.end {
work.push(task.suffix(wrapped_iv));
}
}
self.work = work;
}
/// Adjust offsets for any tasks after an edit.
fn patchup_tasks<T: Into<Interval>>(&mut self, iv: T, new_len: usize) {
let iv = iv.into();
let mut new_work = Vec::new();
for task in &self.work {
if task.is_before(iv.start) {
new_work.push(*task);
} else if task.contains(iv.start) {
let head = task.prefix(iv);
let tail_end = iv.start.max((task.end + new_len).saturating_sub(iv.size()));
let tail = Interval::new(iv.start, tail_end);
new_work.push(head);
new_work.push(tail);
} else {
// take task - our edit interval, then translate it (- old_size, + new_size)
let tail = task.suffix(iv).translate(new_len).translate_neg(iv.size());
new_work.push(tail);
}
}
new_work.retain(|iv| !iv.is_empty());
self.work.clear();
for task in new_work {
if let Some(prev) = self.work.last_mut() {
if prev.end >= task.start {
*prev = prev.union(task);
continue;
}
}
self.work.push(task);
}
}
/// Do a chunk of wrap work, if any exists.
pub(crate) fn rewrap_chunk(
&mut self,
text: &Rope,
width_cache: &mut WidthCache,
client: &Client,
_spans: &Spans<Style>,
visible_lines: Range<usize>,
) -> Option<InvalLines> {
if self.is_converged() {
None
} else {
let summary = self.do_wrap_task(text, width_cache, client, visible_lines, None);
let WrapSummary { start_line, inval_count, new_count, .. } = summary;
Some(InvalLines { start_line, inval_count, new_count })
}
}
/// Updates breaks after an edit. Returns `InvalLines`, for minimal invalidation,
/// when possible.
pub(crate) fn after_edit(
&mut self,
text: &Rope,
old_text: &Rope,
delta: &RopeDelta,
width_cache: &mut WidthCache,
client: &Client,
visible_lines: Range<usize>,
) -> Option<InvalLines> {
let (iv, newlen) = delta.summary();
let logical_start_line = text.line_of_offset(iv.start);
let old_logical_end_line = old_text.line_of_offset(iv.end) + 1;
let new_logical_end_line = text.line_of_offset(iv.start + newlen) + 1;
let old_logical_end_offset = old_text.offset_of_line(old_logical_end_line);
let old_hard_count = old_logical_end_line - logical_start_line;
let new_hard_count = new_logical_end_line - logical_start_line;
//TODO: we should be able to avoid wrapping the whole para in most cases,
// but the logic is trickier.
let prev_break = text.offset_of_line(logical_start_line);
let next_hard_break = text.offset_of_line(new_logical_end_line);
// count the soft breaks in the region we will rewrap, before we update them.
let inval_soft = self.breaks.count::<BreaksMetric>(old_logical_end_offset)
- self.breaks.count::<BreaksMetric>(prev_break);
// update soft breaks, adding empty spans in the edited region
let mut builder = BreakBuilder::new();
builder.add_no_break(newlen);
self.breaks.edit(iv, builder.build());
self.patchup_tasks(iv, newlen);
if self.wrap == WrapWidth::None {
return Some(InvalLines {
start_line: logical_start_line,
inval_count: old_hard_count,
new_count: new_hard_count,
});
}
let new_task = prev_break..next_hard_break;
self.add_task(new_task);
// possible if the whole buffer is deleted, e.g
if !self.work.is_empty() {
let summary = self.do_wrap_task(text, width_cache, client, visible_lines, None);
let WrapSummary { start_line, new_soft, .. } = summary;
// if we haven't converged after this update we can't do minimal invalidation
// because we don't have complete knowledge of the new breaks state.
if self.is_converged() {
let inval_count = old_hard_count + inval_soft;
let new_count = new_hard_count + new_soft;
Some(InvalLines { start_line, inval_count, new_count })
} else {
None
}
} else {
None
}
}
fn do_wrap_task(
&mut self,
text: &Rope,
width_cache: &mut WidthCache,
client: &Client,
visible_lines: Range<usize>,
max_lines: Option<usize>,
) -> WrapSummary {
use self::WrapWidth::*;
let _t = trace_block("Lines::do_wrap_task", &["core"]);
// 'line' is a poor unit here; could do some fancy Duration thing?
const MAX_LINES_PER_BATCH: usize = 500;
let mut cursor = MergedBreaks::new(text, &self.breaks);
let visible_off = cursor.offset_of_line(visible_lines.start);
let logical_off = text.offset_of_line(text.line_of_offset(visible_off));
// task.start is a hard break; task.end is a boundary or EOF.
let task = self.get_next_task(logical_off).unwrap();
cursor.set_offset(task.start);
debug_assert_eq!(cursor.offset, task.start, "task_start must be valid offset");
let mut ctx = match self.wrap {
Bytes(b) => RewrapCtx::new(text, &CodepointMono, b as f64, width_cache, task.start),
Width(w) => RewrapCtx::new(text, client, w, width_cache, task.start),
None => unreachable!(),
};
let start_line = cursor.cur_line;
let max_lines = max_lines.unwrap_or(MAX_LINES_PER_BATCH);
// always wrap at least a screen worth of lines (unless we converge earlier)
let batch_size = max_lines.max(visible_lines.end - visible_lines.start);
let mut builder = BreakBuilder::new();
let mut lines_wrapped = 0;
let mut pos = task.start;
let mut old_next_maybe = cursor.next();
loop {
if let Some(new_next) = ctx.wrap_one_line(pos) {
while let Some(old_next) = old_next_maybe {
if old_next >= new_next {
break; // just advance old cursor and continue
}
old_next_maybe = cursor.next();
}
let is_hard = cursor.offset == new_next && cursor.is_hard_break();
if is_hard {
builder.add_no_break(new_next - pos);
} else {
builder.add_break(new_next - pos);
}
lines_wrapped += 1;
pos = new_next;
if pos == task.end || (lines_wrapped > batch_size && is_hard) {
break;
}
} else {
// EOF
builder.add_no_break(text.len() - pos);
break;
}
}
let breaks = builder.build();
let end = task.start + breaks.len();
// this is correct *only* when an edit has not occured.
let inval_soft =
self.breaks.count::<BreaksMetric>(end) - self.breaks.count::<BreaksMetric>(task.start);
let hard_count = 1 + text.line_of_offset(end) - text.line_of_offset(task.start);
let inval_count = inval_soft + hard_count;
let new_soft = breaks.measure::<BreaksMetric>();
let new_count = new_soft + hard_count;
let iv = Interval::new(task.start, end);
self.breaks.edit(iv, breaks);
self.update_tasks_after_wrap(iv);
WrapSummary { start_line, inval_count, new_count, new_soft }
}
pub fn logical_line_range(&self, text: &Rope, line: usize) -> (usize, usize) {
let mut cursor = MergedBreaks::new(text, &self.breaks);
let offset = cursor.offset_of_line(line);
let logical_line = text.line_of_offset(offset);
let start_logical_line_offset = text.offset_of_line(logical_line);
let end_logical_line_offset = text.offset_of_line(logical_line + 1);
(start_logical_line_offset, end_logical_line_offset)
}
#[cfg(test)]
fn for_testing(text: &Rope, wrap: WrapWidth) -> Lines {
let mut lines = Lines::default();
lines.set_wrap_width(text, wrap);
lines
}
#[cfg(test)]
fn rewrap_all(&mut self, text: &Rope, client: &Client, width_cache: &mut WidthCache) {
if !self.is_converged() {
self.do_wrap_task(text, width_cache, client, 0..10, Some(usize::max_value()));
}
}
}
/// A potential opportunity to insert a break. In this representation, the widths
/// have been requested (in a batch request) but are not necessarily known until
/// the request is issued.
struct PotentialBreak {
/// The offset within the text of the end of the word.
pos: usize,
/// A token referencing the width of the word, to be resolved in the width cache.
tok: Token,
/// Whether the break is a hard break or a soft break.
hard: bool,
}
/// State for a rewrap in progress
struct RewrapCtx<'a> {
text: &'a Rope,
lb_cursor: LineBreakCursor<'a>,
lb_cursor_pos: usize,
width_cache: &'a mut WidthCache,
client: &'a dyn WidthMeasure,
pot_breaks: Vec<PotentialBreak>,
/// Index within `pot_breaks`
pot_break_ix: usize,
max_width: f64,
}
// This constant should be tuned so that the RPC takes about 1ms. Less than that,
// RPC overhead becomes significant. More than that, interactivity suffers.
const MAX_POT_BREAKS: usize = 10_000;
impl<'a> RewrapCtx<'a> {
fn new(
text: &'a Rope,
//_style_spans: &Spans<Style>, client: &'a T,
client: &'a dyn WidthMeasure,
max_width: f64,
width_cache: &'a mut WidthCache,
start: usize,
) -> RewrapCtx<'a> {
let lb_cursor_pos = start;
let lb_cursor = LineBreakCursor::new(text, start);
RewrapCtx {
text,
lb_cursor,
lb_cursor_pos,
width_cache,
client,
pot_breaks: Vec::new(),
pot_break_ix: 0,
max_width,
}
}
fn refill_pot_breaks(&mut self) {
let mut req = self.width_cache.batch_req();
self.pot_breaks.clear();
self.pot_break_ix = 0;
let mut pos = self.lb_cursor_pos;
while pos < self.text.len() && self.pot_breaks.len() < MAX_POT_BREAKS {
let (next, hard) = self.lb_cursor.next();
let word = self.text.slice_to_cow(pos..next);
let tok = req.request(N_RESERVED_STYLES, &word);
pos = next;
self.pot_breaks.push(PotentialBreak { pos, tok, hard });
}
req.resolve_pending(self.client).unwrap();
self.lb_cursor_pos = pos;
}
/// Compute the next break, assuming `start` is a valid break.
///
/// Invariant: `start` corresponds to the start of the word referenced by `pot_break_ix`.
fn wrap_one_line(&mut self, start: usize) -> Option<usize> {
let mut line_width = 0.0;
let mut pos = start;
while pos < self.text.len() {
if self.pot_break_ix >= self.pot_breaks.len() {
self.refill_pot_breaks();
}
let pot_break = &self.pot_breaks[self.pot_break_ix];
let width = self.width_cache.resolve(pot_break.tok);
if !pot_break.hard {
if line_width == 0.0 && width >= self.max_width {
// we don't care about soft breaks at EOF
if pot_break.pos == self.text.len() {
return None;
}
self.pot_break_ix += 1;
return Some(pot_break.pos);
}
line_width += width;
if line_width > self.max_width {
return Some(pos);
}
self.pot_break_ix += 1;
pos = pot_break.pos;
} else if line_width != 0. && width + line_width > self.max_width {
// if this is a hard break but we would have broken at the previous
// pos otherwise, we still break at the previous pos.
return Some(pos);
} else {
self.pot_break_ix += 1;
return Some(pot_break.pos);
}
}
None
}
}
struct LineBreakCursor<'a> {
inner: Cursor<'a, RopeInfo>,
lb_iter: LineBreakLeafIter,
last_byte: u8,
}
impl<'a> LineBreakCursor<'a> {
fn new(text: &'a Rope, pos: usize) -> LineBreakCursor<'a> {
let inner = Cursor::new(text, pos);
let lb_iter = match inner.get_leaf() {
Some((s, offset)) => LineBreakLeafIter::new(s.as_str(), offset),
_ => LineBreakLeafIter::default(),
};
LineBreakCursor { inner, lb_iter, last_byte: 0 }
}
// position and whether break is hard; up to caller to stop calling after EOT
fn next(&mut self) -> (usize, bool) {
let mut leaf = self.inner.get_leaf();
loop {
match leaf {
Some((s, offset)) => {
let (next, hard) = self.lb_iter.next(s.as_str());
if next < s.len() {
return (self.inner.pos() - offset + next, hard);
}
if !s.is_empty() {
self.last_byte = s.as_bytes()[s.len() - 1];
}
leaf = self.inner.next_leaf();
}
// A little hacky but only reports last break as hard if final newline
None => return (self.inner.pos(), self.last_byte == b'\n'),
}
}
}
}
struct VisualLines<'a> {
cursor: MergedBreaks<'a>,
offset: usize,
/// The current logical line number.
logical_line: usize,
len: usize,
eof: bool,
}
impl<'a> Iterator for VisualLines<'a> {
type Item = VisualLine;
fn next(&mut self) -> Option<VisualLine> {
let line_num = if self.cursor.is_hard_break() { Some(self.logical_line) } else { None };
let next_end_bound = match self.cursor.next() {
Some(b) => b,
None if self.eof => return None,
_else => {
self.eof = true;
self.len
}
};
let result = VisualLine::new(self.offset..next_end_bound, line_num);
if self.cursor.is_hard_break() {
self.logical_line += 1;
}
self.offset = next_end_bound;
Some(result)
}
}
/// A cursor over both hard and soft breaks. Hard breaks are retrieved from
/// the rope; the soft breaks are stored independently; this interleaves them.
///
/// # Invariants:
///
/// `self.offset` is always a valid break in one of the cursors, unless
/// at 0 or EOF.
///
/// `self.offset == self.text.pos().min(self.soft.pos())`.
struct MergedBreaks<'a> {
text: Cursor<'a, RopeInfo>,
soft: Cursor<'a, BreaksInfo>,
offset: usize,
/// Starting from zero, how many calls to `next` to get to `self.offset`?
cur_line: usize,
total_lines: usize,
/// Total length, in base units
len: usize,
}
impl<'a> Iterator for MergedBreaks<'a> {
type Item = usize;
fn next(&mut self) -> Option<usize> {
if self.text.pos() == self.offset && !self.at_eof() {
// don't iterate past EOF, or we can't get the leaf and check for \n
self.text.next::<LinesMetric>();
}
if self.soft.pos() == self.offset {
self.soft.next::<BreaksMetric>();
}
let prev_off = self.offset;
self.offset = self.text.pos().min(self.soft.pos());
let eof_without_newline = self.offset > 0 && self.at_eof() && self.eof_without_newline();
if self.offset == prev_off || eof_without_newline {
None
} else {
self.cur_line += 1;
Some(self.offset)
}
}
}
// arrived at this by just trying out a bunch of values ¯\_(ツ)_/¯
/// how far away a line can be before we switch to a binary search
const MAX_LINEAR_DIST: usize = 20;
impl<'a> MergedBreaks<'a> {
fn new(text: &'a Rope, breaks: &'a Breaks) -> Self {
debug_assert_eq!(text.len(), breaks.len());
let text = Cursor::new(text, 0);
let soft = Cursor::new(breaks, 0);
let total_lines =
text.root().measure::<LinesMetric>() + soft.root().measure::<BreaksMetric>() + 1;
let len = text.total_len();
MergedBreaks { text, soft, offset: 0, cur_line: 0, total_lines, len }
}
/// Sets the `self.offset` to the first valid break immediately at or preceding `offset`,
/// and restores invariants.
fn set_offset(&mut self, offset: usize) {
self.text.set(offset);
self.soft.set(offset);
if offset > 0 {
if self.text.at_or_prev::<LinesMetric>().is_none() {
self.text.set(0);
}
if self.soft.at_or_prev::<BreaksMetric>().is_none() {
self.soft.set(0);
}
}
// self.offset should be at the first valid break immediately preceding `offset`, or 0.
// the position of the non-break cursor should be > than that of the break cursor, or EOF.
match self.text.pos().cmp(&self.soft.pos()) {
Ordering::Less => {
self.text.next::<LinesMetric>();
}
Ordering::Greater => {
self.soft.next::<BreaksMetric>();
}
Ordering::Equal => assert!(self.text.pos() == 0),
}
self.offset = self.text.pos().min(self.soft.pos());
self.cur_line = merged_line_of_offset(self.text.root(), self.soft.root(), self.offset);
}
fn offset_of_line(&mut self, line: usize) -> usize {
match line {
0 => 0,
l if l >= self.total_lines => self.text.total_len(),
l if l == self.cur_line => self.offset,
l if l > self.cur_line && l - self.cur_line < MAX_LINEAR_DIST => {
self.offset_of_line_linear(l)
}
other => self.offset_of_line_bsearch(other),
}
}
fn offset_of_line_linear(&mut self, line: usize) -> usize {
assert!(line > self.cur_line);
let dist = line - self.cur_line;
self.nth(dist - 1).unwrap_or(self.len)
}
fn offset_of_line_bsearch(&mut self, line: usize) -> usize {
let mut range = 0..self.len;
loop {
let pivot = range.start + (range.end - range.start) / 2;
self.set_offset(pivot);
match self.cur_line {
l if l == line => break self.offset,
l if l > line => range = range.start..pivot,
l if line - l > MAX_LINEAR_DIST => range = pivot..range.end,
_else => break self.offset_of_line_linear(line),
}
}
}
fn is_hard_break(&self) -> bool {
self.offset == self.text.pos()
}
fn at_eof(&self) -> bool {
self.offset == self.len
}
fn eof_without_newline(&mut self) -> bool {
debug_assert!(self.at_eof());
self.text.set(self.len);
self.text.get_leaf().map(|(l, _)| l.as_bytes().last() != Some(&b'\n')).unwrap()
}
}
fn merged_line_of_offset(text: &Rope, soft: &Breaks, offset: usize) -> usize {
text.count::<LinesMetric>(offset) + soft.count::<BreaksMetric>(offset)
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Cow;
use xi_rpc::test_utils::DummyPeer;
fn make_lines(text: &Rope, width: f64) -> Lines {
let client = Client::new(Box::new(DummyPeer));
let mut width_cache = WidthCache::new();
let wrap = WrapWidth::Bytes(width as usize);
let mut lines = Lines::for_testing(text, wrap);
lines.rewrap_all(text, &client, &mut width_cache);
lines
}
fn render_breaks<'a>(text: &'a Rope, lines: &Lines) -> Vec<Cow<'a, str>> {
let result = lines.iter_lines(text, 0).map(|l| text.slice_to_cow(l.interval)).collect();
result
}
fn debug_breaks(text: &Rope, width: f64) -> Vec<Cow<'_, str>> {
let lines = make_lines(text, width);
render_breaks(text, &lines)
}
#[test]
fn column_breaks_basic() {
let text: Rope = "every wordthing should getits own".into();
let result = debug_breaks(&text, 8.0);
assert_eq!(result, vec!["every ", "wordthing ", "should ", "getits ", "own",]);
}
#[test]
fn column_breaks_trailing_newline() {
let text: Rope = "every wordthing should getits ow\n".into();
let result = debug_breaks(&text, 8.0);
assert_eq!(result, vec!["every ", "wordthing ", "should ", "getits ", "ow\n", "",]);
}
#[test]
fn soft_before_hard() {
let text: Rope = "create abreak between THESE TWO\nwords andbreakcorrectlyhere\nplz".into();
let result = debug_breaks(&text, 4.0);
assert_eq!(
result,
vec![
"create ",
"abreak ",
"between ",
"THESE ",
"TWO\n",
"words ",
"andbreakcorrectlyhere\n",
"plz",
]
);
}
#[test]
fn column_breaks_hard_soft() {
let text: Rope = "so\nevery wordthing should getits own".into();
let result = debug_breaks(&text, 4.0);
assert_eq!(result, vec!["so\n", "every ", "wordthing ", "should ", "getits ", "own",]);
}
#[test]
fn empty_file() {
let text: Rope = "".into();
let result = debug_breaks(&text, 4.0);
assert_eq!(result, vec![""]);
}
#[test]
fn dont_break_til_i_tell_you() {
let text: Rope = "thisis_longerthan_our_break_width".into();
let result = debug_breaks(&text, 12.0);
assert_eq!(result, vec!["thisis_longerthan_our_break_width"]);
}
#[test]
fn break_now_though() {
let text: Rope = "thisis_longerthan_our_break_width hi".into();
let result = debug_breaks(&text, 12.0);
assert_eq!(result, vec!["thisis_longerthan_our_break_width ", "hi"]);
}
#[test]
fn newlines() {
let text: Rope = "\n\n".into();
let result = debug_breaks(&text, 4.0);
assert_eq!(result, vec!["\n", "\n", ""]);
}
#[test]
fn newline_eof() {
let text: Rope = "hello\n".into();
let result = debug_breaks(&text, 4.0);
assert_eq!(result, vec!["hello\n", ""]);
}
#[test]
fn no_newline_eof() {
let text: Rope = "hello".into();
let result = debug_breaks(&text, 4.0);
assert_eq!(result, vec!["hello"]);
}
#[test]
fn merged_offset() {
let text: Rope = "a quite\nshort text".into();
let mut builder = BreakBuilder::new();
builder.add_break(2);
builder.add_no_break(text.len() - 2);
let breaks = builder.build();
assert_eq!(merged_line_of_offset(&text, &breaks, 0), 0);
assert_eq!(merged_line_of_offset(&text, &breaks, 1), 0);
assert_eq!(merged_line_of_offset(&text, &breaks, 2), 1);
assert_eq!(merged_line_of_offset(&text, &breaks, 5), 1);
assert_eq!(merged_line_of_offset(&text, &breaks, 5), 1);
assert_eq!(merged_line_of_offset(&text, &breaks, 9), 2);
assert_eq!(merged_line_of_offset(&text, &breaks, text.len()), 2);
let text: Rope = "a quite\nshort tex\n".into();
// trailing newline increases total count
assert_eq!(merged_line_of_offset(&text, &breaks, text.len()), 3);
}
#[test]
fn bsearch_equivalence() {
let text: Rope =
"this is a line with some text in it, which is not unusual\n".repeat(1000).into();
let lines = make_lines(&text, 30.);
let mut linear = MergedBreaks::new(&text, &lines.breaks);
let mut binary = MergedBreaks::new(&text, &lines.breaks);
// skip zero because these two impls don't handle edge cases
for i in 1..1000 {
linear.set_offset(0);
binary.set_offset(0);
assert_eq!(
linear.offset_of_line_linear(i),
binary.offset_of_line_bsearch(i),
"line {}",
i
);
}
}
#[test]
fn merge_cursor_no_breaks() {
let text: Rope = "aaaa\nbb bb cc\ncc dddd eeee ff\nff gggg".into();
// first with no breaks
let breaks = Breaks::new_no_break(text.len());
let mut cursor = MergedBreaks::new(&text, &breaks);
assert_eq!(cursor.offset, 0);
assert_eq!(cursor.cur_line, 0);
assert_eq!(cursor.len, text.len());
assert_eq!(cursor.total_lines, 4);
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/layers.rs | rust/core-lib/src/layers.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Handles syntax highlighting and other styling.
//!
//! Plugins provide syntax highlighting information in the form of 'scopes'.
//! Scope information originating from any number of plugins can be resolved
//! into styles using a theme, augmented with additional style definitions.
use std::collections::{BTreeMap, HashMap, HashSet};
use syntect::highlighting::StyleModifier;
use syntect::parsing::Scope;
use xi_rope::spans::{Spans, SpansBuilder};
use xi_rope::{Interval, RopeDelta};
use xi_trace::trace_block;
use crate::plugins::PluginPid;
use crate::styles::{Style, ThemeStyleMap};
/// A collection of layers containing scope information.
#[derive(Default)]
pub struct Layers {
layers: BTreeMap<PluginPid, ScopeLayer>,
deleted: HashSet<PluginPid>,
merged: Spans<Style>,
}
/// A collection of scope spans from a single source.
#[derive(Default)]
pub struct ScopeLayer {
stack_lookup: Vec<Vec<Scope>>,
style_lookup: Vec<Style>,
// TODO: this might be efficient (in memory at least) if we use
// a prefix tree.
/// style state of existing scope spans, so we can more efficiently
/// compute styles of child spans.
style_cache: HashMap<Vec<Scope>, StyleModifier>,
/// Human readable scope names, for debugging
scope_spans: Spans<u32>,
style_spans: Spans<Style>,
}
impl Layers {
pub fn get_merged(&self) -> &Spans<Style> {
&self.merged
}
/// Adds the provided scopes to the layer's lookup table.
pub fn add_scopes(
&mut self,
layer: PluginPid,
scopes: Vec<Vec<String>>,
style_map: &ThemeStyleMap,
) {
let _t = trace_block("Layers::AddScopes", &["core"]);
if self.create_if_missing(layer).is_err() {
return;
}
self.layers.get_mut(&layer).unwrap().add_scopes(scopes, style_map);
}
/// Applies the delta to all layers, inserting empty intervals
/// for any regions inserted in the delta.
///
/// This is useful for clearing spans, and for updating spans
/// as edits occur.
pub fn update_all(&mut self, delta: &RopeDelta) {
self.merged.apply_shape(delta);
for layer in self.layers.values_mut() {
layer.blank_scopes(delta);
}
let (iv, _len) = delta.summary();
self.resolve_styles(iv);
}
/// Updates the scope spans for a given layer.
pub fn update_layer(&mut self, layer: PluginPid, iv: Interval, spans: Spans<u32>) {
if self.create_if_missing(layer).is_err() {
return;
}
self.layers.get_mut(&layer).unwrap().update_scopes(iv, &spans);
self.resolve_styles(iv);
}
/// Removes a given layer. This will remove all styles derived from
/// that layer's scopes.
pub fn remove_layer(&mut self, layer: PluginPid) -> Option<ScopeLayer> {
self.deleted.insert(layer);
let layer = self.layers.remove(&layer);
if layer.is_some() {
let iv_all = Interval::new(0, self.merged.len());
//TODO: should Spans<T> have a clear() method?
self.merged = SpansBuilder::new(self.merged.len()).build();
self.resolve_styles(iv_all);
}
layer
}
pub fn theme_changed(&mut self, style_map: &ThemeStyleMap) {
for layer in self.layers.values_mut() {
layer.theme_changed(style_map);
}
self.merged = SpansBuilder::new(self.merged.len()).build();
let iv_all = Interval::new(0, self.merged.len());
self.resolve_styles(iv_all);
}
/// Resolves styles from all layers for the given interval, updating
/// the master style spans.
fn resolve_styles(&mut self, iv: Interval) {
if self.layers.is_empty() {
return;
}
let mut layer_iter = self.layers.values();
let mut resolved = layer_iter.next().unwrap().style_spans.subseq(iv);
for other in layer_iter {
let spans = other.style_spans.subseq(iv);
assert_eq!(resolved.len(), spans.len());
resolved = resolved.merge(&spans, |a, b| match b {
Some(b) => a.merge(b),
None => a.to_owned(),
});
}
self.merged.edit(iv, resolved);
}
/// Prints scopes and style information for the given `Interval`.
pub fn debug_print_spans(&self, iv: Interval) {
for (id, layer) in &self.layers {
let spans = layer.scope_spans.subseq(iv);
let styles = layer.style_spans.subseq(iv);
if spans.iter().next().is_some() {
info!("scopes for layer {:?}:", id);
for (iv, val) in spans.iter() {
info!("{}: {:?}", iv, layer.stack_lookup[*val as usize]);
}
info!("styles:");
for (iv, val) in styles.iter() {
info!("{}: {:?}", iv, val);
}
}
}
}
/// Returns an `Err` if this layer has been deleted; the caller should return.
fn create_if_missing(&mut self, layer_id: PluginPid) -> Result<(), ()> {
if self.deleted.contains(&layer_id) {
return Err(());
}
if !self.layers.contains_key(&layer_id) {
self.layers.insert(layer_id, ScopeLayer::new(self.merged.len()));
}
Ok(())
}
}
impl ScopeLayer {
pub fn new(len: usize) -> Self {
ScopeLayer {
stack_lookup: Vec::new(),
style_lookup: Vec::new(),
style_cache: HashMap::new(),
scope_spans: SpansBuilder::new(len).build(),
style_spans: SpansBuilder::new(len).build(),
}
}
fn theme_changed(&mut self, style_map: &ThemeStyleMap) {
// recompute styles with the new theme
let cur_stacks = self.stack_lookup.clone();
self.style_lookup = self.styles_for_stacks(&cur_stacks, style_map);
let iv_all = Interval::new(0, self.style_spans.len());
self.style_spans = SpansBuilder::new(self.style_spans.len()).build();
// this feels unnecessary but we can't pass in a reference to self
// and I don't want to get fancy unless there's an actual perf problem
let scopes = self.scope_spans.clone();
self.update_styles(iv_all, &scopes)
}
fn add_scopes(&mut self, scopes: Vec<Vec<String>>, style_map: &ThemeStyleMap) {
let mut stacks = Vec::with_capacity(scopes.len());
for stack in scopes {
let scopes = stack
.iter()
.map(|s| Scope::new(s))
.filter(|result| match *result {
Err(ref err) => {
warn!("failed to resolve scope {}\nErr: {:?}", &stack.join(" "), err);
false
}
_ => true,
})
.map(|s| s.unwrap())
.collect::<Vec<_>>();
stacks.push(scopes);
}
let mut new_styles = self.styles_for_stacks(stacks.as_slice(), style_map);
self.stack_lookup.append(&mut stacks);
self.style_lookup.append(&mut new_styles);
}
fn styles_for_stacks(
&mut self,
stacks: &[Vec<Scope>],
style_map: &ThemeStyleMap,
) -> Vec<Style> {
//let style_map = style_map.borrow();
let highlighter = style_map.get_highlighter();
let mut new_styles = Vec::new();
for stack in stacks {
let mut last_style: Option<StyleModifier> = None;
let mut upper_bound_of_last = stack.len() as usize;
// walk backwards through stack to see if we have an existing
// style for any child stacks.
for i in 0..stack.len() - 1 {
let prev_range = 0..stack.len() - (i + 1);
if let Some(s) = self.style_cache.get(&stack[prev_range]) {
last_style = Some(*s);
upper_bound_of_last = stack.len() - (i + 1);
break;
}
}
let mut base_style_mod = last_style.unwrap_or_default();
// apply the stack, generating children as needed.
for i in upper_bound_of_last..stack.len() {
let style_mod = highlighter.style_mod_for_stack(&stack[0..=i]);
base_style_mod = base_style_mod.apply(style_mod);
}
let style = Style::from_syntect_style_mod(&base_style_mod);
self.style_cache.insert(stack.clone(), base_style_mod);
new_styles.push(style);
}
new_styles
}
fn update_scopes(&mut self, iv: Interval, spans: &Spans<u32>) {
self.scope_spans.edit(iv, spans.to_owned());
self.update_styles(iv, spans);
}
/// Applies `delta`, which is presumed to contain empty spans.
/// This is only used when we receive an edit, to adjust current span
/// positions.
fn blank_scopes(&mut self, delta: &RopeDelta) {
self.style_spans.apply_shape(delta);
self.scope_spans.apply_shape(delta);
}
/// Updates `self.style_spans`, mapping scopes to styles and combining
/// adjacent and equal spans.
fn update_styles(&mut self, iv: Interval, spans: &Spans<u32>) {
// NOTE: This is a tradeoff. Keeping both u32 and Style spans for each
// layer makes debugging simpler and reduces the total number of spans
// on the wire (because we combine spans that resolve to the same style)
// but it does require additional computation + memory up front.
let mut sb = SpansBuilder::new(spans.len());
let mut spans_iter = spans.iter();
let mut prev = spans_iter.next();
{
// distinct adjacent scopes can often resolve to the same style,
// so we combine them when building the styles.
let style_eq = |i1: &u32, i2: &u32| {
self.style_lookup[*i1 as usize] == self.style_lookup[*i2 as usize]
};
while let Some((p_iv, p_val)) = prev {
match spans_iter.next() {
Some((n_iv, n_val)) if n_iv.start() == p_iv.end() && style_eq(p_val, n_val) => {
prev = Some((p_iv.union(n_iv), p_val));
}
other => {
sb.add_span(p_iv, self.style_lookup[*p_val as usize].to_owned());
prev = other;
}
}
}
}
self.style_spans.edit(iv, sb.build());
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/tabs.rs | rust/core-lib/src/tabs.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The main container for core state.
//!
//! All events from the frontend or from plugins are handled here first.
//!
//! This file is called 'tabs' for historical reasons, and should probably
//! be renamed.
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashSet};
use std::fmt;
use std::fs::File;
use std::io;
use std::mem;
use std::path::{Path, PathBuf};
use serde::de::{self, Deserialize, Deserializer, Unexpected};
use serde::ser::{Serialize, Serializer};
use serde_json::Value;
use xi_rope::Rope;
use xi_rpc::{self, ReadError, RemoteError, RpcCtx, RpcPeer};
use xi_trace::{self, trace_block};
use crate::client::Client;
use crate::config::{self, ConfigDomain, ConfigDomainExternal, ConfigManager, Table};
use crate::editor::Editor;
use crate::event_context::EventContext;
use crate::file::FileManager;
use crate::line_ending::LineEnding;
use crate::plugin_rpc::{PluginNotification, PluginRequest};
use crate::plugins::rpc::ClientPluginInfo;
use crate::plugins::{start_plugin_process, Plugin, PluginCatalog, PluginPid};
use crate::recorder::Recorder;
use crate::rpc::{
CoreNotification, CoreRequest, EditNotification, EditRequest,
PluginNotification as CorePluginNotification,
};
use crate::styles::{ThemeStyleMap, DEFAULT_THEME};
use crate::syntax::LanguageId;
use crate::view::View;
use crate::whitespace::Indentation;
use crate::width_cache::WidthCache;
use crate::WeakXiCore;
#[cfg(feature = "notify")]
use crate::watcher::{FileWatcher, WatchToken};
#[cfg(feature = "notify")]
use notify::Event;
#[cfg(feature = "notify")]
use std::ffi::OsStr;
/// ViewIds are the primary means of routing messages between
/// xi-core and a client view.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ViewId(pub(crate) usize);
/// BufferIds uniquely identify open buffers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
pub struct BufferId(pub(crate) usize);
pub type PluginId = crate::plugins::PluginPid;
// old-style names; will be deprecated
pub type BufferIdentifier = BufferId;
/// Totally arbitrary; we reserve this space for `ViewId`s
pub(crate) const RENDER_VIEW_IDLE_MASK: usize = 1 << 25;
pub(crate) const REWRAP_VIEW_IDLE_MASK: usize = 1 << 26;
pub(crate) const FIND_VIEW_IDLE_MASK: usize = 1 << 27;
const NEW_VIEW_IDLE_TOKEN: usize = 1001;
/// xi_rpc idle Token for watcher related idle scheduling.
pub(crate) const WATCH_IDLE_TOKEN: usize = 1002;
#[cfg(feature = "notify")]
const CONFIG_EVENT_TOKEN: WatchToken = WatchToken(1);
/// Token for file-change events in open files
#[cfg(feature = "notify")]
pub const OPEN_FILE_EVENT_TOKEN: WatchToken = WatchToken(2);
#[cfg(feature = "notify")]
const THEME_FILE_EVENT_TOKEN: WatchToken = WatchToken(3);
#[cfg(feature = "notify")]
const PLUGIN_EVENT_TOKEN: WatchToken = WatchToken(4);
#[allow(dead_code)]
pub struct CoreState {
editors: BTreeMap<BufferId, RefCell<Editor>>,
views: BTreeMap<ViewId, RefCell<View>>,
file_manager: FileManager,
/// A local pasteboard.
kill_ring: RefCell<Rope>,
/// Theme and style state.
style_map: RefCell<ThemeStyleMap>,
width_cache: RefCell<WidthCache>,
/// User and platform specific settings
config_manager: ConfigManager,
/// Recorded editor actions
recorder: RefCell<Recorder>,
/// A weak reference to the main state container, stashed so that
/// it can be passed to plugins.
self_ref: Option<WeakXiCore>,
/// Views which need to have setup finished.
pending_views: Vec<(ViewId, Table)>,
peer: Client,
id_counter: Counter,
plugins: PluginCatalog,
// for the time being we auto-start all plugins we find on launch.
running_plugins: Vec<Plugin>,
}
/// Initial setup and bookkeeping
impl CoreState {
pub(crate) fn new(
peer: &RpcPeer,
config_dir: Option<PathBuf>,
extras_dir: Option<PathBuf>,
) -> Self {
#[cfg(feature = "notify")]
let mut watcher = FileWatcher::new(peer.clone());
if let Some(p) = config_dir.as_ref() {
if !p.exists() {
if let Err(e) = config::init_config_dir(p) {
//TODO: report this error?
error!("error initing file based configs: {:?}", e);
}
}
#[cfg(feature = "notify")]
watcher.watch_filtered(p, true, CONFIG_EVENT_TOKEN, |p| {
p.extension().and_then(OsStr::to_str).unwrap_or("") == "xiconfig"
});
}
let config_manager = ConfigManager::new(config_dir, extras_dir);
let themes_dir = config_manager.get_themes_dir();
if let Some(p) = themes_dir.as_ref() {
#[cfg(feature = "notify")]
watcher.watch_filtered(p, true, THEME_FILE_EVENT_TOKEN, |p| {
p.extension().and_then(OsStr::to_str).unwrap_or("") == "tmTheme"
});
}
let plugins_dir = config_manager.get_plugins_dir();
if let Some(p) = plugins_dir.as_ref() {
#[cfg(feature = "notify")]
watcher.watch_filtered(p, true, PLUGIN_EVENT_TOKEN, |p| p.is_dir() || !p.exists());
}
CoreState {
views: BTreeMap::new(),
editors: BTreeMap::new(),
#[cfg(feature = "notify")]
file_manager: FileManager::new(watcher),
#[cfg(not(feature = "notify"))]
file_manager: FileManager::new(),
kill_ring: RefCell::new(Rope::from("")),
style_map: RefCell::new(ThemeStyleMap::new(themes_dir)),
width_cache: RefCell::new(WidthCache::new()),
config_manager,
recorder: RefCell::new(Recorder::new()),
self_ref: None,
pending_views: Vec::new(),
peer: Client::new(peer.clone()),
id_counter: Counter::default(),
plugins: PluginCatalog::default(),
running_plugins: Vec::new(),
}
}
fn next_view_id(&self) -> ViewId {
ViewId(self.id_counter.next())
}
fn next_buffer_id(&self) -> BufferId {
BufferId(self.id_counter.next())
}
fn next_plugin_id(&self) -> PluginId {
PluginPid(self.id_counter.next())
}
pub(crate) fn finish_setup(&mut self, self_ref: WeakXiCore) {
self.self_ref = Some(self_ref);
if let Some(path) = self.config_manager.base_config_file_path() {
self.load_file_based_config(&path);
}
// Load the custom theme files.
self.style_map.borrow_mut().load_theme_dir();
// instead of having to do this here, config should just own
// the plugin catalog and reload automatically
let plugin_paths = self.config_manager.get_plugin_paths();
self.plugins.reload_from_paths(&plugin_paths);
let languages = self.plugins.make_languages_map();
let languages_ids = languages.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
self.peer.available_languages(languages_ids);
self.config_manager.set_languages(languages);
let theme_names = self.style_map.borrow().get_theme_names();
self.peer.available_themes(theme_names);
// FIXME: temporary: we just launch every plugin we find at startup
for manifest in self.plugins.iter() {
start_plugin_process(
manifest.clone(),
self.next_plugin_id(),
self.self_ref.as_ref().unwrap().clone(),
);
}
}
/// Attempt to load a config file.
fn load_file_based_config(&mut self, path: &Path) {
let _t = trace_block("CoreState::load_config_file", &["core"]);
if let Some(domain) = self.config_manager.domain_for_path(path) {
match config::try_load_from_file(path) {
Ok(table) => self.set_config(domain, table),
Err(e) => self.peer.alert(e.to_string()),
}
} else {
self.peer.alert(format!("Unexpected config file {:?}", path));
}
}
/// Sets (overwriting) the config for a given domain.
fn set_config(&mut self, domain: ConfigDomain, table: Table) {
match self.config_manager.set_user_config(domain, table) {
Err(e) => self.peer.alert(format!("{}", &e)),
Ok(changes) => self.handle_config_changes(changes),
}
}
/// Notify editors/views/plugins of config changes.
fn handle_config_changes(&self, changes: Vec<(BufferId, Table)>) {
for (id, table) in changes {
let view_id = self
.views
.values()
.find(|v| v.borrow().get_buffer_id() == id)
.map(|v| v.borrow().get_view_id())
.unwrap();
self.make_context(view_id).unwrap().config_changed(&table)
}
}
}
/// Handling client events
impl CoreState {
/// Creates an `EventContext` for the provided `ViewId`. This context
/// holds references to the `Editor` and `View` backing this `ViewId`,
/// as well as to sibling views, plugins, and other state necessary
/// for handling most events.
pub(crate) fn make_context(&self, view_id: ViewId) -> Option<EventContext> {
self.views.get(&view_id).map(|view| {
let buffer_id = view.borrow().get_buffer_id();
let editor = &self.editors[&buffer_id];
let info = self.file_manager.get_info(buffer_id);
let plugins = self.running_plugins.iter().collect::<Vec<_>>();
let config = self.config_manager.get_buffer_config(buffer_id);
let language = self.config_manager.get_buffer_language(buffer_id);
EventContext {
view_id,
buffer_id,
view,
editor,
config: &config.items,
recorder: &self.recorder,
language,
info,
siblings: Vec::new(),
plugins,
client: &self.peer,
style_map: &self.style_map,
width_cache: &self.width_cache,
kill_ring: &self.kill_ring,
weak_core: self.self_ref.as_ref().unwrap(),
}
})
}
/// Produces an iterator over all event contexts, with each view appearing
/// exactly once.
fn iter_groups<'a>(&'a self) -> Iter<'a, Box<dyn Iterator<Item = &ViewId> + 'a>> {
Iter { views: Box::new(self.views.keys()), seen: HashSet::new(), inner: self }
}
pub(crate) fn client_notification(&mut self, cmd: CoreNotification) {
use self::CoreNotification::*;
use self::CorePluginNotification as PN;
match cmd {
Edit(crate::rpc::EditCommand { view_id, cmd }) => self.do_edit(view_id, cmd),
Save { view_id, file_path } => self.do_save(view_id, file_path),
CloseView { view_id } => self.do_close_view(view_id),
ModifyUserConfig { domain, changes } => self.do_modify_user_config(domain, changes),
SetTheme { theme_name } => self.do_set_theme(&theme_name),
SaveTrace { destination, frontend_samples } => {
self.save_trace(&destination, frontend_samples)
}
Plugin(cmd) => match cmd {
PN::Start { view_id, plugin_name } => self.do_start_plugin(view_id, &plugin_name),
PN::Stop { view_id, plugin_name } => self.do_stop_plugin(view_id, &plugin_name),
PN::PluginRpc { view_id, receiver, rpc } => {
self.do_plugin_rpc(view_id, &receiver, &rpc.method, &rpc.params)
}
},
TracingConfig { enabled } => self.toggle_tracing(enabled),
// handled at the top level
ClientStarted { .. } => (),
SetLanguage { view_id, language_id } => self.do_set_language(view_id, language_id),
}
}
pub(crate) fn client_request(&mut self, cmd: CoreRequest) -> Result<Value, RemoteError> {
use self::CoreRequest::*;
match cmd {
//TODO: make file_path be an Option<PathBuf>
//TODO: make this a notification
NewView { file_path } => self.do_new_view(file_path.map(PathBuf::from)),
Edit(crate::rpc::EditCommand { view_id, cmd }) => self.do_edit_sync(view_id, cmd),
//TODO: why is this a request?? make a notification?
GetConfig { view_id } => self.do_get_config(view_id).map(|c| json!(c)),
DebugGetContents { view_id } => self.do_get_contents(view_id).map(|c| json!(c)),
}
}
fn do_edit(&mut self, view_id: ViewId, cmd: EditNotification) {
if let Some(mut edit_ctx) = self.make_context(view_id) {
edit_ctx.do_edit(cmd);
}
}
fn do_edit_sync(&mut self, view_id: ViewId, cmd: EditRequest) -> Result<Value, RemoteError> {
if let Some(mut edit_ctx) = self.make_context(view_id) {
edit_ctx.do_edit_sync(cmd)
} else {
// TODO: some custom error tpye that can Into<RemoteError>
Err(RemoteError::custom(404, format!("missing view {:?}", view_id), None))
}
}
fn do_new_view(&mut self, path: Option<PathBuf>) -> Result<Value, RemoteError> {
let view_id = self.next_view_id();
let buffer_id = self.next_buffer_id();
let rope = match path.as_ref() {
Some(p) => self.file_manager.open(p, buffer_id)?,
None => Rope::from(""),
};
let editor = RefCell::new(Editor::with_text(rope));
let view = RefCell::new(View::new(view_id, buffer_id));
self.editors.insert(buffer_id, editor);
self.views.insert(view_id, view);
let config = self.config_manager.add_buffer(buffer_id, path.as_deref());
// NOTE: because this is a synchronous call, we have to initialize the
// view and return the view_id before we can send any events to this
// view. We call view_init(), mark the view as pending and schedule the
// idle handler so that we can finish setting up this view on the next
// runloop pass, in finalize_new_views.
let mut edit_ctx = self.make_context(view_id).unwrap();
edit_ctx.view_init();
self.pending_views.push((view_id, config));
self.peer.schedule_idle(NEW_VIEW_IDLE_TOKEN);
Ok(json!(view_id))
}
fn do_save<P>(&mut self, view_id: ViewId, path: P)
where
P: AsRef<Path>,
{
let _t = trace_block("CoreState::do_save", &["core"]);
let path = path.as_ref();
let buffer_id = self.views.get(&view_id).map(|v| v.borrow().get_buffer_id());
let buffer_id = match buffer_id {
Some(id) => id,
None => return,
};
let mut save_ctx = self.make_context(view_id).unwrap();
let fin_text = save_ctx.text_for_save();
if let Err(e) = self.file_manager.save(path, &fin_text, buffer_id) {
let error_message = e.to_string();
error!("File error: {:?}", error_message);
self.peer.alert(error_message);
return;
}
let changes = self.config_manager.update_buffer_path(buffer_id, path);
let language = self.config_manager.get_buffer_language(buffer_id);
self.make_context(view_id).unwrap().after_save(path);
self.make_context(view_id).unwrap().language_changed(&language);
// update the config _after_ sending save related events
if let Some(changes) = changes {
self.make_context(view_id).unwrap().config_changed(&changes);
}
}
fn do_close_view(&mut self, view_id: ViewId) {
let close_buffer = self.make_context(view_id).map(|ctx| ctx.close_view()).unwrap_or(true);
let buffer_id = self.views.remove(&view_id).map(|v| v.borrow().get_buffer_id());
if let Some(buffer_id) = buffer_id {
if close_buffer {
self.editors.remove(&buffer_id);
self.file_manager.close(buffer_id);
self.config_manager.remove_buffer(buffer_id);
}
}
}
fn do_set_theme(&self, theme_name: &str) {
//Set only if requested theme is different from the
//current one.
if theme_name != self.style_map.borrow().get_theme_name() {
if let Err(e) = self.style_map.borrow_mut().set_theme(theme_name) {
error!("error setting theme: {:?}, {:?}", theme_name, e);
return;
}
}
self.notify_client_and_update_views();
}
fn notify_client_and_update_views(&self) {
{
let style_map = self.style_map.borrow();
self.peer.theme_changed(style_map.get_theme_name(), style_map.get_theme_settings());
}
self.iter_groups().for_each(|mut edit_ctx| {
edit_ctx.with_editor(|ed, view, _, _| {
ed.theme_changed(&self.style_map.borrow());
view.set_dirty(ed.get_buffer());
});
edit_ctx.render_if_needed();
});
}
/// Updates the config for a given domain.
fn do_modify_user_config(&mut self, domain: ConfigDomainExternal, changes: Table) {
// the client sends ViewId but we need BufferId so we do a dance
let domain: ConfigDomain = match domain {
ConfigDomainExternal::General => ConfigDomain::General,
ConfigDomainExternal::Syntax(id) => ConfigDomain::Language(id),
ConfigDomainExternal::Language(id) => ConfigDomain::Language(id),
ConfigDomainExternal::UserOverride(view_id) => match self.views.get(&view_id) {
Some(v) => ConfigDomain::UserOverride(v.borrow().get_buffer_id()),
None => return,
},
};
let new_config = self.config_manager.table_for_update(domain.clone(), changes);
self.set_config(domain, new_config);
}
fn do_get_config(&self, view_id: ViewId) -> Result<Table, RemoteError> {
let _t = trace_block("CoreState::get_config", &["core"]);
self.views
.get(&view_id)
.map(|v| v.borrow().get_buffer_id())
.map(|id| self.config_manager.get_buffer_config(id).to_table())
.ok_or(RemoteError::custom(404, format!("missing {}", view_id), None))
}
fn do_get_contents(&self, view_id: ViewId) -> Result<Rope, RemoteError> {
self.make_context(view_id)
.map(|ctx| ctx.editor.borrow().get_buffer().to_owned())
.ok_or_else(|| RemoteError::custom(404, format!("No view for id {}", view_id), None))
}
fn do_set_language(&mut self, view_id: ViewId, language_id: LanguageId) {
if let Some(view) = self.views.get(&view_id) {
let buffer_id = view.borrow().get_buffer_id();
let changes = self.config_manager.override_language(buffer_id, language_id.clone());
let mut context = self.make_context(view_id).unwrap();
context.language_changed(&language_id);
if let Some(changes) = changes {
context.config_changed(&changes);
}
}
}
fn do_start_plugin(&mut self, _view_id: ViewId, plugin: &str) {
if self.running_plugins.iter().any(|p| p.name == plugin) {
info!("plugin {} already running", plugin);
return;
}
if let Some(manifest) = self.plugins.get_named(plugin) {
//TODO: lots of races possible here, we need to keep track of
//pending launches.
start_plugin_process(
manifest,
self.next_plugin_id(),
self.self_ref.as_ref().unwrap().clone(),
);
} else {
warn!("no plugin found with name '{}'", plugin);
}
}
fn do_stop_plugin(&mut self, _view_id: ViewId, plugin: &str) {
if let Some(p) = self
.running_plugins
.iter()
.position(|p| p.name == plugin)
.map(|ix| self.running_plugins.remove(ix))
{
//TODO: verify shutdown; kill if necessary
p.shutdown();
self.after_stop_plugin(&p);
}
}
fn do_plugin_rpc(&self, view_id: ViewId, receiver: &str, method: &str, params: &Value) {
self.running_plugins
.iter()
.filter(|p| p.name == receiver)
.for_each(|p| p.dispatch_command(view_id, method, params))
}
fn after_stop_plugin(&mut self, plugin: &Plugin) {
self.iter_groups().for_each(|mut cx| cx.plugin_stopped(plugin));
}
}
/// Idle, tracing, and file event handling
impl CoreState {
pub(crate) fn handle_idle(&mut self, token: usize) {
match token {
NEW_VIEW_IDLE_TOKEN => self.finalize_new_views(),
WATCH_IDLE_TOKEN => self.handle_fs_events(),
other if (other & RENDER_VIEW_IDLE_MASK) != 0 => {
self.handle_render_timer(other ^ RENDER_VIEW_IDLE_MASK)
}
other if (other & REWRAP_VIEW_IDLE_MASK) != 0 => {
self.handle_rewrap_callback(other ^ REWRAP_VIEW_IDLE_MASK)
}
other if (other & FIND_VIEW_IDLE_MASK) != 0 => {
self.handle_find_callback(other ^ FIND_VIEW_IDLE_MASK)
}
other => panic!("unexpected idle token {}", other),
};
}
fn finalize_new_views(&mut self) {
let to_start = mem::take(&mut self.pending_views);
to_start.iter().for_each(|(id, config)| {
let modified = self.detect_whitespace(*id, config);
let config = modified.as_ref().unwrap_or(config);
let mut edit_ctx = self.make_context(*id).unwrap();
edit_ctx.finish_init(config);
});
}
// Detects whitespace settings from the file and merges them with the config
fn detect_whitespace(&mut self, id: ViewId, config: &Table) -> Option<Table> {
let buffer_id = self.views.get(&id).map(|v| v.borrow().get_buffer_id())?;
let editor = self
.editors
.get(&buffer_id)
.expect("existing buffer_id must have corresponding editor");
if editor.borrow().get_buffer().is_empty() {
return None;
}
let autodetect_whitespace =
self.config_manager.get_buffer_config(buffer_id).items.autodetect_whitespace;
if !autodetect_whitespace {
return None;
}
let mut changes = Table::new();
let indentation = Indentation::parse(editor.borrow().get_buffer());
match indentation {
Ok(Some(Indentation::Tabs)) => {
changes.insert("translate_tabs_to_spaces".into(), false.into());
}
Ok(Some(Indentation::Spaces(n))) => {
changes.insert("translate_tabs_to_spaces".into(), true.into());
changes.insert("tab_size".into(), n.into());
}
Err(_) => info!("detected mixed indentation"),
Ok(None) => info!("file contains no indentation"),
}
let line_ending = LineEnding::parse(editor.borrow().get_buffer());
match line_ending {
Ok(Some(LineEnding::CrLf)) => {
changes.insert("line_ending".into(), "\r\n".into());
}
Ok(Some(LineEnding::Lf)) => {
changes.insert("line_ending".into(), "\n".into());
}
Err(_) => info!("detected mixed line endings"),
Ok(None) => info!("file contains no supported line endings"),
}
let config_delta =
self.config_manager.table_for_update(ConfigDomain::SysOverride(buffer_id), changes);
match self
.config_manager
.set_user_config(ConfigDomain::SysOverride(buffer_id), config_delta)
{
Ok(ref mut items) if !items.is_empty() => {
assert!(
items.len() == 1,
"whitespace overrides can only update a single buffer's config\n{:?}",
items
);
let table = items.remove(0).1;
let mut config = config.clone();
config.extend(table);
Some(config)
}
Ok(_) => {
warn!("set_user_config failed to update config, no tables were returned");
None
}
Err(err) => {
warn!("detect_whitespace failed to update config: {:?}", err);
None
}
}
}
fn handle_render_timer(&mut self, token: usize) {
let id: ViewId = token.into();
if let Some(mut ctx) = self.make_context(id) {
ctx._finish_delayed_render();
}
}
/// Callback for doing word wrap on a view
fn handle_rewrap_callback(&mut self, token: usize) {
let id: ViewId = token.into();
if let Some(mut ctx) = self.make_context(id) {
ctx.do_rewrap_batch();
}
}
/// Callback for doing incremental find in a view
fn handle_find_callback(&mut self, token: usize) {
let id: ViewId = token.into();
if let Some(mut ctx) = self.make_context(id) {
ctx.do_incremental_find();
}
}
#[cfg(feature = "notify")]
fn handle_fs_events(&mut self) {
let _t = trace_block("CoreState::handle_fs_events", &["core"]);
let mut events = self.file_manager.watcher().take_events();
for (token, event) in events.drain(..) {
match token {
OPEN_FILE_EVENT_TOKEN => self.handle_open_file_fs_event(event),
CONFIG_EVENT_TOKEN => self.handle_config_fs_event(event),
THEME_FILE_EVENT_TOKEN => self.handle_themes_fs_event(event),
PLUGIN_EVENT_TOKEN => self.handle_plugin_fs_event(event),
_ => warn!("unexpected fs event token {:?}", token),
}
}
}
#[cfg(not(feature = "notify"))]
fn handle_fs_events(&mut self) {}
/// Handles a file system event related to a currently open file
#[cfg(feature = "notify")]
fn handle_open_file_fs_event(&mut self, event: Event) {
use notify::event::*;
let path = match event.kind {
EventKind::Create(CreateKind::Any)
| EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))
| EventKind::Modify(ModifyKind::Any) => &event.paths[0],
other => {
debug!("Ignoring event in open file {:?}", other);
return;
}
};
let buffer_id = match self.file_manager.get_editor(path) {
Some(id) => id,
None => return,
};
let has_changes = self.file_manager.check_file(path, buffer_id);
let is_pristine = self.editors.get(&buffer_id).map(|ed| ed.borrow().is_pristine()).unwrap();
//TODO: currently we only use the file's modification time when
// determining if a file has been changed by another process.
// A more robust solution would also hash the file's contents.
if has_changes && is_pristine {
if let Ok(text) = self.file_manager.open(path, buffer_id) {
// this is ugly; we don't map buffer_id -> view_id anywhere
// but we know we must have a view.
let view_id = self
.views
.values()
.find(|v| v.borrow().get_buffer_id() == buffer_id)
.map(|v| v.borrow().get_view_id())
.unwrap();
self.make_context(view_id).unwrap().reload(text);
}
}
}
/// Handles a config related file system event.
#[cfg(feature = "notify")]
fn handle_config_fs_event(&mut self, event: Event) {
use notify::event::*;
match event.kind {
EventKind::Create(CreateKind::Any)
| EventKind::Modify(ModifyKind::Any)
| EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)) => {
self.load_file_based_config(&event.paths[0])
}
EventKind::Remove(RemoveKind::Any) if !event.paths[0].exists() => {
self.remove_config_at_path(&event.paths[0])
}
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
self.remove_config_at_path(&event.paths[0]);
self.load_file_based_config(&event.paths[1]);
}
_ => (),
}
}
fn remove_config_at_path(&mut self, path: &Path) {
if let Some(domain) = self.config_manager.domain_for_path(path) {
self.set_config(domain, Table::default());
}
}
/// Handles changes in plugin files.
#[cfg(feature = "notify")]
fn handle_plugin_fs_event(&mut self, event: Event) {
use notify::event::*;
match event.kind {
EventKind::Create(CreateKind::Any) | EventKind::Modify(ModifyKind::Any) => {
self.plugins.load_from_paths(&[event.paths[0].clone()]);
if let Some(plugin) = self.plugins.get_from_path(&event.paths[0]) {
self.do_start_plugin(ViewId(0), &plugin.name);
}
}
// the way FSEvents on macOS work, we want to verify that this path
// has actually be removed before we do anything.
EventKind::Remove(RemoveKind::Any) if !event.paths[0].exists() => {
if let Some(plugin) = self.plugins.get_from_path(&event.paths[0]) {
self.do_stop_plugin(ViewId(0), &plugin.name);
self.plugins.remove_named(&plugin.name);
}
}
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
let old = &event.paths[0];
let new = &event.paths[1];
if let Some(old_plugin) = self.plugins.get_from_path(old) {
self.do_stop_plugin(ViewId(0), &old_plugin.name);
self.plugins.remove_named(&old_plugin.name);
}
self.plugins.load_from_paths(&[new.clone()]);
if let Some(new_plugin) = self.plugins.get_from_path(new) {
self.do_start_plugin(ViewId(0), &new_plugin.name);
}
}
EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any))
| EventKind::Remove(RemoveKind::Any) => {
if let Some(plugin) = self.plugins.get_from_path(&event.paths[0]) {
self.do_stop_plugin(ViewId(0), &plugin.name);
self.do_start_plugin(ViewId(0), &plugin.name);
}
}
_ => (),
}
self.views.keys().for_each(|view_id| {
let available_plugins = self
.plugins
.iter()
.map(|plugin| ClientPluginInfo { name: plugin.name.clone(), running: true })
.collect::<Vec<_>>();
self.peer.available_plugins(*view_id, &available_plugins);
});
}
/// Handles changes in theme files.
#[cfg(feature = "notify")]
fn handle_themes_fs_event(&mut self, event: Event) {
use notify::event::*;
match event.kind {
EventKind::Create(CreateKind::Any) | EventKind::Modify(ModifyKind::Any) => {
self.load_theme_file(&event.paths[0])
}
// the way FSEvents on macOS work, we want to verify that this path
// has actually be removed before we do anything.
EventKind::Remove(RemoveKind::Any) if !event.paths[0].exists() => {
self.remove_theme(&event.paths[0]);
}
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
let old = &event.paths[0];
let new = &event.paths[1];
self.remove_theme(old);
self.load_theme_file(new);
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/lib.rs | rust/core-lib/src/lib.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The main library for xi-core.
#![allow(
clippy::boxed_local,
clippy::cast_lossless,
clippy::collapsible_if,
clippy::let_and_return,
clippy::map_entry,
clippy::match_as_ref,
clippy::match_bool,
clippy::needless_pass_by_value,
clippy::new_without_default,
clippy::or_fun_call,
clippy::ptr_arg,
clippy::too_many_arguments,
clippy::unreadable_literal,
clippy::get_unwrap
)]
#[macro_use]
extern crate log;
extern crate regex;
extern crate serde;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate memchr;
#[cfg(feature = "notify")]
extern crate notify;
extern crate syntect;
extern crate time;
extern crate toml;
extern crate xi_rope;
extern crate xi_rpc;
extern crate xi_trace;
extern crate xi_unicode;
#[cfg(feature = "ledger")]
mod ledger_includes {
extern crate fuchsia_zircon;
extern crate fuchsia_zircon_sys;
extern crate mxruntime;
#[macro_use]
extern crate fidl;
extern crate apps_ledger_services_public;
extern crate sha2;
}
#[cfg(feature = "ledger")]
use ledger_includes::*;
pub mod annotations;
pub mod backspace;
pub mod client;
pub mod config;
pub mod core;
pub mod edit_ops;
pub mod edit_types;
pub mod editor;
pub mod event_context;
pub mod file;
pub mod find;
#[cfg(feature = "ledger")]
pub mod fuchsia;
pub mod index_set;
pub mod layers;
pub mod line_cache_shadow;
pub mod line_ending;
pub mod line_offset;
pub mod linewrap;
pub mod movement;
pub mod plugins;
pub mod recorder;
pub mod selection;
pub mod styles;
pub mod syntax;
pub mod tabs;
pub mod view;
#[cfg(feature = "notify")]
pub mod watcher;
pub mod whitespace;
pub mod width_cache;
pub mod word_boundaries;
pub mod rpc;
#[cfg(feature = "ledger")]
use apps_ledger_services_public::Ledger_Proxy;
pub use crate::config::{BufferItems as BufferConfig, Table as ConfigTable};
pub use crate::core::{WeakXiCore, XiCore};
pub use crate::editor::EditType;
pub use crate::plugins::manifest as plugin_manifest;
pub use crate::plugins::rpc as plugin_rpc;
pub use crate::plugins::PluginPid;
pub use crate::syntax::{LanguageDefinition, LanguageId};
pub use crate::tabs::test_helpers;
pub use crate::tabs::{BufferId, BufferIdentifier, ViewId};
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/line_cache_shadow.rs | rust/core-lib/src/line_cache_shadow.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Data structures for tracking the state of the front-end's line cache
//! and preparing render plans to update it.
use std::cmp::{max, min};
use std::fmt;
const SCROLL_SLOP: usize = 2;
const PRESERVE_EXTENT: usize = 1000;
/// The line cache shadow tracks the state of the line cache in the front-end.
/// Any content marked as valid here is up-to-date in the current state of the
/// view. Also, if `dirty` is false, then the entire line cache is valid.
#[derive(Debug)]
pub struct LineCacheShadow {
spans: Vec<Span>,
dirty: bool,
}
type Validity = u8;
pub const INVALID: Validity = 0;
pub const TEXT_VALID: Validity = 1;
pub const STYLES_VALID: Validity = 2;
pub const CURSOR_VALID: Validity = 4;
pub const ALL_VALID: Validity = 7;
pub struct Span {
/// Number of lines in this span. Units are visual lines in the
/// current state of the view.
pub n: usize,
/// Starting line number. Units are visual lines in the front end's
/// current cache state (i.e. the last one rendered). Note: this is
/// irrelevant if validity is 0.
pub start_line_num: usize,
/// Validity of lines in this span, consisting of the above constants or'ed.
pub validity: Validity,
}
/// Builder for `LineCacheShadow` object.
pub struct Builder {
spans: Vec<Span>,
dirty: bool,
}
#[derive(Clone, Copy, PartialEq)]
pub enum RenderTactic {
/// Discard all content for this span. Used to keep storage reasonable.
Discard,
/// Preserve existing content.
Preserve,
/// Render content if it is invalid.
Render,
}
pub struct RenderPlan {
/// Each span is a number of lines and a tactic.
pub spans: Vec<(usize, RenderTactic)>,
}
pub struct PlanIterator<'a> {
lc_shadow: &'a LineCacheShadow,
plan: &'a RenderPlan,
shadow_ix: usize,
shadow_line_num: usize,
plan_ix: usize,
plan_line_num: usize,
}
pub struct PlanSegment {
/// Line number of start of segment, visual lines in current view state.
pub our_line_num: usize,
/// Line number of start of segment, visual lines in client's cache, if validity != 0.
pub their_line_num: usize,
/// Number of visual lines in this segment.
pub n: usize,
/// Validity of this segment in client's cache.
pub validity: Validity,
/// Tactic for rendering this segment.
pub tactic: RenderTactic,
}
impl Builder {
pub fn new() -> Builder {
Builder { spans: Vec::new(), dirty: false }
}
pub fn build(self) -> LineCacheShadow {
LineCacheShadow { spans: self.spans, dirty: self.dirty }
}
pub fn add_span(&mut self, n: usize, start_line_num: usize, validity: Validity) {
if n > 0 {
if let Some(last) = self.spans.last_mut() {
if last.validity == validity
&& (validity == INVALID || last.start_line_num + last.n == start_line_num)
{
last.n += n;
return;
}
}
self.spans.push(Span { n, start_line_num, validity });
}
}
pub fn set_dirty(&mut self, dirty: bool) {
self.dirty = dirty;
}
}
impl LineCacheShadow {
pub fn edit(&mut self, start: usize, end: usize, replace: usize) {
let mut b = Builder::new();
let mut line_num = 0;
let mut i = 0;
while i < self.spans.len() {
let span = &self.spans[i];
if line_num + span.n <= start {
b.add_span(span.n, span.start_line_num, span.validity);
line_num += span.n;
i += 1;
} else {
b.add_span(start - line_num, span.start_line_num, span.validity);
break;
}
}
b.add_span(replace, 0, INVALID);
for span in &self.spans[i..] {
if line_num + span.n > end {
let offset = end.saturating_sub(line_num);
b.add_span(span.n - offset, span.start_line_num + offset, span.validity);
}
line_num += span.n;
}
b.set_dirty(true);
*self = b.build();
}
pub fn partial_invalidate(&mut self, start: usize, end: usize, invalid: Validity) {
let mut clean = true;
let mut line_num = 0;
for span in &self.spans {
if start < line_num + span.n && end > line_num && (span.validity & invalid) != 0 {
clean = false;
break;
}
line_num += span.n;
}
if clean {
return;
}
let mut b = Builder::new();
let mut line_num = 0;
for span in &self.spans {
if start > line_num {
b.add_span(min(span.n, start - line_num), span.start_line_num, span.validity);
}
let invalid_start = max(start, line_num);
let invalid_end = min(end, line_num + span.n);
if invalid_end > invalid_start {
b.add_span(
invalid_end - invalid_start,
span.start_line_num + (invalid_start - line_num),
span.validity & !invalid,
);
}
if line_num + span.n > end {
let offset = end.saturating_sub(line_num);
b.add_span(span.n - offset, span.start_line_num + offset, span.validity);
}
line_num += span.n;
}
b.set_dirty(true);
*self = b.build();
}
pub fn needs_render(&self, plan: &RenderPlan) -> bool {
self.dirty
|| self
.iter_with_plan(plan)
.any(|seg| seg.tactic == RenderTactic::Render && seg.validity != ALL_VALID)
}
pub fn spans(&self) -> &[Span] {
&self.spans
}
pub fn iter_with_plan<'a>(&'a self, plan: &'a RenderPlan) -> PlanIterator<'a> {
PlanIterator {
lc_shadow: self,
plan,
shadow_ix: 0,
shadow_line_num: 0,
plan_ix: 0,
plan_line_num: 0,
}
}
}
impl Default for LineCacheShadow {
fn default() -> LineCacheShadow {
Builder::new().build()
}
}
impl<'a> Iterator for PlanIterator<'a> {
type Item = PlanSegment;
fn next(&mut self) -> Option<PlanSegment> {
if self.shadow_ix == self.lc_shadow.spans.len() || self.plan_ix == self.plan.spans.len() {
return None;
}
let shadow_span = &self.lc_shadow.spans[self.shadow_ix];
let plan_span = &self.plan.spans[self.plan_ix];
let start = max(self.shadow_line_num, self.plan_line_num);
let end = min(self.shadow_line_num + shadow_span.n, self.plan_line_num + plan_span.0);
let result = PlanSegment {
our_line_num: start,
their_line_num: shadow_span.start_line_num + (start - self.shadow_line_num),
n: end - start,
validity: shadow_span.validity,
tactic: plan_span.1,
};
if end == self.shadow_line_num + shadow_span.n {
self.shadow_line_num = end;
self.shadow_ix += 1;
}
if end == self.plan_line_num + plan_span.0 {
self.plan_line_num = end;
self.plan_ix += 1;
}
Some(result)
}
}
impl RenderPlan {
/// This function implements the policy of what to discard, what to preserve, and
/// what to render.
pub fn create(total_height: usize, first_line: usize, height: usize) -> RenderPlan {
let mut spans = Vec::new();
let mut last = 0;
let first_line = min(first_line, total_height);
if first_line > PRESERVE_EXTENT {
last = first_line - PRESERVE_EXTENT;
spans.push((last, RenderTactic::Discard));
}
if first_line > SCROLL_SLOP {
let n = first_line - SCROLL_SLOP - last;
spans.push((n, RenderTactic::Preserve));
last += n;
}
let render_end = min(first_line + height + SCROLL_SLOP, total_height);
spans.push((render_end - last, RenderTactic::Render));
last = render_end;
let preserve_end = min(first_line + height + PRESERVE_EXTENT, total_height);
if preserve_end > last {
spans.push((preserve_end - last, RenderTactic::Preserve));
last = preserve_end;
}
if total_height > last {
spans.push((total_height - last, RenderTactic::Discard));
}
RenderPlan { spans }
}
/// Upgrade a range of lines to the "Render" tactic.
pub fn request_lines(&mut self, start: usize, end: usize) {
let mut spans: Vec<(usize, RenderTactic)> = Vec::new();
let mut i = 0;
let mut line_num = 0;
while i < self.spans.len() {
let span = &self.spans[i];
if line_num + span.0 <= start {
spans.push(*span);
line_num += span.0;
i += 1;
} else {
if line_num < start {
spans.push((start - line_num, span.1));
}
break;
}
}
spans.push((end - start, RenderTactic::Render));
for span in &self.spans[i..] {
if line_num + span.0 > end {
let offset = end.saturating_sub(line_num);
spans.push((span.0 - offset, span.1));
}
line_num += span.0;
}
self.spans = spans;
}
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let validity = match self.validity {
TEXT_VALID => "text",
ALL_VALID => "all",
_other => "mixed",
};
if self.validity == INVALID {
write!(f, "({} invalid)", self.n)?;
} else {
write!(f, "({}: {}, {})", self.start_line_num, self.n, validity)?;
}
Ok(())
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/event_context.rs | rust/core-lib/src/event_context.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A container for the state relevant to a single event.
use std::cell::RefCell;
use std::iter;
use std::ops::Range;
use std::path::Path;
use std::time::{Duration, Instant};
use serde_json::{self, Value};
use xi_rope::{Cursor, Interval, LinesMetric, Rope, RopeDelta};
use xi_rpc::{Error as RpcError, RemoteError};
use xi_trace::trace_block;
use crate::plugins::rpc::{
ClientPluginInfo, Hover, PluginBufferInfo, PluginNotification, PluginRequest, PluginUpdate,
};
use crate::rpc::{EditNotification, EditRequest, LineRange, Position as ClientPosition};
use crate::client::Client;
use crate::config::{BufferItems, Table};
use crate::edit_types::{EventDomain, SpecialEvent};
use crate::editor::Editor;
use crate::file::FileInfo;
use crate::line_offset::LineOffset;
use crate::plugins::Plugin;
use crate::recorder::Recorder;
use crate::selection::InsertDrift;
use crate::styles::ThemeStyleMap;
use crate::syntax::LanguageId;
use crate::tabs::{
BufferId, PluginId, ViewId, FIND_VIEW_IDLE_MASK, RENDER_VIEW_IDLE_MASK, REWRAP_VIEW_IDLE_MASK,
};
use crate::view::View;
use crate::width_cache::WidthCache;
use crate::WeakXiCore;
// Maximum returned result from plugin get_data RPC.
pub const MAX_SIZE_LIMIT: usize = 1024 * 1024;
//TODO: tune this. a few ms can make a big difference. We may in the future
//want to make this tuneable at runtime, or to be configured by the client.
/// The render delay after an edit occurs; plugin updates received in this
/// window will be sent to the view along with the edit.
const RENDER_DELAY: Duration = Duration::from_millis(2);
/// A collection of all the state relevant for handling a particular event.
///
/// This is created dynamically for each event that arrives to the core,
/// such as a user-initiated edit or style updates from a plugin.
pub struct EventContext<'a> {
pub(crate) view_id: ViewId,
pub(crate) buffer_id: BufferId,
pub(crate) editor: &'a RefCell<Editor>,
pub(crate) info: Option<&'a FileInfo>,
pub(crate) config: &'a BufferItems,
pub(crate) recorder: &'a RefCell<Recorder>,
pub(crate) language: LanguageId,
pub(crate) view: &'a RefCell<View>,
pub(crate) siblings: Vec<&'a RefCell<View>>,
pub(crate) plugins: Vec<&'a Plugin>,
pub(crate) client: &'a Client,
pub(crate) style_map: &'a RefCell<ThemeStyleMap>,
pub(crate) width_cache: &'a RefCell<WidthCache>,
pub(crate) kill_ring: &'a RefCell<Rope>,
pub(crate) weak_core: &'a WeakXiCore,
}
impl<'a> EventContext<'a> {
/// Executes a closure with mutable references to the editor and the view,
/// common in edit actions that modify the text.
pub(crate) fn with_editor<R, F>(&mut self, f: F) -> R
where
F: FnOnce(&mut Editor, &mut View, &mut Rope, &BufferItems) -> R,
{
let mut editor = self.editor.borrow_mut();
let mut view = self.view.borrow_mut();
let mut kill_ring = self.kill_ring.borrow_mut();
f(&mut editor, &mut view, &mut kill_ring, self.config)
}
/// Executes a closure with a mutable reference to the view and a reference
/// to the current text. This is common to most edits that just modify
/// selection or viewport state.
fn with_view<R, F>(&mut self, f: F) -> R
where
F: FnOnce(&mut View, &Rope) -> R,
{
let editor = self.editor.borrow();
let mut view = self.view.borrow_mut();
f(&mut view, editor.get_buffer())
}
fn with_each_plugin<F: FnMut(&&Plugin)>(&self, f: F) {
self.plugins.iter().for_each(f)
}
pub(crate) fn do_edit(&mut self, cmd: EditNotification) {
let event: EventDomain = cmd.into();
{
// Handle recording-- clone every non-toggle and play event into the recording buffer
let mut recorder = self.recorder.borrow_mut();
match (recorder.is_recording(), &event) {
(_, EventDomain::Special(SpecialEvent::ToggleRecording(recording_name))) => {
recorder.toggle_recording(recording_name.clone());
}
// Don't save special events
(true, EventDomain::Special(_)) => {
warn!("Special events cannot be recorded-- ignoring event {:?}", event)
}
(true, event) => recorder.record(event.clone()),
_ => {}
}
}
self.dispatch_event(event);
self.after_edit("core");
self.render_if_needed();
}
fn dispatch_event(&mut self, event: EventDomain) {
use self::EventDomain as E;
match event {
E::View(cmd) => {
self.with_view(|view, text| view.do_edit(text, cmd));
self.editor.borrow_mut().update_edit_type();
if self.with_view(|v, t| v.needs_wrap_in_visible_region(t)) {
self.rewrap();
}
if self.with_view(|v, _| v.find_in_progress()) {
self.do_incremental_find();
}
}
E::Buffer(cmd) => {
self.with_editor(|ed, view, k_ring, conf| ed.do_edit(view, k_ring, conf, cmd))
}
E::Special(cmd) => self.do_special(cmd),
}
}
fn do_special(&mut self, cmd: SpecialEvent) {
match cmd {
SpecialEvent::Resize(size) => {
self.with_view(|view, _| view.set_size(size));
if self.config.word_wrap {
self.update_wrap_settings(false);
}
}
SpecialEvent::DebugRewrap | SpecialEvent::DebugWrapWidth => {
warn!("debug wrapping methods are removed, use the config system")
}
SpecialEvent::DebugPrintSpans => self.with_editor(|ed, view, _, _| {
let sel = view.sel_regions().last().unwrap();
let iv = Interval::new(sel.min(), sel.max());
ed.get_layers().debug_print_spans(iv);
}),
SpecialEvent::RequestLines(LineRange { first, last }) => {
self.do_request_lines(first as usize, last as usize)
}
SpecialEvent::RequestHover { request_id, position } => {
self.do_request_hover(request_id, position)
}
SpecialEvent::DebugToggleComment => self.do_debug_toggle_comment(),
SpecialEvent::Reindent => self.do_reindent(),
SpecialEvent::ToggleRecording(_) => {}
SpecialEvent::PlayRecording(recording_name) => {
let recorder = self.recorder.borrow();
let starting_revision = self.editor.borrow_mut().get_head_rev_token();
// Don't group with the previous action
self.editor.borrow_mut().update_edit_type();
self.editor.borrow_mut().calculate_undo_group();
// No matter what, our entire block must belong to the same undo group
self.editor.borrow_mut().set_force_undo_group(true);
recorder.play(&recording_name, |event| {
self.dispatch_event(event.clone());
let mut editor = self.editor.borrow_mut();
let (delta, last_text, drift) = match editor.commit_delta() {
Some(edit_info) => edit_info,
None => return,
};
self.update_views(&editor, &delta, &last_text, drift);
});
self.editor.borrow_mut().set_force_undo_group(false);
// The action that follows the block must belong to a separate undo group
self.editor.borrow_mut().update_edit_type();
let delta = self.editor.borrow_mut().delta_rev_head(starting_revision).unwrap();
self.update_plugins(&mut self.editor.borrow_mut(), delta, "core");
}
SpecialEvent::ClearRecording(recording_name) => {
let mut recorder = self.recorder.borrow_mut();
recorder.clear(&recording_name);
}
}
}
pub(crate) fn do_edit_sync(&mut self, cmd: EditRequest) -> Result<Value, RemoteError> {
use self::EditRequest::*;
let result = match cmd {
Cut => Ok(self.with_editor(|ed, view, _, _| ed.do_cut(view))),
Copy => Ok(self.with_editor(|ed, view, _, _| ed.do_copy(view))),
};
self.after_edit("core");
self.render_if_needed();
result
}
pub(crate) fn do_plugin_cmd(&mut self, plugin: PluginId, cmd: PluginNotification) {
use self::PluginNotification::*;
match cmd {
AddScopes { scopes } => {
let mut ed = self.editor.borrow_mut();
let style_map = self.style_map.borrow();
ed.get_layers_mut().add_scopes(plugin, scopes, &style_map);
}
UpdateSpans { start, len, spans, rev } => self.with_editor(|ed, view, _, _| {
ed.update_spans(view, plugin, start, len, spans, rev)
}),
Edit { edit } => self.with_editor(|ed, _, _, _| ed.apply_plugin_edit(edit)),
Alert { msg } => self.client.alert(&msg),
AddStatusItem { key, value, alignment } => {
let plugin_name = &self.plugins.iter().find(|p| p.id == plugin).unwrap().name;
self.client.add_status_item(self.view_id, plugin_name, &key, &value, &alignment);
}
UpdateStatusItem { key, value } => {
self.client.update_status_item(self.view_id, &key, &value)
}
UpdateAnnotations { start, len, spans, annotation_type, rev } => {
self.with_editor(|ed, view, _, _| {
ed.update_annotations(view, plugin, start, len, spans, annotation_type, rev)
})
}
RemoveStatusItem { key } => self.client.remove_status_item(self.view_id, &key),
ShowHover { request_id, result } => self.do_show_hover(request_id, result),
};
self.after_edit(&plugin.to_string());
self.render_if_needed();
}
pub(crate) fn do_plugin_cmd_sync(&mut self, _plugin: PluginId, cmd: PluginRequest) -> Value {
use self::PluginRequest::*;
match cmd {
LineCount => json!(self.editor.borrow().plugin_n_lines()),
GetData { start, unit, max_size, rev } => {
json!(self.editor.borrow().plugin_get_data(start, unit, max_size, rev))
}
GetSelections => json!("not implemented"),
}
}
/// Commits any changes to the buffer, updating views and plugins as needed.
/// This only updates internal state; it does not update the client.
fn after_edit(&mut self, author: &str) {
let _t = trace_block("EventContext::after_edit", &["core"]);
let edit_info = self.editor.borrow_mut().commit_delta();
let (delta, last_text, drift) = match edit_info {
Some(edit_info) => edit_info,
None => return,
};
self.update_views(&self.editor.borrow(), &delta, &last_text, drift);
self.update_plugins(&mut self.editor.borrow_mut(), delta, author);
//if we have no plugins we always render immediately.
if !self.plugins.is_empty() {
let mut view = self.view.borrow_mut();
if !view.has_pending_render() {
let timeout = Instant::now() + RENDER_DELAY;
let view_id: usize = self.view_id.into();
let token = RENDER_VIEW_IDLE_MASK | view_id;
self.client.schedule_timer(timeout, token);
view.set_has_pending_render(true);
}
}
}
fn update_views(&self, ed: &Editor, delta: &RopeDelta, last_text: &Rope, drift: InsertDrift) {
let mut width_cache = self.width_cache.borrow_mut();
let iter_views = iter::once(&self.view).chain(self.siblings.iter());
iter_views.for_each(|view| {
view.borrow_mut().after_edit(
ed.get_buffer(),
last_text,
delta,
self.client,
&mut width_cache,
drift,
)
});
}
fn update_plugins(&self, ed: &mut Editor, delta: RopeDelta, author: &str) {
let new_len = delta.new_document_len();
let nb_lines = ed.get_buffer().measure::<LinesMetric>() + 1;
// don't send the actual delta if it is too large, by some heuristic
let approx_size = delta.inserts_len() + (delta.els.len() * 10);
let delta = if approx_size > MAX_SIZE_LIMIT { None } else { Some(delta) };
let undo_group = ed.get_active_undo_group();
//TODO: we want to just put EditType on the wire, but don't want
//to update the plugin lib quite yet.
let v: Value = serde_json::to_value(&ed.get_edit_type()).unwrap();
let edit_type_str = v.as_str().unwrap().to_string();
let update = PluginUpdate::new(
self.view_id,
ed.get_head_rev_token(),
delta,
new_len,
nb_lines,
Some(undo_group),
edit_type_str,
author.into(),
);
// we always increment and decrement regardless of whether we're
// sending plugins, to ensure that GC runs.
ed.increment_revs_in_flight();
self.plugins.iter().for_each(|plugin| {
ed.increment_revs_in_flight();
let weak_core = self.weak_core.clone();
let id = plugin.id;
let view_id = self.view_id;
plugin.update(&update, move |resp| {
weak_core.handle_plugin_update(id, view_id, resp);
});
});
ed.dec_revs_in_flight();
ed.update_edit_type();
}
/// Renders the view, if a render has not already been scheduled.
pub(crate) fn render_if_needed(&mut self) {
let needed = !self.view.borrow().has_pending_render();
if needed {
self.render()
}
}
pub(crate) fn _finish_delayed_render(&mut self) {
self.render();
self.view.borrow_mut().set_has_pending_render(false);
}
/// Flushes any changes in the views out to the frontend.
fn render(&mut self) {
let _t = trace_block("EventContext::render", &["core"]);
let ed = self.editor.borrow();
//TODO: render other views
self.view.borrow_mut().render_if_dirty(
ed.get_buffer(),
self.client,
self.style_map,
ed.get_layers().get_merged(),
ed.is_pristine(),
)
}
}
/// Helpers related to specific commands.
///
/// Certain events and actions don't generalize well; handling these
/// requires access to particular combinations of state. We isolate such
/// special cases here.
impl<'a> EventContext<'a> {
pub(crate) fn view_init(&mut self) {
let wrap_width = self.config.wrap_width;
let word_wrap = self.config.word_wrap;
self.with_view(|view, text| view.update_wrap_settings(text, wrap_width, word_wrap));
}
pub(crate) fn finish_init(&mut self, config: &Table) {
if !self.plugins.is_empty() {
let info = self.plugin_info();
self.plugins.iter().for_each(|plugin| {
plugin.new_buffer(&info);
self.plugin_started(plugin);
});
}
let available_plugins = self
.plugins
.iter()
.map(|plugin| ClientPluginInfo { name: plugin.name.clone(), running: true })
.collect::<Vec<_>>();
self.client.available_plugins(self.view_id, &available_plugins);
self.client.config_changed(self.view_id, config);
self.client.language_changed(self.view_id, &self.language);
// Rewrap and request a render.
// This is largely similar to update_wrap_settings(), the only difference
// being that the view is expected to be already initialized.
self.rewrap();
if self.view.borrow().needs_more_wrap() {
self.schedule_rewrap();
}
self.with_view(|view, text| view.set_dirty(text));
self.render()
}
pub(crate) fn after_save(&mut self, path: &Path) {
// notify plugins
self.plugins.iter().for_each(|plugin| plugin.did_save(self.view_id, path));
self.editor.borrow_mut().set_pristine();
self.with_view(|view, text| view.set_dirty(text));
self.render()
}
/// Returns `true` if this was the last view
pub(crate) fn close_view(&self) -> bool {
// we probably want to notify plugins _before_ we close the view
// TODO: determine what plugins we're stopping
self.plugins.iter().for_each(|plug| plug.close_view(self.view_id));
self.siblings.is_empty()
}
pub(crate) fn config_changed(&mut self, changes: &Table) {
if changes.contains_key("wrap_width") || changes.contains_key("word_wrap") {
// FIXME: if switching from measurement-based widths to columnar widths,
// we need to reset the cache, since we're using different coordinate spaces
// for the same IDs. The long-term solution would be to include font
// information in the width cache, and then use real width even in the column
// case, getting the unit width for a typeface and multiplying that by
// a string's unicode width.
if changes.contains_key("word_wrap") {
debug!("clearing {} items from width cache", self.width_cache.borrow().len());
self.width_cache.replace(WidthCache::new());
}
self.update_wrap_settings(true);
}
self.client.config_changed(self.view_id, changes);
self.plugins.iter().for_each(|plug| plug.config_changed(self.view_id, changes));
self.render()
}
pub(crate) fn language_changed(&mut self, new_language_id: &LanguageId) {
self.language = new_language_id.clone();
self.client.language_changed(self.view_id, new_language_id);
self.plugins.iter().for_each(|plug| plug.language_changed(self.view_id, new_language_id));
}
pub(crate) fn reload(&mut self, text: Rope) {
self.with_editor(|ed, _, _, _| ed.reload(text));
self.after_edit("core");
self.render();
}
pub(crate) fn plugin_info(&mut self) -> PluginBufferInfo {
let ed = self.editor.borrow();
let nb_lines = ed.get_buffer().measure::<LinesMetric>() + 1;
let views: Vec<ViewId> = iter::once(&self.view)
.chain(self.siblings.iter())
.map(|v| v.borrow().get_view_id())
.collect();
let changes = serde_json::to_value(self.config).unwrap();
let path = self.info.map(|info| info.path.to_owned());
PluginBufferInfo::new(
self.buffer_id,
&views,
ed.get_head_rev_token(),
ed.get_buffer().len(),
nb_lines,
path,
self.language.clone(),
changes.as_object().unwrap().to_owned(),
)
}
pub(crate) fn plugin_started(&self, plugin: &Plugin) {
self.client.plugin_started(self.view_id, &plugin.name)
}
pub(crate) fn plugin_stopped(&mut self, plugin: &Plugin) {
self.client.plugin_stopped(self.view_id, &plugin.name, 0);
let needs_render = self.with_editor(|ed, view, _, _| {
if ed.get_layers_mut().remove_layer(plugin.id).is_some() {
view.set_dirty(ed.get_buffer());
true
} else {
false
}
});
if needs_render {
self.render();
}
}
pub(crate) fn do_plugin_update(&mut self, update: Result<Value, RpcError>) {
match update.map(serde_json::from_value::<u64>) {
Ok(Ok(_)) => (),
Ok(Err(err)) => error!("plugin response json err: {:?}", err),
Err(err) => error!("plugin shutdown, do something {:?}", err),
}
self.editor.borrow_mut().dec_revs_in_flight();
}
/// Returns the text to be saved, appending a newline if necessary.
pub(crate) fn text_for_save(&mut self) -> Rope {
let editor = self.editor.borrow();
let mut rope = editor.get_buffer().clone();
let rope_len = rope.len();
if rope_len < 1 || !self.config.save_with_newline {
return rope;
}
let cursor = Cursor::new(&rope, rope.len());
let has_newline_at_eof = match cursor.get_leaf() {
Some((last_chunk, _)) => last_chunk.ends_with(&self.config.line_ending),
// The rope can't be empty, since we would have returned earlier if it was
None => unreachable!(),
};
if !has_newline_at_eof {
let line_ending = &self.config.line_ending;
rope.edit(rope_len.., line_ending);
}
rope
}
/// Called after anything changes that effects word wrap, such as the size of
/// the window or the user's wrap settings. `rewrap_immediately` should be `true`
/// except in the resize case; during live resize we want to delay recalculation
/// to avoid unnecessary work.
fn update_wrap_settings(&mut self, rewrap_immediately: bool) {
let wrap_width = self.config.wrap_width;
let word_wrap = self.config.word_wrap;
self.with_view(|view, text| view.update_wrap_settings(text, wrap_width, word_wrap));
if rewrap_immediately {
self.rewrap();
self.with_view(|view, text| view.set_dirty(text));
}
if self.view.borrow().needs_more_wrap() {
self.schedule_rewrap();
}
}
/// Tells the view to rewrap a batch of lines, if needed. This guarantees that
/// the currently visible region will be correctly wrapped; the caller should
/// check if additional wrapping is necessary and schedule that if so.
fn rewrap(&mut self) {
let mut view = self.view.borrow_mut();
let ed = self.editor.borrow();
let mut width_cache = self.width_cache.borrow_mut();
view.rewrap(ed.get_buffer(), &mut width_cache, self.client, ed.get_layers().get_merged());
}
/// Does incremental find.
pub(crate) fn do_incremental_find(&mut self) {
let _t = trace_block("EventContext::do_incremental_find", &["find"]);
self.find();
if self.view.borrow().find_in_progress() {
let ed = self.editor.borrow();
self.client.find_status(
self.view_id,
&json!(self.view.borrow().find_status(ed.get_buffer(), true)),
);
self.schedule_find();
}
self.render_if_needed();
}
fn schedule_find(&self) {
let view_id: usize = self.view_id.into();
let token = FIND_VIEW_IDLE_MASK | view_id;
self.client.schedule_idle(token);
}
/// Tells the view to execute find on a batch of lines, if needed.
fn find(&mut self) {
let mut view = self.view.borrow_mut();
let ed = self.editor.borrow();
view.do_find(ed.get_buffer());
}
/// Does a rewrap batch, and schedules follow-up work if needed.
pub(crate) fn do_rewrap_batch(&mut self) {
self.rewrap();
if self.view.borrow().needs_more_wrap() {
self.schedule_rewrap();
}
self.render_if_needed();
}
fn schedule_rewrap(&self) {
let view_id: usize = self.view_id.into();
let token = REWRAP_VIEW_IDLE_MASK | view_id;
self.client.schedule_idle(token);
}
fn do_request_lines(&mut self, first: usize, last: usize) {
let mut view = self.view.borrow_mut();
let ed = self.editor.borrow();
view.request_lines(
ed.get_buffer(),
self.client,
self.style_map,
ed.get_layers().get_merged(),
first,
last,
ed.is_pristine(),
)
}
fn selected_line_ranges(&mut self) -> Vec<(usize, usize)> {
let ed = self.editor.borrow();
let mut prev_range: Option<Range<usize>> = None;
let mut line_ranges = Vec::new();
// we send selection state to syntect in the form of a vec of line ranges,
// so we combine overlapping selections to get the minimum set of ranges.
for region in self.view.borrow().sel_regions().iter() {
let start = ed.get_buffer().line_of_offset(region.min());
let end = ed.get_buffer().line_of_offset(region.max()) + 1;
let line_range = start..end;
let prev = prev_range.take();
match (prev, line_range) {
(None, range) => prev_range = Some(range),
(Some(ref prev), ref range) if range.start <= prev.end => {
let combined =
Range { start: prev.start.min(range.start), end: prev.end.max(range.end) };
prev_range = Some(combined);
}
(Some(prev), range) => {
line_ranges.push((prev.start, prev.end));
prev_range = Some(range);
}
}
}
if let Some(prev) = prev_range {
line_ranges.push((prev.start, prev.end));
}
line_ranges
}
fn do_reindent(&mut self) {
let line_ranges = self.selected_line_ranges();
// this is handled by syntect only; this is definitely not the long-term solution.
if let Some(plug) = self.plugins.iter().find(|p| p.name == "xi-syntect-plugin") {
plug.dispatch_command(self.view_id, "reindent", &json!(line_ranges));
}
}
fn do_debug_toggle_comment(&mut self) {
let line_ranges = self.selected_line_ranges();
// this is handled by syntect only; this is definitely not the long-term solution.
if let Some(plug) = self.plugins.iter().find(|p| p.name == "xi-syntect-plugin") {
plug.dispatch_command(self.view_id, "toggle_comment", &json!(line_ranges));
}
}
fn do_request_hover(&mut self, request_id: usize, position: Option<ClientPosition>) {
if let Some(position) = self.get_resolved_position(position) {
self.with_each_plugin(|p| p.get_hover(self.view_id, request_id, position))
}
}
fn do_show_hover(&mut self, request_id: usize, hover: Result<Hover, RemoteError>) {
match hover {
Ok(hover) => {
// TODO: Get Range from hover here and use it to highlight text
self.client.show_hover(self.view_id, request_id, hover.content)
}
Err(err) => warn!("Hover Response from Client Error {:?}", err),
}
}
/// Gives the requested position in UTF-8 offset format to be sent to plugin
/// If position is `None`, it tries to get the current Caret Position and use
/// that instead
fn get_resolved_position(&mut self, position: Option<ClientPosition>) -> Option<usize> {
position
.map(|p| self.with_view(|view, text| view.line_col_to_offset(text, p.line, p.column)))
.or_else(|| self.view.borrow().get_caret_offset())
}
}
#[cfg(test)]
#[rustfmt::skip]
mod tests {
use super::*;
use crate::config::ConfigManager;
use crate::core::dummy_weak_core;
use crate::tabs::BufferId;
use xi_rpc::test_utils::DummyPeer;
struct ContextHarness {
view: RefCell<View>,
editor: RefCell<Editor>,
client: Client,
core_ref: WeakXiCore,
kill_ring: RefCell<Rope>,
style_map: RefCell<ThemeStyleMap>,
width_cache: RefCell<WidthCache>,
config_manager: ConfigManager,
recorder: RefCell<Recorder>,
}
impl ContextHarness {
fn new<S: AsRef<str>>(s: S) -> Self {
// we could make this take a config, which would let us test
// behaviour with different config settings?
let view_id = ViewId(1);
let buffer_id = BufferId(2);
let mut config_manager = ConfigManager::new(None, None);
let config = config_manager.add_buffer(buffer_id, None);
let view = RefCell::new(View::new(view_id, buffer_id));
let editor = RefCell::new(Editor::with_text(s));
let client = Client::new(Box::new(DummyPeer));
let core_ref = dummy_weak_core();
let kill_ring = RefCell::new(Rope::from(""));
let style_map = RefCell::new(ThemeStyleMap::new(None));
let width_cache = RefCell::new(WidthCache::new());
let recorder = RefCell::new(Recorder::new());
let harness = ContextHarness { view, editor, client, core_ref, kill_ring,
style_map, width_cache, config_manager, recorder };
harness.make_context().view_init();
harness.make_context().finish_init(&config);
harness
}
/// Renders the text and selections. cursors are represented with
/// the pipe '|', and non-caret regions are represented by \[braces\].
fn debug_render(&self) -> String {
let b = self.editor.borrow();
let mut text: String = b.get_buffer().into();
let v = self.view.borrow();
for sel in v.sel_regions().iter().rev() {
if sel.end == sel.start {
text.insert(sel.end, '|');
} else if sel.end > sel.start {
text.insert_str(sel.end, "|]");
text.insert(sel.start, '[');
} else {
text.insert(sel.start, ']');
text.insert_str(sel.end, "[|");
}
}
text
}
fn make_context(&self) -> EventContext<'_> {
let view_id = ViewId(1);
let buffer_id = self.view.borrow().get_buffer_id();
let config = self.config_manager.get_buffer_config(buffer_id);
let language = self.config_manager.get_buffer_language(buffer_id);
EventContext {
view_id,
buffer_id,
view: &self.view,
editor: &self.editor,
config: &config.items,
language,
info: None,
siblings: Vec::new(),
plugins: Vec::new(),
recorder: &self.recorder,
client: &self.client,
kill_ring: &self.kill_ring,
style_map: &self.style_map,
width_cache: &self.width_cache,
weak_core: &self.core_ref,
}
}
}
#[test]
fn smoke_test() {
let harness = ContextHarness::new("");
let mut ctx = harness.make_context();
ctx.do_edit(EditNotification::Insert { chars: "hello".into() });
ctx.do_edit(EditNotification::Insert { chars: " ".into() });
ctx.do_edit(EditNotification::Insert { chars: "world".into() });
ctx.do_edit(EditNotification::Insert { chars: "!".into() });
assert_eq!(harness.debug_render(),"hello world!|");
ctx.do_edit(EditNotification::MoveWordLeft);
ctx.do_edit(EditNotification::InsertNewline);
assert_eq!(harness.debug_render(),"hello \n|world!");
ctx.do_edit(EditNotification::MoveWordRightAndModifySelection);
assert_eq!(harness.debug_render(), "hello \n[world|]!");
ctx.do_edit(EditNotification::Insert { chars: "friends".into() });
assert_eq!(harness.debug_render(), "hello \nfriends|!");
}
#[test]
fn test_gestures() {
use crate::rpc::GestureType::*;
let initial_text = "\
this is a string\n\
that has three\n\
lines.";
let harness = ContextHarness::new(initial_text);
let mut ctx = harness.make_context();
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/view.rs | rust/core-lib/src/view.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::cell::RefCell;
use std::cmp::{max, min};
use std::iter;
use std::ops::Range;
use serde_json::Value;
use crate::annotations::{AnnotationStore, Annotations, ToAnnotation};
use crate::client::{Client, Update, UpdateOp};
use crate::edit_types::ViewEvent;
use crate::find::{Find, FindStatus};
use crate::line_cache_shadow::{self, LineCacheShadow, RenderPlan, RenderTactic};
use crate::line_offset::LineOffset;
use crate::linewrap::{InvalLines, Lines, VisualLine, WrapWidth};
use crate::movement::{region_movement, selection_movement, Movement};
use crate::plugins::PluginId;
use crate::rpc::{FindQuery, GestureType, MouseAction, SelectionGranularity, SelectionModifier};
use crate::selection::{Affinity, InsertDrift, SelRegion, Selection};
use crate::styles::{Style, ThemeStyleMap};
use crate::tabs::{BufferId, Counter, ViewId};
use crate::width_cache::WidthCache;
use crate::word_boundaries::WordCursor;
use xi_rope::spans::Spans;
use xi_rope::{Cursor, Interval, LinesMetric, Rope, RopeDelta};
use xi_trace::trace_block;
type StyleMap = RefCell<ThemeStyleMap>;
/// A flag used to indicate when legacy actions should modify selections
const FLAG_SELECT: u64 = 2;
/// Size of batches as number of bytes used during incremental find.
const FIND_BATCH_SIZE: usize = 500000;
/// A view to a buffer. It is the buffer plus additional information
/// like line breaks and selection state.
pub struct View {
view_id: ViewId,
buffer_id: BufferId,
/// Tracks whether this view has been scheduled to render.
/// We attempt to reduce duplicate renders by setting a small timeout
/// after an edit is applied, to allow batching with any plugin updates.
pending_render: bool,
size: Size,
/// The selection state for this view. Invariant: non-empty.
selection: Selection,
drag_state: Option<DragState>,
/// vertical scroll position
first_line: usize,
/// height of visible portion
height: usize,
lines: Lines,
/// Front end's line cache state for this view. See the `LineCacheShadow`
/// description for the invariant.
lc_shadow: LineCacheShadow,
/// New offset to be scrolled into position after an edit.
scroll_to: Option<usize>,
/// The state for finding text for this view.
/// Each instance represents a separate search query.
find: Vec<Find>,
/// Tracks the IDs for additional search queries in find.
find_id_counter: Counter,
/// Tracks whether there has been changes in find results or find parameters.
/// This is used to determined whether FindStatus should be sent to the frontend.
find_changed: FindStatusChange,
/// Tracks the progress of incremental find.
find_progress: FindProgress,
/// Tracks whether find highlights should be rendered.
/// Highlights are only rendered when search dialog is open.
highlight_find: bool,
/// The state for replacing matches for this view.
replace: Option<Replace>,
/// Tracks whether the replacement string or replace parameters changed.
replace_changed: bool,
/// Annotations provided by plugins.
annotations: AnnotationStore,
}
/// Indicates what changed in the find state.
#[derive(PartialEq, Debug)]
enum FindStatusChange {
/// None of the find parameters or number of matches changed.
None,
/// Find parameters and number of matches changed.
All,
/// Only number of matches changed
Matches,
}
/// Indicates what changed in the find state.
#[derive(PartialEq, Debug, Clone)]
enum FindProgress {
/// Incremental find is done/not running.
Ready,
/// The find process just started.
Started,
/// Incremental find is in progress. Keeps tracked of already searched range.
InProgress(Range<usize>),
}
/// Contains replacement string and replace options.
#[derive(Debug, Default, PartialEq, Serialize, Deserialize, Clone)]
pub struct Replace {
/// Replacement string.
pub chars: String,
pub preserve_case: bool,
}
/// A size, in pixel units (not display pixels).
#[derive(Debug, Default, PartialEq, Serialize, Deserialize, Clone)]
pub struct Size {
pub width: f64,
pub height: f64,
}
/// State required to resolve a drag gesture into a selection.
struct DragState {
/// All the selection regions other than the one being dragged.
base_sel: Selection,
/// Start of the region selected when drag was started (region is
/// assumed to be forward).
min: usize,
/// End of the region selected when drag was started.
max: usize,
granularity: SelectionGranularity,
}
impl View {
pub fn new(view_id: ViewId, buffer_id: BufferId) -> View {
View {
view_id,
buffer_id,
pending_render: false,
selection: SelRegion::caret(0).into(),
scroll_to: Some(0),
size: Size::default(),
drag_state: None,
first_line: 0,
height: 10,
lines: Lines::default(),
lc_shadow: LineCacheShadow::default(),
find: Vec::new(),
find_id_counter: Counter::default(),
find_changed: FindStatusChange::None,
find_progress: FindProgress::Ready,
highlight_find: false,
replace: None,
replace_changed: false,
annotations: AnnotationStore::new(),
}
}
pub(crate) fn get_buffer_id(&self) -> BufferId {
self.buffer_id
}
pub(crate) fn get_view_id(&self) -> ViewId {
self.view_id
}
pub(crate) fn get_lines(&self) -> &Lines {
&self.lines
}
pub(crate) fn get_replace(&self) -> Option<Replace> {
self.replace.clone()
}
pub(crate) fn set_has_pending_render(&mut self, pending: bool) {
self.pending_render = pending
}
pub(crate) fn has_pending_render(&self) -> bool {
self.pending_render
}
pub(crate) fn update_wrap_settings(&mut self, text: &Rope, wrap_cols: usize, word_wrap: bool) {
let wrap_width = match (word_wrap, wrap_cols) {
(true, _) => WrapWidth::Width(self.size.width),
(false, 0) => WrapWidth::None,
(false, cols) => WrapWidth::Bytes(cols),
};
self.lines.set_wrap_width(text, wrap_width);
}
pub(crate) fn needs_more_wrap(&self) -> bool {
!self.lines.is_converged()
}
pub(crate) fn needs_wrap_in_visible_region(&self, text: &Rope) -> bool {
if self.lines.is_converged() {
false
} else {
let visible_region = self.interval_of_visible_region(text);
self.lines.interval_needs_wrap(visible_region)
}
}
pub(crate) fn find_in_progress(&self) -> bool {
matches!(self.find_progress, FindProgress::InProgress(_) | FindProgress::Started)
}
pub(crate) fn do_edit(&mut self, text: &Rope, cmd: ViewEvent) {
use self::ViewEvent::*;
match cmd {
Move(movement) => self.do_move(text, movement, false),
ModifySelection(movement) => self.do_move(text, movement, true),
SelectAll => self.select_all(text),
Scroll(range) => self.set_scroll(range.first, range.last),
AddSelectionAbove => self.add_selection_by_movement(text, Movement::UpExactPosition),
AddSelectionBelow => self.add_selection_by_movement(text, Movement::DownExactPosition),
Gesture { line, col, ty } => self.do_gesture(text, line, col, ty),
GotoLine { line } => self.goto_line(text, line),
Find { chars, case_sensitive, regex, whole_words } => {
let id = self.find.first().map(|q| q.id());
let query_changes = FindQuery { id, chars, case_sensitive, regex, whole_words };
self.set_find(text, [query_changes].to_vec())
}
MultiFind { queries } => self.set_find(text, queries),
FindNext { wrap_around, allow_same, modify_selection } => {
self.do_find_next(text, false, wrap_around, allow_same, &modify_selection)
}
FindPrevious { wrap_around, allow_same, modify_selection } => {
self.do_find_next(text, true, wrap_around, allow_same, &modify_selection)
}
FindAll => self.do_find_all(text),
Click(MouseAction { line, column, flags, click_count }) => {
// Deprecated (kept for client compatibility):
// should be removed in favor of do_gesture
warn!("Usage of click is deprecated; use do_gesture");
if (flags & FLAG_SELECT) != 0 {
self.do_gesture(
text,
line,
column,
GestureType::SelectExtend { granularity: SelectionGranularity::Point },
)
} else if click_count == Some(2) {
self.do_gesture(text, line, column, GestureType::WordSelect)
} else if click_count == Some(3) {
self.do_gesture(text, line, column, GestureType::LineSelect)
} else {
self.do_gesture(text, line, column, GestureType::PointSelect)
}
}
Drag(MouseAction { line, column, .. }) => {
warn!("Usage of drag is deprecated; use gesture instead");
self.do_gesture(text, line, column, GestureType::Drag)
}
CollapseSelections => self.collapse_selections(text),
HighlightFind { visible } => {
self.highlight_find = visible;
self.find_changed = FindStatusChange::All;
self.set_dirty(text);
}
SelectionForFind { case_sensitive } => self.do_selection_for_find(text, case_sensitive),
Replace { chars, preserve_case } => self.do_set_replace(chars, preserve_case),
SelectionForReplace => self.do_selection_for_replace(text),
SelectionIntoLines => self.do_split_selection_into_lines(text),
}
}
fn do_gesture(&mut self, text: &Rope, line: u64, col: u64, ty: GestureType) {
let line = line as usize;
let col = col as usize;
let offset = self.line_col_to_offset(text, line, col);
match ty {
GestureType::Select { granularity, multi } => {
self.select(text, offset, granularity, multi)
}
GestureType::SelectExtend { granularity } => {
self.extend_selection(text, offset, granularity)
}
GestureType::Drag => self.do_drag(text, offset, Affinity::default()),
_ => {
warn!("Deprecated gesture type sent to do_gesture method");
}
}
}
fn goto_line(&mut self, text: &Rope, line: u64) {
let offset = self.line_col_to_offset(text, line as usize, 0);
self.set_selection(text, SelRegion::caret(offset));
}
pub fn set_size(&mut self, size: Size) {
self.size = size;
}
pub fn set_scroll(&mut self, first: i64, last: i64) {
let first = max(first, 0) as usize;
let last = max(last, 0) as usize;
self.first_line = first;
self.height = last - first;
}
pub fn scroll_height(&self) -> usize {
self.height
}
fn scroll_to_cursor(&mut self, text: &Rope) {
let end = self.sel_regions().last().unwrap().end;
let line = self.line_of_offset(text, end);
if line < self.first_line {
self.first_line = line;
} else if self.first_line + self.height <= line {
self.first_line = line - (self.height - 1);
}
// We somewhat arbitrarily choose the last region for setting the old-style
// selection state, and for scrolling it into view if needed. This choice can
// likely be improved.
self.scroll_to = Some(end);
}
/// Removes any selection present at the given offset.
/// Returns true if a selection was removed, false otherwise.
pub fn deselect_at_offset(&mut self, text: &Rope, offset: usize) -> bool {
if !self.selection.regions_in_range(offset, offset).is_empty() {
let mut sel = self.selection.clone();
sel.delete_range(offset, offset, true);
if !sel.is_empty() {
self.drag_state = None;
self.set_selection_raw(text, sel);
return true;
}
}
false
}
/// Move the selection by the given movement. Return value is the offset of
/// a point that should be scrolled into view.
///
/// If `modify` is `true`, the selections are modified, otherwise the results
/// of individual region movements become carets.
pub fn do_move(&mut self, text: &Rope, movement: Movement, modify: bool) {
self.drag_state = None;
let new_sel =
selection_movement(movement, &self.selection, self, self.scroll_height(), text, modify);
self.set_selection(text, new_sel);
}
/// Set the selection to a new value.
pub fn set_selection<S: Into<Selection>>(&mut self, text: &Rope, sel: S) {
self.set_selection_raw(text, sel.into());
self.scroll_to_cursor(text);
}
/// Sets the selection to a new value, without invalidating.
fn set_selection_for_edit(&mut self, text: &Rope, sel: Selection) {
self.selection = sel;
self.scroll_to_cursor(text);
}
/// Sets the selection to a new value, invalidating the line cache as needed.
/// This function does not perform any scrolling.
fn set_selection_raw(&mut self, text: &Rope, sel: Selection) {
self.invalidate_selection(text);
self.selection = sel;
self.invalidate_selection(text);
}
/// Invalidate the current selection. Note that we could be even more
/// fine-grained in the case of multiple cursors, but we also want this
/// method to be fast even when the selection is large.
fn invalidate_selection(&mut self, text: &Rope) {
// TODO: refine for upstream (caret appears on prev line)
let first_line = self.line_of_offset(text, self.selection.first().unwrap().min());
let last_line = self.line_of_offset(text, self.selection.last().unwrap().max()) + 1;
let all_caret = self.selection.iter().all(|region| region.is_caret());
let invalid = if all_caret {
line_cache_shadow::CURSOR_VALID
} else {
line_cache_shadow::CURSOR_VALID | line_cache_shadow::STYLES_VALID
};
self.lc_shadow.partial_invalidate(first_line, last_line, invalid);
}
fn add_selection_by_movement(&mut self, text: &Rope, movement: Movement) {
let mut sel = Selection::new();
for ®ion in self.sel_regions() {
sel.add_region(region);
let new_region =
region_movement(movement, region, self, self.scroll_height(), text, false);
sel.add_region(new_region);
}
self.set_selection(text, sel);
}
// TODO: insert from keyboard or input method shouldn't break undo group,
/// Invalidates the styles of the given range (start and end are offsets within
/// the text).
pub fn invalidate_styles(&mut self, text: &Rope, start: usize, end: usize) {
let first_line = self.line_of_offset(text, start);
let (mut last_line, last_col) = self.offset_to_line_col(text, end);
last_line += if last_col > 0 { 1 } else { 0 };
self.lc_shadow.partial_invalidate(first_line, last_line, line_cache_shadow::STYLES_VALID);
}
pub fn update_annotations(
&mut self,
plugin: PluginId,
interval: Interval,
annotations: Annotations,
) {
self.annotations.update(plugin, interval, annotations)
}
/// Select entire buffer.
///
/// Note: unlike movement based selection, this does not scroll.
pub fn select_all(&mut self, text: &Rope) {
let selection = SelRegion::new(0, text.len()).into();
self.set_selection_raw(text, selection);
}
/// Finds the unit of text containing the given offset.
fn unit(&self, text: &Rope, offset: usize, granularity: SelectionGranularity) -> Interval {
match granularity {
SelectionGranularity::Point => Interval::new(offset, offset),
SelectionGranularity::Word => {
let mut word_cursor = WordCursor::new(text, offset);
let (start, end) = word_cursor.select_word();
Interval::new(start, end)
}
SelectionGranularity::Line => {
let (line, _) = self.offset_to_line_col(text, offset);
let (start, end) = self.lines.logical_line_range(text, line);
Interval::new(start, end)
}
}
}
/// Selects text with a certain granularity and supports multi_selection
fn select(
&mut self,
text: &Rope,
offset: usize,
granularity: SelectionGranularity,
multi: bool,
) {
// If multi-select is enabled, toggle existing regions
if multi
&& granularity == SelectionGranularity::Point
&& self.deselect_at_offset(text, offset)
{
return;
}
let region = self.unit(text, offset, granularity).into();
let base_sel = match multi {
true => self.selection.clone(),
false => Selection::new(),
};
let mut selection = base_sel.clone();
selection.add_region(region);
self.set_selection(text, selection);
self.drag_state =
Some(DragState { base_sel, min: region.start, max: region.end, granularity });
}
/// Extends an existing selection (eg. when the user performs SHIFT + click).
pub fn extend_selection(
&mut self,
text: &Rope,
offset: usize,
granularity: SelectionGranularity,
) {
if self.sel_regions().is_empty() {
return;
}
let (base_sel, last) = {
let mut base = Selection::new();
let (last, rest) = self.sel_regions().split_last().unwrap();
for ®ion in rest {
base.add_region(region);
}
(base, *last)
};
let mut sel = base_sel.clone();
self.drag_state =
Some(DragState { base_sel, min: last.start, max: last.start, granularity });
let start = (last.start, last.start);
let new_region = self.range_region(text, start, offset, granularity);
// TODO: small nit, merged region should be backward if end < start.
// This could be done by explicitly overriding, or by tweaking the
// merge logic.
sel.add_region(new_region);
self.set_selection(text, sel);
}
/// Splits current selections into lines.
fn do_split_selection_into_lines(&mut self, text: &Rope) {
let mut selection = Selection::new();
for region in self.selection.iter() {
if region.is_caret() {
selection.add_region(SelRegion::caret(region.max()));
} else {
let mut cursor = Cursor::new(text, region.min());
while cursor.pos() < region.max() {
let sel_start = cursor.pos();
let end_of_line = match cursor.next::<LinesMetric>() {
Some(end) if end >= region.max() => max(0, region.max() - 1),
Some(end) => max(0, end - 1),
None if cursor.pos() == text.len() => cursor.pos(),
_ => break,
};
selection.add_region(SelRegion::new(sel_start, end_of_line));
}
}
}
self.set_selection_raw(text, selection);
}
/// Does a drag gesture, setting the selection from a combination of the drag
/// state and new offset.
fn do_drag(&mut self, text: &Rope, offset: usize, affinity: Affinity) {
let new_sel = self.drag_state.as_ref().map(|drag_state| {
let mut sel = drag_state.base_sel.clone();
let start = (drag_state.min, drag_state.max);
let new_region = self.range_region(text, start, offset, drag_state.granularity);
sel.add_region(new_region.with_horiz(None).with_affinity(affinity));
sel
});
if let Some(sel) = new_sel {
self.set_selection(text, sel);
}
}
/// Creates a `SelRegion` for range select or drag operations.
pub fn range_region(
&self,
text: &Rope,
start: (usize, usize),
offset: usize,
granularity: SelectionGranularity,
) -> SelRegion {
let (min_start, max_start) = start;
let end = self.unit(text, offset, granularity);
let (min_end, max_end) = (end.start, end.end);
if offset >= min_start {
SelRegion::new(min_start, max_end)
} else {
SelRegion::new(max_start, min_end)
}
}
/// Returns the regions of the current selection.
pub fn sel_regions(&self) -> &[SelRegion] {
&self.selection
}
/// Collapse all selections in this view into a single caret
pub fn collapse_selections(&mut self, text: &Rope) {
let mut sel = self.selection.clone();
sel.collapse();
self.set_selection(text, sel);
}
/// Determines whether the offset is in any selection (counting carets and
/// selection edges).
pub fn is_point_in_selection(&self, offset: usize) -> bool {
!self.selection.regions_in_range(offset, offset).is_empty()
}
// Encode a single line with its styles and cursors in JSON.
// If "text" is not specified, don't add "text" to the output.
// If "style_spans" are not specified, don't add "styles" to the output.
fn encode_line(
&self,
client: &Client,
styles: &StyleMap,
line: VisualLine,
text: Option<&Rope>,
style_spans: Option<&Spans<Style>>,
last_pos: usize,
) -> Value {
let start_pos = line.interval.start;
let pos = line.interval.end;
let mut cursors = Vec::new();
let mut selections = Vec::new();
for region in self.selection.regions_in_range(start_pos, pos) {
// cursor
let c = region.end;
if (c > start_pos && c < pos)
|| (!region.is_upstream() && c == start_pos)
|| (region.is_upstream() && c == pos)
|| (c == pos && c == last_pos)
{
cursors.push(c - start_pos);
}
// selection with interior
let sel_start_ix = clamp(region.min(), start_pos, pos) - start_pos;
let sel_end_ix = clamp(region.max(), start_pos, pos) - start_pos;
if sel_end_ix > sel_start_ix {
selections.push((sel_start_ix, sel_end_ix));
}
}
let mut hls = Vec::new();
if self.highlight_find {
for find in &self.find {
let mut cur_hls = Vec::new();
for region in find.occurrences().regions_in_range(start_pos, pos) {
let sel_start_ix = clamp(region.min(), start_pos, pos) - start_pos;
let sel_end_ix = clamp(region.max(), start_pos, pos) - start_pos;
if sel_end_ix > sel_start_ix {
cur_hls.push((sel_start_ix, sel_end_ix));
}
}
hls.push(cur_hls);
}
}
let mut result = json!({});
if let Some(text) = text {
result["text"] = json!(text.slice_to_cow(start_pos..pos));
}
if let Some(style_spans) = style_spans {
result["styles"] = json!(self.encode_styles(
client,
styles,
start_pos,
pos,
&selections,
&hls,
style_spans
));
}
if !cursors.is_empty() {
result["cursor"] = json!(cursors);
}
if let Some(line_num) = line.line_num {
result["ln"] = json!(line_num);
}
result
}
pub fn encode_styles(
&self,
client: &Client,
styles: &StyleMap,
start: usize,
end: usize,
sel: &[(usize, usize)],
hls: &Vec<Vec<(usize, usize)>>,
style_spans: &Spans<Style>,
) -> Vec<isize> {
let mut encoded_styles = Vec::new();
assert!(start <= end, "{} {}", start, end);
let style_spans = style_spans.subseq(Interval::new(start, end));
let mut ix = 0;
// we add the special find highlights (1 to N) and selection (0) styles first.
// We add selection after find because we want it to be preferred if the
// same span exists in both sets (as when there is an active selection)
for (index, cur_find_hls) in hls.iter().enumerate() {
for &(sel_start, sel_end) in cur_find_hls {
encoded_styles.push((sel_start as isize) - ix);
encoded_styles.push(sel_end as isize - sel_start as isize);
encoded_styles.push(index as isize + 1);
ix = sel_end as isize;
}
}
for &(sel_start, sel_end) in sel {
encoded_styles.push((sel_start as isize) - ix);
encoded_styles.push(sel_end as isize - sel_start as isize);
encoded_styles.push(0);
ix = sel_end as isize;
}
for (iv, style) in style_spans.iter() {
let style_id = self.get_or_def_style_id(client, styles, style);
encoded_styles.push((iv.start() as isize) - ix);
encoded_styles.push(iv.end() as isize - iv.start() as isize);
encoded_styles.push(style_id as isize);
ix = iv.end() as isize;
}
encoded_styles
}
fn get_or_def_style_id(&self, client: &Client, style_map: &StyleMap, style: &Style) -> usize {
let mut style_map = style_map.borrow_mut();
if let Some(ix) = style_map.lookup(style) {
return ix;
}
let ix = style_map.add(style);
let style = style_map.merge_with_default(style);
client.def_style(&style.to_json(ix));
ix
}
fn send_update_for_plan(
&mut self,
text: &Rope,
client: &Client,
styles: &StyleMap,
style_spans: &Spans<Style>,
plan: &RenderPlan,
pristine: bool,
) {
// every time current visible range changes, annotations are sent to frontend
let start_off = self.offset_of_line(text, self.first_line);
let end_off = self.offset_of_line(text, self.first_line + self.height + 2);
let visible_range = Interval::new(start_off, end_off);
let selection_annotations =
self.selection.get_annotations(visible_range, self, text).to_json();
let find_annotations =
self.find.iter().map(|f| f.get_annotations(visible_range, self, text).to_json());
let plugin_annotations =
self.annotations.iter_range(self, text, visible_range).map(|a| a.to_json());
let annotations = iter::once(selection_annotations)
.chain(find_annotations)
.chain(plugin_annotations)
.collect::<Vec<_>>();
if !self.lc_shadow.needs_render(plan) {
let total_lines = self.line_of_offset(text, text.len()) + 1;
let update =
Update { ops: vec![UpdateOp::copy(total_lines, 1)], pristine, annotations };
client.update_view(self.view_id, &update);
return;
}
// send updated find status only if there have been changes
if self.find_changed != FindStatusChange::None {
let matches_only = self.find_changed == FindStatusChange::Matches;
client.find_status(self.view_id, &json!(self.find_status(text, matches_only)));
self.find_changed = FindStatusChange::None;
}
// send updated replace status if changed
if self.replace_changed {
if let Some(replace) = self.get_replace() {
client.replace_status(self.view_id, &json!(replace))
}
}
let mut b = line_cache_shadow::Builder::new();
let mut ops = Vec::new();
let mut line_num = 0; // tracks old line cache
for seg in self.lc_shadow.iter_with_plan(plan) {
match seg.tactic {
RenderTactic::Discard => {
ops.push(UpdateOp::invalidate(seg.n));
b.add_span(seg.n, 0, 0);
}
RenderTactic::Preserve | RenderTactic::Render => {
// Depending on the state of TEXT_VALID, STYLES_VALID and
// CURSOR_VALID, perform one of the following actions:
//
// - All the three are valid => send the "copy" op
// (+leading "skip" to catch up with "ln" to update);
//
// - Text and styles are valid, cursors are not => same,
// but send an "update" op instead of "copy" to move
// the cursors;
//
// - Text or styles are invalid:
// => send "invalidate" if RenderTactic is "Preserve";
// => send "skip"+"insert" (recreate the lines) if
// RenderTactic is "Render".
if (seg.validity & line_cache_shadow::TEXT_VALID) != 0
&& (seg.validity & line_cache_shadow::STYLES_VALID) != 0
{
let n_skip = seg.their_line_num - line_num;
if n_skip > 0 {
ops.push(UpdateOp::skip(n_skip));
}
let line_offset = self.offset_of_line(text, seg.our_line_num);
let logical_line = text.line_of_offset(line_offset);
if (seg.validity & line_cache_shadow::CURSOR_VALID) != 0 {
// ALL_VALID; copy lines as-is
ops.push(UpdateOp::copy(seg.n, logical_line + 1));
} else {
// !CURSOR_VALID; update cursors
let start_line = seg.our_line_num;
let encoded_lines = self
.lines
.iter_lines(text, start_line)
.take(seg.n)
.map(|l| {
self.encode_line(
client,
styles,
l,
/* text = */ None,
/* style_spans = */ None,
text.len(),
)
})
.collect::<Vec<_>>();
let logical_line_opt =
if logical_line == 0 { None } else { Some(logical_line + 1) };
ops.push(UpdateOp::update(encoded_lines, logical_line_opt));
}
b.add_span(seg.n, seg.our_line_num, seg.validity);
line_num = seg.their_line_num + seg.n;
} else if seg.tactic == RenderTactic::Preserve {
ops.push(UpdateOp::invalidate(seg.n));
b.add_span(seg.n, 0, 0);
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/line_ending.rs | rust/core-lib/src/line_ending.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Utilities for detecting and working with line endings
extern crate xi_rope;
use memchr::memchr2;
use xi_rope::Rope;
/// An enumeration of valid line endings
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LineEnding {
CrLf, // DOS style, \r\n
Lf, // *nix style, \n
}
/// A struct representing a mixed line ending error.
#[derive(Debug)]
pub struct MixedLineEndingError;
impl LineEnding {
/// Breaks a rope down into chunks, and checks each chunk for line endings
pub fn parse(rope: &Rope) -> Result<Option<Self>, MixedLineEndingError> {
let mut crlf = false;
let mut lf = false;
for chunk in rope.iter_chunks(..) {
match LineEnding::parse_chunk(chunk) {
Ok(Some(LineEnding::CrLf)) => crlf = true,
Ok(Some(LineEnding::Lf)) => lf = true,
Ok(None) => (),
Err(e) => return Err(e),
}
}
match (crlf, lf) {
(true, false) => Ok(Some(LineEnding::CrLf)),
(false, true) => Ok(Some(LineEnding::Lf)),
(false, false) => Ok(None),
_ => Err(MixedLineEndingError),
}
}
/// Checks a chunk for line endings, assuming \n or \r\n
pub fn parse_chunk(chunk: &str) -> Result<Option<Self>, MixedLineEndingError> {
let bytes = chunk.as_bytes();
let newline = memchr2(b'\n', b'\r', bytes);
match newline {
Some(x) if bytes[x] == b'\r' && bytes.len() > x + 1 && bytes[x + 1] == b'\n' => {
Ok(Some(LineEnding::CrLf))
}
Some(x) if bytes[x] == b'\n' => Ok(Some(LineEnding::Lf)),
Some(_) => Err(MixedLineEndingError),
_ => Ok(None),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn crlf() {
let result = LineEnding::parse_chunk("\r\n");
assert!(result.is_ok());
assert_eq!(result.unwrap(), Some(LineEnding::CrLf));
}
#[test]
fn lf() {
let result = LineEnding::parse_chunk("\n");
assert!(result.is_ok());
assert_eq!(result.unwrap(), Some(LineEnding::Lf));
}
#[test]
fn legacy_mac_errors() {
assert!(LineEnding::parse_chunk("\r").is_err());
}
#[test]
fn bad_space() {
assert!(LineEnding::parse_chunk("\r \n").is_err());
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/styles.rs | rust/core-lib/src/styles.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Management of styles.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::OsStr;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use serde_json::{self, Value};
use syntect::dumps::{dump_to_file, from_dump_file};
use syntect::highlighting::StyleModifier as SynStyleModifier;
use syntect::highlighting::{Color, Highlighter, Theme, ThemeSet};
use syntect::LoadingError;
pub use syntect::highlighting::ThemeSettings;
pub const N_RESERVED_STYLES: usize = 8;
const SYNTAX_PRIORITY_DEFAULT: u16 = 200;
const SYNTAX_PRIORITY_LOWEST: u16 = 0;
pub const DEFAULT_THEME: &str = "InspiredGitHub";
#[derive(Clone, PartialEq, Eq, Default, Hash, Serialize, Deserialize)]
/// A mergeable style. All values except priority are optional.
///
/// Note: A `None` value represents the absense of preference; in the case of
/// boolean options, `Some(false)` means that this style will override a lower
/// priority value in the same field.
pub struct Style {
/// The priority of this style, in the range (0, 1000). Used to resolve
/// conflicting fields when merging styles. The higher priority wins.
#[serde(skip_serializing)]
pub priority: u16,
/// The foreground text color, in ARGB.
pub fg_color: Option<u32>,
/// The background text color, in ARGB.
#[serde(skip_serializing_if = "Option::is_none")]
pub bg_color: Option<u32>,
/// The font-weight, in the range 100-900, interpreted like the CSS
/// font-weight property.
#[serde(skip_serializing_if = "Option::is_none")]
pub weight: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub underline: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub italic: Option<bool>,
}
impl Style {
/// Creates a new `Style` by converting from a `Syntect::StyleModifier`.
pub fn from_syntect_style_mod(style: &SynStyleModifier) -> Self {
let font_style = style.font_style.map(|s| s.bits()).unwrap_or_default();
let weight = if (font_style & 1) != 0 { Some(700) } else { None };
let underline = if (font_style & 2) != 0 { Some(true) } else { None };
let italic = if (font_style & 4) != 0 { Some(true) } else { None };
Self::new(
SYNTAX_PRIORITY_DEFAULT,
style.foreground.map(Self::rgba_from_syntect_color),
style.background.map(Self::rgba_from_syntect_color),
weight,
underline,
italic,
)
}
pub fn new<O32, O16, OB>(
priority: u16,
fg_color: O32,
bg_color: O32,
weight: O16,
underline: OB,
italic: OB,
) -> Self
where
O32: Into<Option<u32>>,
O16: Into<Option<u16>>,
OB: Into<Option<bool>>,
{
assert!(priority <= 1000);
Style {
priority,
fg_color: fg_color.into(),
bg_color: bg_color.into(),
weight: weight.into(),
underline: underline.into(),
italic: italic.into(),
}
}
/// Returns the default style for the given `Theme`.
pub fn default_for_theme(theme: &Theme) -> Self {
let fg = theme.settings.foreground.unwrap_or(Color::BLACK);
Style::new(
SYNTAX_PRIORITY_LOWEST,
Some(Self::rgba_from_syntect_color(fg)),
None,
None,
None,
None,
)
}
/// Creates a new style by combining attributes of `self` and `other`.
/// If both styles define an attribute, the highest priority wins; `other`
/// wins in the case of a tie.
///
/// Note: when merging multiple styles, apply them in increasing priority.
pub fn merge(&self, other: &Style) -> Style {
let (p1, p2) = if self.priority > other.priority { (self, other) } else { (other, self) };
Style::new(
p1.priority,
p1.fg_color.or(p2.fg_color),
p1.bg_color.or(p2.bg_color),
p1.weight.or(p2.weight),
p1.underline.or(p2.underline),
p1.italic.or(p2.italic),
)
}
/// Encode this `Style`, setting the `id` property.
///
/// Note: this should only be used when sending the `def_style` RPC.
pub fn to_json(&self, id: usize) -> Value {
let mut as_val = serde_json::to_value(self).expect("failed to encode style");
as_val["id"] = id.into();
as_val
}
fn rgba_from_syntect_color(color: Color) -> u32 {
let Color { r, g, b, a } = color;
((a as u32) << 24) | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32)
}
}
/// A map from styles to client identifiers for a given `Theme`.
pub struct ThemeStyleMap {
themes: ThemeSet,
theme_name: String,
theme: Theme,
// Keeps a list of default themes.
default_themes: Vec<String>,
default_style: Style,
map: HashMap<Style, usize>,
// Maintains the map of found themes and their paths.
path_map: BTreeMap<String, PathBuf>,
// It's not obvious we actually have to store the style, we seem to only need it
// as the key in the map.
styles: Vec<Style>,
themes_dir: Option<PathBuf>,
cache_dir: Option<PathBuf>,
caching_enabled: bool,
}
impl ThemeStyleMap {
pub fn new(themes_dir: Option<PathBuf>) -> ThemeStyleMap {
let themes = ThemeSet::load_defaults();
let theme_name = DEFAULT_THEME.to_owned();
let theme = themes.themes.get(&theme_name).expect("missing theme").to_owned();
let default_themes = themes.themes.keys().cloned().collect();
let default_style = Style::default_for_theme(&theme);
let cache_dir = None;
let caching_enabled = true;
ThemeStyleMap {
themes,
theme_name,
theme,
default_themes,
default_style,
map: HashMap::new(),
path_map: BTreeMap::new(),
styles: Vec::new(),
themes_dir,
cache_dir,
caching_enabled,
}
}
pub fn get_default_style(&self) -> &Style {
&self.default_style
}
pub fn get_highlighter(&self) -> Highlighter {
Highlighter::new(&self.theme)
}
pub fn get_theme_name(&self) -> &str {
&self.theme_name
}
pub fn get_theme_settings(&self) -> &ThemeSettings {
&self.theme.settings
}
pub fn get_theme_names(&self) -> Vec<String> {
self.path_map.keys().chain(self.default_themes.iter()).cloned().collect()
}
pub fn contains_theme(&self, k: &str) -> bool {
self.themes.themes.contains_key(k)
}
pub fn set_theme(&mut self, theme_name: &str) -> Result<(), &'static str> {
match self.load_theme(theme_name) {
Ok(()) => {
if let Some(new_theme) = self.themes.themes.get(theme_name) {
self.theme = new_theme.to_owned();
self.theme_name = theme_name.to_owned();
self.default_style = Style::default_for_theme(&self.theme);
self.map = HashMap::new();
self.styles = Vec::new();
Ok(())
} else {
Err("unknown theme")
}
}
Err(e) => {
error!("Encountered error {:?} while trying to load {:?}", e, theme_name);
Err("could not load theme")
}
}
}
pub fn merge_with_default(&self, style: &Style) -> Style {
self.default_style.merge(style)
}
pub fn lookup(&self, style: &Style) -> Option<usize> {
self.map.get(style).cloned()
}
pub fn add(&mut self, style: &Style) -> usize {
let result = self.styles.len() + N_RESERVED_STYLES;
self.map.insert(style.clone(), result);
self.styles.push(style.clone());
result
}
/// Delete key and the corresponding dump file from the themes map.
pub(crate) fn remove_theme(&mut self, path: &Path) -> Option<String> {
validate_theme_file(path).ok()?;
let theme_name = path.file_stem().and_then(OsStr::to_str)?;
self.themes.themes.remove(theme_name);
self.path_map.remove(theme_name);
let dump_p = self.get_dump_path(theme_name)?;
if dump_p.exists() {
let _ = fs::remove_file(dump_p);
}
Some(theme_name.to_string())
}
/// Cache all themes names and their paths inside the given directory.
pub(crate) fn load_theme_dir(&mut self) {
if let Some(themes_dir) = self.themes_dir.clone() {
match ThemeSet::discover_theme_paths(themes_dir) {
Ok(themes) => {
self.caching_enabled = self.caching_enabled && self.init_cache_dir();
// We look through the theme folder here and cache their names/paths to a
// path hashmap.
for theme_p in &themes {
match self.load_theme_info_from_path(theme_p) {
Ok(_) => (),
Err(e) => {
error!("Encountered error {:?} loading theme at {:?}", e, theme_p)
}
}
}
}
Err(e) => error!("Error loading themes dir: {:?}", e),
}
}
}
/// A wrapper around `from_dump_file`
/// to validate the state of dump file.
/// Invalidates if mod time of dump is less
/// than the original one.
fn try_load_from_dump(&self, theme_p: &Path) -> Option<(String, Theme)> {
if !self.caching_enabled {
return None;
}
let theme_name = theme_p.file_stem().and_then(OsStr::to_str)?;
let dump_p = self.get_dump_path(theme_name)?;
if !&dump_p.exists() {
return None;
}
//NOTE: `try_load_from_dump` will return `None` if the file at
//`dump_p` or `theme_p` is deleted before the execution of this fn.
let mod_t = fs::metadata(&dump_p).and_then(|md| md.modified()).ok()?;
let mod_t_orig = fs::metadata(theme_p).and_then(|md| md.modified()).ok()?;
if mod_t >= mod_t_orig {
from_dump_file(&dump_p).ok().map(|t| (theme_name.to_owned(), t))
} else {
// Delete dump file
let _ = fs::remove_file(&dump_p);
None
}
}
/// Loads a theme's name and its respective path into the theme path map.
pub(crate) fn load_theme_info_from_path(
&mut self,
theme_p: &Path,
) -> Result<String, LoadingError> {
validate_theme_file(theme_p)?;
let theme_name =
theme_p.file_stem().and_then(OsStr::to_str).ok_or(LoadingError::BadPath)?;
self.path_map.insert(theme_name.to_string(), theme_p.to_path_buf());
Ok(theme_name.to_owned())
}
/// Loads theme using syntect's `get_theme` fn to our `theme` path map.
/// Stores binary dump in a file with `tmdump` extension, only if
/// caching is enabled.
fn load_theme(&mut self, theme_name: &str) -> Result<(), LoadingError> {
// If it is the current theme (the user has edited it), we load it again.
// Otherwise, if it's a default theme or the theme has already been loaded, we can move on.
if self.contains_theme(theme_name) && self.get_theme_name() != theme_name {
return Ok(());
}
// If we haven't loaded the theme before, we try to load it from the dump if a dump
// exists or load it from the theme file itself.
let theme_p = &self.path_map.get(theme_name).cloned();
if let Some(theme_p) = theme_p {
match self.try_load_from_dump(theme_p) {
Some((dump_theme_name, dump_theme_data)) => {
self.insert_to_map(dump_theme_name, dump_theme_data);
}
None => {
let theme = ThemeSet::get_theme(theme_p)?;
if self.caching_enabled {
if let Some(dump_p) = self.get_dump_path(theme_name) {
let _ = dump_to_file(&theme, dump_p);
}
}
self.insert_to_map(theme_name.to_owned(), theme);
}
}
Ok(())
} else {
Err(LoadingError::BadPath)
}
}
fn insert_to_map(&mut self, k: String, v: Theme) {
self.themes.themes.insert(k, v);
}
/// Returns dump's path corresponding to the given theme name.
fn get_dump_path(&self, theme_name: &str) -> Option<PathBuf> {
self.cache_dir.as_ref().map(|p| p.join(theme_name).with_extension("tmdump"))
}
/// Compare the stored file paths in `self.state`
/// to the present ones.
pub(crate) fn sync_dir(&mut self, dir: Option<&Path>) {
if let Some(themes_dir) = dir {
if let Ok(paths) = ThemeSet::discover_theme_paths(themes_dir) {
let current_state: HashSet<PathBuf> = paths.into_iter().collect();
let maintained_state: HashSet<PathBuf> = self.path_map.values().cloned().collect();
let to_insert = current_state.difference(&maintained_state);
for path in to_insert {
let _ = self.load_theme_info_from_path(path);
}
let to_remove = maintained_state.difference(¤t_state);
for path in to_remove {
self.remove_theme(path);
}
}
}
}
/// Creates the cache dir returns true
/// if it is successfully initialized or
/// already exists.
fn init_cache_dir(&mut self) -> bool {
self.cache_dir = self.themes_dir.clone().map(|p| p.join("cache"));
if let Some(ref p) = self.cache_dir {
if p.exists() {
return true;
}
fs::DirBuilder::new().create(&p).is_ok()
} else {
false
}
}
}
/// Used to remove files with extension other than `tmTheme`.
fn validate_theme_file(path: &Path) -> Result<bool, LoadingError> {
path.extension().map(|e| e != "tmTheme").ok_or(LoadingError::BadPath)
}
impl fmt::Debug for Style {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn fmt_color(f: &mut fmt::Formatter, c: Option<u32>) -> fmt::Result {
if let Some(c) = c {
write!(f, "#{:X}", c)
} else {
write!(f, "None")
}
}
write!(f, "Style( P{}, fg: ", self.priority)?;
fmt_color(f, self.fg_color)?;
write!(f, " bg: ")?;
fmt_color(f, self.bg_color)?;
if let Some(w) = self.weight {
write!(f, " weight {}", w)?;
}
if let Some(i) = self.italic {
write!(f, " ital: {}", i)?;
}
if let Some(u) = self.underline {
write!(f, " uline: {}", u)?;
}
write!(f, " )")
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/editor.rs | rust/core-lib/src/editor.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::borrow::{Borrow, Cow};
use std::cmp::min;
use std::collections::BTreeSet;
use serde_json::Value;
use xi_rope::diff::{Diff, LineHashDiff};
use xi_rope::engine::{Engine, RevId, RevToken};
use xi_rope::rope::count_newlines;
use xi_rope::spans::SpansBuilder;
use xi_rope::{DeltaBuilder, Interval, LinesMetric, Rope, RopeDelta, Transformer};
use xi_trace::{trace_block, trace_payload};
use crate::annotations::{AnnotationType, Annotations};
use crate::config::BufferItems;
use crate::edit_ops::{self, IndentDirection};
use crate::edit_types::BufferEvent;
use crate::event_context::MAX_SIZE_LIMIT;
use crate::layers::Layers;
use crate::line_offset::{LineOffset, LogicalLines};
use crate::movement::Movement;
use crate::plugins::rpc::{DataSpan, GetDataResponse, PluginEdit, ScopeSpan, TextUnit};
use crate::plugins::PluginId;
use crate::rpc::SelectionModifier;
use crate::selection::{InsertDrift, SelRegion, Selection};
use crate::styles::ThemeStyleMap;
use crate::view::{Replace, View};
#[cfg(not(feature = "ledger"))]
pub struct SyncStore;
#[cfg(feature = "ledger")]
use fuchsia::sync::SyncStore;
// TODO This could go much higher without issue but while developing it is
// better to keep it low to expose bugs in the GC during casual testing.
const MAX_UNDOS: usize = 20;
pub struct Editor {
/// The contents of the buffer.
text: Rope,
/// The CRDT engine, which tracks edit history and manages concurrent edits.
engine: Engine,
/// The most recent revision.
last_rev_id: RevId,
/// The revision of the last save.
pristine_rev_id: RevId,
undo_group_id: usize,
/// Undo groups that may still be toggled
live_undos: Vec<usize>,
/// The index of the current undo; subsequent undos are currently 'undone'
/// (but may be redone)
cur_undo: usize,
/// undo groups that are undone
undos: BTreeSet<usize>,
/// undo groups that are no longer live and should be gc'ed
gc_undos: BTreeSet<usize>,
force_undo_group: bool,
this_edit_type: EditType,
last_edit_type: EditType,
revs_in_flight: usize,
/// Used only on Fuchsia for syncing
#[allow(dead_code)]
sync_store: Option<SyncStore>,
#[allow(dead_code)]
last_synced_rev: RevId,
layers: Layers,
}
impl Editor {
/// Creates a new `Editor` with a new empty buffer.
pub fn new() -> Editor {
Self::with_text("")
}
/// Creates a new `Editor`, loading text into a new buffer.
pub fn with_text<T: Into<Rope>>(text: T) -> Editor {
let engine = Engine::new(text.into());
let buffer = engine.get_head().clone();
let last_rev_id = engine.get_head_rev_id();
Editor {
text: buffer,
engine,
last_rev_id,
pristine_rev_id: last_rev_id,
undo_group_id: 1,
// GC only works on undone edits or prefixes of the visible edits,
// but initial file loading can create an edit with undo group 0,
// so we want to collect that as part of the prefix.
live_undos: vec![0],
cur_undo: 1,
undos: BTreeSet::new(),
gc_undos: BTreeSet::new(),
force_undo_group: false,
last_edit_type: EditType::Other,
this_edit_type: EditType::Other,
layers: Layers::default(),
revs_in_flight: 0,
sync_store: None,
last_synced_rev: last_rev_id,
}
}
pub(crate) fn get_buffer(&self) -> &Rope {
&self.text
}
pub(crate) fn get_layers(&self) -> &Layers {
&self.layers
}
pub(crate) fn get_layers_mut(&mut self) -> &mut Layers {
&mut self.layers
}
pub(crate) fn get_head_rev_token(&self) -> u64 {
self.engine.get_head_rev_id().token()
}
pub(crate) fn get_edit_type(&self) -> EditType {
self.this_edit_type
}
pub(crate) fn get_active_undo_group(&self) -> usize {
*self.live_undos.last().unwrap_or(&0)
}
pub(crate) fn update_edit_type(&mut self) {
self.last_edit_type = self.this_edit_type;
self.this_edit_type = EditType::Other
}
pub(crate) fn set_pristine(&mut self) {
self.pristine_rev_id = self.engine.get_head_rev_id();
}
pub(crate) fn is_pristine(&self) -> bool {
self.engine.is_equivalent_revision(self.pristine_rev_id, self.engine.get_head_rev_id())
}
/// Set whether or not edits are forced into the same undo group rather than being split by
/// their EditType.
///
/// This is used for things such as recording playback, where you don't want the
/// individual events to be undoable, but instead the entire playback should be.
pub(crate) fn set_force_undo_group(&mut self, force_undo_group: bool) {
trace_payload("Editor::set_force_undo_group", &["core"], force_undo_group.to_string());
self.force_undo_group = force_undo_group;
}
/// Sets this Editor's contents to `text`, preserving undo state and cursor
/// position when possible.
pub fn reload(&mut self, text: Rope) {
let delta = LineHashDiff::compute_delta(self.get_buffer(), &text);
self.add_delta(delta);
self.set_pristine();
}
// each outstanding plugin edit represents a rev_in_flight.
pub fn increment_revs_in_flight(&mut self) {
self.revs_in_flight += 1;
}
// GC of CRDT engine is deferred until all plugins have acknowledged the new rev,
// so when the ack comes back, potentially trigger GC.
pub fn dec_revs_in_flight(&mut self) {
self.revs_in_flight -= 1;
self.gc_undos();
}
/// Applies a delta to the text, and updates undo state.
///
/// Records the delta into the CRDT engine so that it can be undone. Also
/// contains the logic for merging edits into the same undo group. At call
/// time, self.this_edit_type should be set appropriately.
///
/// This method can be called multiple times, accumulating deltas that will
/// be committed at once with `commit_delta`. Note that it does not update
/// the views. Thus, view-associated state such as the selection and line
/// breaks are to be considered invalid after this method, until the
/// `commit_delta` call.
fn add_delta(&mut self, delta: RopeDelta) {
let head_rev_id = self.engine.get_head_rev_id();
let undo_group = self.calculate_undo_group();
self.last_edit_type = self.this_edit_type;
let priority = 0x10000;
self.engine.edit_rev(priority, undo_group, head_rev_id.token(), delta);
self.text = self.engine.get_head().clone();
}
pub(crate) fn calculate_undo_group(&mut self) -> usize {
let has_undos = !self.live_undos.is_empty();
let force_undo_group = self.force_undo_group;
let is_unbroken_group = !self.this_edit_type.breaks_undo_group(self.last_edit_type);
if has_undos && (force_undo_group || is_unbroken_group) {
*self.live_undos.last().unwrap()
} else {
let undo_group = self.undo_group_id;
self.gc_undos.extend(&self.live_undos[self.cur_undo..]);
self.live_undos.truncate(self.cur_undo);
self.live_undos.push(undo_group);
if self.live_undos.len() <= MAX_UNDOS {
self.cur_undo += 1;
} else {
self.gc_undos.insert(self.live_undos.remove(0));
}
self.undo_group_id += 1;
undo_group
}
}
/// generates a delta from a plugin's response and applies it to the buffer.
pub fn apply_plugin_edit(&mut self, edit: PluginEdit) {
let _t = trace_block("Editor::apply_plugin_edit", &["core"]);
//TODO: get priority working, so that plugin edits don't necessarily move cursor
let PluginEdit { rev, delta, priority, undo_group, .. } = edit;
let priority = priority as usize;
let undo_group = undo_group.unwrap_or_else(|| self.calculate_undo_group());
match self.engine.try_edit_rev(priority, undo_group, rev, delta) {
Err(e) => error!("Error applying plugin edit: {}", e),
Ok(_) => self.text = self.engine.get_head().clone(),
};
}
/// Commits the current delta. If the buffer has changed, returns
/// a 3-tuple containing the delta representing the changes, the previous
/// buffer, and an `InsertDrift` enum describing the correct selection update
/// behaviour.
pub(crate) fn commit_delta(&mut self) -> Option<(RopeDelta, Rope, InsertDrift)> {
let _t = trace_block("Editor::commit_delta", &["core"]);
if self.engine.get_head_rev_id() == self.last_rev_id {
return None;
}
let last_token = self.last_rev_id.token();
let delta = self.engine.try_delta_rev_head(last_token).expect("last_rev not found");
// TODO (performance): it's probably quicker to stash last_text
// rather than resynthesize it.
let last_text = self.engine.get_rev(last_token).expect("last_rev not found");
// Transpose can rotate characters inside of a selection; this is why it's an Inside edit.
// Surround adds characters on either side of a selection, that's why it's an Outside edit.
let drift = match self.this_edit_type {
EditType::Transpose => InsertDrift::Inside,
EditType::Surround => InsertDrift::Outside,
_ => InsertDrift::Default,
};
self.layers.update_all(&delta);
self.last_rev_id = self.engine.get_head_rev_id();
self.sync_state_changed();
Some((delta, last_text, drift))
}
/// Attempts to find the delta from head for the given `RevToken`. Returns
/// `None` if the revision is not found, so this result should be checked if
/// the revision is coming from a plugin.
pub(crate) fn delta_rev_head(&self, target_rev_id: RevToken) -> Option<RopeDelta> {
self.engine.try_delta_rev_head(target_rev_id).ok()
}
#[cfg(not(target_os = "fuchsia"))]
fn gc_undos(&mut self) {
if self.revs_in_flight == 0 && !self.gc_undos.is_empty() {
self.engine.gc(&self.gc_undos);
self.undos = &self.undos - &self.gc_undos;
self.gc_undos.clear();
}
}
#[cfg(target_os = "fuchsia")]
fn gc_undos(&mut self) {
// Never run GC on Fuchsia so that peers don't invalidate our
// last_rev_id and so that merge will work.
}
pub fn merge_new_state(&mut self, new_engine: Engine) {
self.engine.merge(&new_engine);
self.text = self.engine.get_head().clone();
// TODO: better undo semantics. This only implements separate undo
// histories for low concurrency.
self.undo_group_id = self.engine.max_undo_group_id() + 1;
self.last_synced_rev = self.engine.get_head_rev_id();
self.commit_delta();
//self.render();
//FIXME: render after fuchsia sync
}
/// See `Engine::set_session_id`. Only useful for Fuchsia sync.
pub fn set_session_id(&mut self, session: (u64, u32)) {
self.engine.set_session_id(session);
}
#[cfg(feature = "ledger")]
pub fn set_sync_store(&mut self, sync_store: SyncStore) {
self.sync_store = Some(sync_store);
}
#[cfg(not(feature = "ledger"))]
pub fn sync_state_changed(&mut self) {}
#[cfg(feature = "ledger")]
pub fn sync_state_changed(&mut self) {
if let Some(sync_store) = self.sync_store.as_mut() {
// we don't want to sync right after recieving a new merge
if self.last_synced_rev != self.engine.get_head_rev_id() {
self.last_synced_rev = self.engine.get_head_rev_id();
sync_store.state_changed();
}
}
}
#[cfg(feature = "ledger")]
pub fn transaction_ready(&mut self) {
if let Some(sync_store) = self.sync_store.as_mut() {
sync_store.commit_transaction(&self.engine);
}
}
fn do_insert(&mut self, view: &View, config: &BufferItems, chars: &str) {
let pair_search = config.surrounding_pairs.iter().find(|pair| pair.0 == chars);
let caret_exists = view.sel_regions().iter().any(|region| region.is_caret());
if let (Some(pair), false) = (pair_search, caret_exists) {
self.this_edit_type = EditType::Surround;
self.add_delta(edit_ops::surround(
&self.text,
view.sel_regions(),
pair.0.to_string(),
pair.1.to_string(),
));
} else {
self.this_edit_type = EditType::InsertChars;
self.add_delta(edit_ops::insert(&self.text, view.sel_regions(), chars));
}
}
fn do_paste(&mut self, view: &View, chars: &str) {
if view.sel_regions().len() == 1 || view.sel_regions().len() != count_lines(chars) {
self.add_delta(edit_ops::insert(&self.text, view.sel_regions(), chars));
} else {
let mut builder = DeltaBuilder::new(self.text.len());
for (sel, line) in view.sel_regions().iter().zip(chars.lines()) {
let iv = Interval::new(sel.min(), sel.max());
builder.replace(iv, line.into());
}
self.add_delta(builder.build());
}
}
pub(crate) fn do_cut(&mut self, view: &mut View) -> Value {
let result = self.do_copy(view);
let delta = edit_ops::delete_sel_regions(&self.text, view.sel_regions());
if !delta.is_identity() {
self.this_edit_type = EditType::Delete;
self.add_delta(delta);
}
result
}
pub(crate) fn do_copy(&self, view: &View) -> Value {
if let Some(val) = edit_ops::extract_sel_regions(&self.text, view.sel_regions()) {
Value::String(val.into_owned())
} else {
Value::Null
}
}
fn do_undo(&mut self) {
if self.cur_undo > 1 {
self.cur_undo -= 1;
assert!(self.undos.insert(self.live_undos[self.cur_undo]));
self.this_edit_type = EditType::Undo;
self.update_undos();
}
}
fn do_redo(&mut self) {
if self.cur_undo < self.live_undos.len() {
assert!(self.undos.remove(&self.live_undos[self.cur_undo]));
self.cur_undo += 1;
self.this_edit_type = EditType::Redo;
self.update_undos();
}
}
fn update_undos(&mut self) {
self.engine.undo(self.undos.clone());
self.text = self.engine.get_head().clone();
}
fn do_replace(&mut self, view: &mut View, replace_all: bool) {
if let Some(Replace { chars, .. }) = view.get_replace() {
// todo: implement preserve case
// store old selection because in case nothing is found the selection will be preserved
let mut old_selection = Selection::new();
for ®ion in view.sel_regions() {
old_selection.add_region(region);
}
view.collapse_selections(&self.text);
if replace_all {
view.do_find_all(&self.text);
} else {
view.do_find_next(&self.text, false, true, true, &SelectionModifier::Set);
}
if last_selection_region(view.sel_regions()).is_some() {
self.add_delta(edit_ops::insert(&self.text, view.sel_regions(), chars));
}
}
}
fn do_delete_by_movement(
&mut self,
view: &View,
movement: Movement,
save: bool,
kill_ring: &mut Rope,
) {
let (delta, rope) = edit_ops::delete_by_movement(
&self.text,
view.sel_regions(),
view.get_lines(),
movement,
view.scroll_height(),
save,
);
if let Some(rope) = rope {
*kill_ring = rope;
}
if !delta.is_identity() {
self.this_edit_type = EditType::Delete;
self.add_delta(delta);
}
}
fn do_delete_backward(&mut self, view: &View, config: &BufferItems) {
let delta = edit_ops::delete_backward(&self.text, view.sel_regions(), config);
if !delta.is_identity() {
self.this_edit_type = EditType::Delete;
self.add_delta(delta);
}
}
fn do_transpose(&mut self, view: &View) {
let delta = edit_ops::transpose(&self.text, view.sel_regions());
if !delta.is_identity() {
self.this_edit_type = EditType::Transpose;
self.add_delta(delta);
}
}
fn do_transform_text<F: Fn(&str) -> String>(&mut self, view: &View, transform_function: F) {
let delta = edit_ops::transform_text(&self.text, view.sel_regions(), transform_function);
if !delta.is_identity() {
self.this_edit_type = EditType::Other;
self.add_delta(delta);
}
}
fn do_capitalize_text(&mut self, view: &mut View) {
let (delta, final_selection) = edit_ops::capitalize_text(&self.text, view.sel_regions());
if !delta.is_identity() {
self.this_edit_type = EditType::Other;
self.add_delta(delta);
}
// at the end of the transformation carets are located at the end of the words that were
// transformed last in the selections
view.collapse_selections(&self.text);
view.set_selection(&self.text, final_selection);
}
fn do_modify_indent(&mut self, view: &View, config: &BufferItems, direction: IndentDirection) {
let delta = edit_ops::modify_indent(&self.text, view.sel_regions(), config, direction);
self.add_delta(delta);
self.this_edit_type = match direction {
IndentDirection::In => EditType::InsertChars,
IndentDirection::Out => EditType::Delete,
}
}
fn do_insert_newline(&mut self, view: &View, config: &BufferItems) {
let delta = edit_ops::insert_newline(&self.text, view.sel_regions(), config);
self.add_delta(delta);
self.this_edit_type = EditType::InsertNewline;
}
fn do_insert_tab(&mut self, view: &View, config: &BufferItems) {
let regions = view.sel_regions();
let delta = edit_ops::insert_tab(&self.text, regions, config);
// if we indent multiple regions or multiple lines,
// we treat this as an indentation adjustment; otherwise it is
// just inserting text.
let condition = regions
.first()
.map(|x| LogicalLines.get_line_range(&self.text, x).len() > 1)
.unwrap_or(false);
self.add_delta(delta);
self.this_edit_type =
if regions.len() > 1 || condition { EditType::Indent } else { EditType::InsertChars };
}
fn do_yank(&mut self, view: &View, kill_ring: &Rope) {
// TODO: if there are multiple cursors and the number of newlines
// is one less than the number of cursors, split and distribute one
// line per cursor.
let delta = edit_ops::insert(&self.text, view.sel_regions(), kill_ring.clone());
self.add_delta(delta);
}
fn do_duplicate_line(&mut self, view: &View, config: &BufferItems) {
let delta = edit_ops::duplicate_line(&self.text, view.sel_regions(), config);
self.add_delta(delta);
self.this_edit_type = EditType::Other;
}
fn do_change_number<F: Fn(i128) -> Option<i128>>(
&mut self,
view: &View,
transform_function: F,
) {
let delta = edit_ops::change_number(&self.text, view.sel_regions(), transform_function);
if !delta.is_identity() {
self.this_edit_type = EditType::Other;
self.add_delta(delta);
}
}
pub(crate) fn do_edit(
&mut self,
view: &mut View,
kill_ring: &mut Rope,
config: &BufferItems,
cmd: BufferEvent,
) {
use self::BufferEvent::*;
match cmd {
Delete { movement, kill } => {
self.do_delete_by_movement(view, movement, kill, kill_ring)
}
Backspace => self.do_delete_backward(view, config),
Transpose => self.do_transpose(view),
Undo => self.do_undo(),
Redo => self.do_redo(),
Uppercase => self.do_transform_text(view, |s| s.to_uppercase()),
Lowercase => self.do_transform_text(view, |s| s.to_lowercase()),
Capitalize => self.do_capitalize_text(view),
Indent => self.do_modify_indent(view, config, IndentDirection::In),
Outdent => self.do_modify_indent(view, config, IndentDirection::Out),
InsertNewline => self.do_insert_newline(view, config),
InsertTab => self.do_insert_tab(view, config),
Insert(chars) => self.do_insert(view, config, &chars),
Paste(chars) => self.do_paste(view, &chars),
Yank => self.do_yank(view, kill_ring),
ReplaceNext => self.do_replace(view, false),
ReplaceAll => self.do_replace(view, true),
DuplicateLine => self.do_duplicate_line(view, config),
IncreaseNumber => self.do_change_number(view, |s| s.checked_add(1)),
DecreaseNumber => self.do_change_number(view, |s| s.checked_sub(1)),
}
}
pub fn theme_changed(&mut self, style_map: &ThemeStyleMap) {
self.layers.theme_changed(style_map);
}
pub fn plugin_n_lines(&self) -> usize {
self.text.measure::<LinesMetric>() + 1
}
pub fn update_spans(
&mut self,
view: &mut View,
plugin: PluginId,
start: usize,
len: usize,
spans: Vec<ScopeSpan>,
rev: RevToken,
) {
let _t = trace_block("Editor::update_spans", &["core"]);
// TODO: more protection against invalid input
let mut start = start;
let mut end_offset = start + len;
let mut sb = SpansBuilder::new(len);
for span in spans {
sb.add_span(Interval::new(span.start, span.end), span.scope_id);
}
let mut spans = sb.build();
if rev != self.engine.get_head_rev_id().token() {
if let Ok(delta) = self.engine.try_delta_rev_head(rev) {
let mut transformer = Transformer::new(&delta);
let new_start = transformer.transform(start, false);
if !transformer.interval_untouched(Interval::new(start, end_offset)) {
spans = spans.transform(start, end_offset, &mut transformer);
}
start = new_start;
end_offset = transformer.transform(end_offset, true);
} else {
error!("Revision {} not found", rev);
}
}
let iv = Interval::new(start, end_offset);
self.layers.update_layer(plugin, iv, spans);
view.invalidate_styles(&self.text, start, end_offset);
}
pub fn update_annotations(
&mut self,
view: &mut View,
plugin: PluginId,
start: usize,
len: usize,
annotation_spans: Vec<DataSpan>,
annotation_type: AnnotationType,
rev: RevToken,
) {
let _t = trace_block("Editor::update_annotations", &["core"]);
let mut start = start;
let mut end_offset = start + len;
let mut sb = SpansBuilder::new(len);
for span in annotation_spans {
sb.add_span(Interval::new(span.start, span.end), span.data);
}
let mut spans = sb.build();
if rev != self.engine.get_head_rev_id().token() {
if let Ok(delta) = self.engine.try_delta_rev_head(rev) {
let mut transformer = Transformer::new(&delta);
let new_start = transformer.transform(start, false);
if !transformer.interval_untouched(Interval::new(start, end_offset)) {
spans = spans.transform(start, end_offset, &mut transformer);
}
start = new_start;
end_offset = transformer.transform(end_offset, true);
} else {
error!("Revision {} not found", rev);
}
}
let iv = Interval::new(start, end_offset);
view.update_annotations(plugin, iv, Annotations { items: spans, annotation_type });
}
pub(crate) fn get_rev(&self, rev: RevToken) -> Option<Cow<Rope>> {
let text_cow = if rev == self.engine.get_head_rev_id().token() {
Cow::Borrowed(&self.text)
} else {
match self.engine.get_rev(rev) {
None => return None,
Some(text) => Cow::Owned(text),
}
};
Some(text_cow)
}
pub fn plugin_get_data(
&self,
start: usize,
unit: TextUnit,
max_size: usize,
rev: RevToken,
) -> Option<GetDataResponse> {
let _t = trace_block("Editor::plugin_get_data", &["core"]);
let text_cow = self.get_rev(rev)?;
let text = &text_cow;
// convert our offset into a valid byte offset
let offset = unit.resolve_offset(text.borrow(), start)?;
let max_size = min(max_size, MAX_SIZE_LIMIT);
let mut end_off = offset.saturating_add(max_size);
if end_off >= text.len() {
end_off = text.len();
} else {
// Snap end to codepoint boundary.
end_off = text.prev_codepoint_offset(end_off + 1).unwrap();
}
let chunk = text.slice_to_cow(offset..end_off).into_owned();
let first_line = text.line_of_offset(offset);
let first_line_offset = offset - text.offset_of_line(first_line);
Some(GetDataResponse { chunk, offset, first_line, first_line_offset })
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EditType {
/// A catchall for edits that don't fit elsewhere, and which should
/// always have their own undo groups; used for things like cut/copy/paste.
Other,
/// An insert from the keyboard/IME (not a paste or a yank).
#[serde(rename = "insert")]
InsertChars,
#[serde(rename = "newline")]
InsertNewline,
/// An indentation adjustment.
Indent,
Delete,
Undo,
Redo,
Transpose,
Surround,
}
impl EditType {
/// Checks whether a new undo group should be created between two edits.
fn breaks_undo_group(self, previous: EditType) -> bool {
self == EditType::Other || self == EditType::Transpose || self != previous
}
}
fn last_selection_region(regions: &[SelRegion]) -> Option<&SelRegion> {
for region in regions.iter().rev() {
if !region.is_caret() {
return Some(region);
}
}
None
}
/// Counts the number of lines in the string, not including any trailing newline.
fn count_lines(s: &str) -> usize {
let mut newlines = count_newlines(s);
if s.as_bytes().last() == Some(&0xa) {
newlines -= 1;
}
1 + newlines
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plugin_edit() {
let base_text = "hello";
let mut editor = Editor::with_text(base_text);
let mut builder = DeltaBuilder::new(base_text.len());
builder.replace(0..0, "s".into());
let delta = builder.build();
let rev = editor.get_head_rev_token();
let edit_one = PluginEdit {
rev,
delta,
priority: 55,
after_cursor: false,
undo_group: None,
author: "plugin_one".into(),
};
editor.apply_plugin_edit(edit_one.clone());
editor.apply_plugin_edit(edit_one);
assert_eq!(editor.get_buffer().to_string(), "sshello");
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/annotations.rs | rust/core-lib/src/annotations.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Management of annotations.
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, SerializeSeq, Serializer};
use serde_json::{self, Value};
use std::collections::HashMap;
use crate::line_offset::LineOffset;
use crate::plugins::PluginId;
use crate::view::View;
use crate::xi_rope::spans::Spans;
use crate::xi_rope::{Interval, Rope};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum AnnotationType {
Selection,
Find,
Other(String),
}
impl AnnotationType {
fn as_str(&self) -> &str {
match self {
AnnotationType::Find => "find",
AnnotationType::Selection => "selection",
AnnotationType::Other(ref s) => s,
}
}
}
/// Location and range of an annotation ([start_line, start_col, end_line, end_col]).
/// Location and range of an annotation
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct AnnotationRange {
pub start_line: usize,
pub start_col: usize,
pub end_line: usize,
pub end_col: usize,
}
impl Serialize for AnnotationRange {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(Some(4))?;
seq.serialize_element(&self.start_line)?;
seq.serialize_element(&self.start_col)?;
seq.serialize_element(&self.end_line)?;
seq.serialize_element(&self.end_col)?;
seq.end()
}
}
impl<'de> Deserialize<'de> for AnnotationRange {
fn deserialize<D>(deserializer: D) -> Result<AnnotationRange, D::Error>
where
D: Deserializer<'de>,
{
let mut range = AnnotationRange { ..Default::default() };
let seq = <[usize; 4]>::deserialize(deserializer)?;
range.start_line = seq[0];
range.start_col = seq[1];
range.end_line = seq[2];
range.end_col = seq[3];
Ok(range)
}
}
/// A set of annotations of a given type.
#[derive(Debug, Clone)]
pub struct Annotations {
pub items: Spans<Value>,
pub annotation_type: AnnotationType,
}
impl Annotations {
/// Update the annotations in `interval` with the provided `items`.
pub fn update(&mut self, interval: Interval, items: Spans<Value>) {
self.items.edit(interval, items);
}
/// Remove annotations intersecting `interval`.
pub fn invalidate(&mut self, interval: Interval) {
self.items.delete_after(interval);
}
}
/// A region of an `Annotation`.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct AnnotationSlice {
annotation_type: AnnotationType,
/// Annotation occurrences, guaranteed non-descending start order.
ranges: Vec<AnnotationRange>,
/// If present, one payload per range.
payloads: Option<Vec<Value>>,
}
impl AnnotationSlice {
pub fn new(
annotation_type: AnnotationType,
ranges: Vec<AnnotationRange>,
payloads: Option<Vec<Value>>,
) -> Self {
AnnotationSlice { annotation_type, ranges, payloads }
}
/// Returns json representation.
pub fn to_json(&self) -> Value {
json!({
"type": self.annotation_type.as_str(),
"ranges": self.ranges,
"payloads": self.payloads,
"n": self.ranges.len()
})
}
}
/// A trait for types (like `Selection`) that have a distinct representation
/// in core but are presented to the frontend as annotations.
pub trait ToAnnotation {
/// Returns annotations that overlap the provided interval.
fn get_annotations(&self, interval: Interval, view: &View, text: &Rope) -> AnnotationSlice;
}
/// All the annotations for a given view
pub struct AnnotationStore {
store: HashMap<PluginId, Vec<Annotations>>,
}
impl AnnotationStore {
pub fn new() -> Self {
AnnotationStore { store: HashMap::new() }
}
/// Invalidates and removes all annotations in the range of the interval.
pub fn invalidate(&mut self, interval: Interval) {
self.store.values_mut().flat_map(|v| v.iter_mut()).for_each(|a| a.invalidate(interval));
}
/// Applies an update from a plugin to a set of annotations
pub fn update(&mut self, source: PluginId, interval: Interval, item: Annotations) {
if !self.store.contains_key(&source) {
self.store.insert(source, vec![item]);
return;
}
let entry = self.store.get_mut(&source).unwrap();
if let Some(annotation) =
entry.iter_mut().find(|a| a.annotation_type == item.annotation_type)
{
annotation.update(interval, item.items);
} else {
entry.push(item);
}
}
/// Returns an iterator which produces, for each type of annotation,
/// those annotations which intersect the given interval.
pub fn iter_range<'c>(
&'c self,
view: &'c View,
text: &'c Rope,
interval: Interval,
) -> impl Iterator<Item = AnnotationSlice> + 'c {
self.store.iter().flat_map(move |(_plugin, value)| {
value.iter().map(move |annotation| {
// .filter() used instead of .subseq() because subseq() filters out spans with length 0
let payloads = annotation
.items
.iter()
.filter(|(i, _p)| i.start() <= interval.end() && i.end() >= interval.start())
.map(|(_i, p)| p.clone())
.collect::<Vec<Value>>();
let ranges = annotation
.items
.iter()
.filter(|(i, _p)| i.start() <= interval.end() && i.end() >= interval.start())
.map(|(i, _p)| {
let (start_line, start_col) = view.offset_to_line_col(text, i.start());
let (end_line, end_col) = view.offset_to_line_col(text, i.end());
AnnotationRange { start_line, start_col, end_line, end_col }
})
.collect::<Vec<AnnotationRange>>();
AnnotationSlice {
annotation_type: annotation.annotation_type.clone(),
ranges,
payloads: Some(payloads),
}
})
})
}
/// Removes any annotations provided by this plugin
pub fn clear(&mut self, plugin: PluginId) {
self.store.remove(&plugin);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plugins::PluginPid;
use crate::xi_rope::spans::SpansBuilder;
#[test]
fn test_annotation_range_serialization() {
let range = AnnotationRange { start_line: 1, start_col: 3, end_line: 4, end_col: 1 };
assert_eq!(json!(range).to_string(), "[1,3,4,1]")
}
#[test]
fn test_annotation_range_deserialization() {
let range: AnnotationRange = serde_json::from_str("[1,3,4,1]").unwrap();
assert_eq!(range, AnnotationRange { start_line: 1, start_col: 3, end_line: 4, end_col: 1 })
}
#[test]
fn test_annotation_slice_json() {
let range = AnnotationRange { start_line: 1, start_col: 3, end_line: 4, end_col: 1 };
let slice = AnnotationSlice {
annotation_type: AnnotationType::Find,
ranges: vec![range],
payloads: None,
};
assert_eq!(
slice.to_json().to_string(),
"{\"n\":1,\"payloads\":null,\"ranges\":[[1,3,4,1]],\"type\":\"find\"}"
)
}
#[test]
fn test_annotation_store_update() {
let mut store = AnnotationStore::new();
let mut sb = SpansBuilder::new(10);
sb.add_span(Interval::new(1, 5), json!(null));
assert_eq!(store.store.len(), 0);
store.update(
PluginPid(1),
Interval::new(1, 5),
Annotations { annotation_type: AnnotationType::Find, items: sb.build() },
);
assert_eq!(store.store.len(), 1);
sb = SpansBuilder::new(10);
sb.add_span(Interval::new(6, 8), json!(null));
store.update(
PluginPid(2),
Interval::new(6, 8),
Annotations { annotation_type: AnnotationType::Find, items: sb.build() },
);
assert_eq!(store.store.len(), 2);
}
#[test]
fn test_annotation_store_clear() {
let mut store = AnnotationStore::new();
let mut sb = SpansBuilder::new(10);
sb.add_span(Interval::new(1, 5), json!(null));
assert_eq!(store.store.len(), 0);
store.update(
PluginPid(1),
Interval::new(1, 5),
Annotations { annotation_type: AnnotationType::Find, items: sb.build() },
);
assert_eq!(store.store.len(), 1);
sb = SpansBuilder::new(10);
sb.add_span(Interval::new(6, 8), json!(null));
store.update(
PluginPid(2),
Interval::new(6, 8),
Annotations { annotation_type: AnnotationType::Find, items: sb.build() },
);
assert_eq!(store.store.len(), 2);
store.clear(PluginPid(1));
assert_eq!(store.store.len(), 1);
store.clear(PluginPid(1));
assert_eq!(store.store.len(), 1);
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/watcher.rs | rust/core-lib/src/watcher.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Monitoring files and directories.
//!
//! This module contains `FileWatcher` and related types, responsible for
//! monitoring changes to files and directories. Under the hood it is a
//! thin wrapper around some concrete type provided by the
//! [`notify`](https://docs.rs/notify) crate; the implementation is
//! platform dependent, and may be using kqueue, fsevent, or another
//! low-level monitoring system.
//!
//! Our wrapper provides a few useful features:
//!
//! - All `watch` calls are associated with a `WatchToken`; this
//! allows for the same path to be watched multiple times,
//! presumably by multiple interested parties. events are delivered
//! once-per token.
//!
//! - There is the option (via `FileWatcher::watch_filtered`) to include
//! a predicate along with a path, to filter paths before delivery.
//!
//! - We are integrated with the xi_rpc runloop; events are queued as
//! they arrive, and an idle task is scheduled.
use crossbeam_channel::unbounded;
use notify::{event::*, watcher, RecommendedWatcher, RecursiveMode, Watcher};
use std::collections::VecDeque;
use std::fmt;
use std::mem;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use xi_rpc::RpcPeer;
/// Delay for aggregating related file system events.
pub const DEBOUNCE_WAIT_MILLIS: u64 = 50;
/// Wrapper around a `notify::Watcher`. It runs the inner watcher
/// in a separate thread, and communicates with it via a [crossbeam channel].
/// [crossbeam channel]: https://docs.rs/crossbeam-channel
pub struct FileWatcher {
inner: RecommendedWatcher,
state: Arc<Mutex<WatcherState>>,
}
#[derive(Debug, Default)]
struct WatcherState {
events: EventQueue,
watchees: Vec<Watchee>,
}
/// Tracks a registered 'that-which-is-watched'.
#[doc(hidden)]
struct Watchee {
path: PathBuf,
recursive: bool,
token: WatchToken,
filter: Option<Box<PathFilter>>,
}
/// Token provided to `FileWatcher`, to associate events with
/// interested parties.
///
/// Note: `WatchToken`s are assumed to correspond with an
/// 'area of interest'; that is, they are used to route delivery
/// of events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WatchToken(pub usize);
/// A trait for types which can be notified of new events.
/// New events are accessible through the `FileWatcher` instance.
pub trait Notify: Send {
fn notify(&self);
}
pub type EventQueue = VecDeque<(WatchToken, Event)>;
pub type PathFilter = dyn Fn(&Path) -> bool + Send + 'static;
impl FileWatcher {
pub fn new<T: Notify + 'static>(peer: T) -> Self {
let (tx_event, rx_event) = unbounded();
let state = Arc::new(Mutex::new(WatcherState::default()));
let state_clone = state.clone();
let inner = watcher(tx_event, Duration::from_millis(100)).expect("watcher should spawn");
thread::spawn(move || {
while let Ok(Ok(event)) = rx_event.recv() {
let mut state = state_clone.lock().unwrap();
let WatcherState { ref mut events, ref mut watchees } = *state;
watchees
.iter()
.filter(|w| w.wants_event(&event))
.map(|w| w.token)
.for_each(|t| events.push_back((t, event.clone())));
peer.notify();
}
});
FileWatcher { inner, state }
}
/// Begin watching `path`. As `Event`s (documented in the
/// [notify](https://docs.rs/notify) crate) arrive, they are stored
/// with the associated `token` and a task is added to the runloop's
/// idle queue.
///
/// Delivery of events then requires that the runloop's handler
/// correctly forward the `handle_idle` call to the interested party.
pub fn watch(&mut self, path: &Path, recursive: bool, token: WatchToken) {
self.watch_impl(path, recursive, token, None);
}
/// Like `watch`, but taking a predicate function that filters delivery
/// of events based on their path.
pub fn watch_filtered<F>(&mut self, path: &Path, recursive: bool, token: WatchToken, filter: F)
where
F: Fn(&Path) -> bool + Send + 'static,
{
let filter = Box::new(filter) as Box<PathFilter>;
self.watch_impl(path, recursive, token, Some(filter));
}
fn watch_impl(
&mut self,
path: &Path,
recursive: bool,
token: WatchToken,
filter: Option<Box<PathFilter>>,
) {
let path = match path.canonicalize() {
Ok(ref p) => p.to_owned(),
Err(e) => {
warn!("error watching {:?}: {:?}", path, e);
return;
}
};
let mut state = self.state.lock().unwrap();
let w = Watchee { path, recursive, token, filter };
let mode = mode_from_bool(w.recursive);
if !state.watchees.iter().any(|w2| w.path == w2.path) {
if let Err(e) = self.inner.watch(&w.path, mode) {
warn!("watching error {:?}", e);
}
}
state.watchees.push(w);
}
/// Removes the provided token/path pair from the watch list.
/// Does not stop watching this path, if it is associated with
/// other tokens.
pub fn unwatch(&mut self, path: &Path, token: WatchToken) {
let mut state = self.state.lock().unwrap();
let idx = state.watchees.iter().position(|w| w.token == token && w.path == path);
if let Some(idx) = idx {
let removed = state.watchees.remove(idx);
if !state.watchees.iter().any(|w| w.path == removed.path) {
if let Err(e) = self.inner.unwatch(&removed.path) {
warn!("unwatching error {:?}", e);
}
}
//TODO: Ideally we would be tracking what paths we're watching with
// some prefix-tree-like structure, which would let us keep track
// of when some child path might need to be reregistered. How this
// works and when registration would be required is dependent on
// the underlying notification mechanism, however. There's an
// in-progress rewrite of the Notify crate which use under the
// hood, and a component of that rewrite is adding this
// functionality; so until that lands we're using a fairly coarse
// heuristic to determine if we need to re-watch subpaths.
// if this was recursive, check if any child paths need to be
// manually re-added
if removed.recursive {
// do this in two steps because we've borrowed mutably up top
let to_add = state
.watchees
.iter()
.filter(|w| w.path.starts_with(&removed.path))
.map(|w| (w.path.to_owned(), mode_from_bool(w.recursive)))
.collect::<Vec<_>>();
for (path, mode) in to_add {
if let Err(e) = self.inner.watch(&path, mode) {
warn!("watching error {:?}", e);
}
}
}
}
}
/// Takes ownership of this `Watcher`'s current event queue.
pub fn take_events(&mut self) -> VecDeque<(WatchToken, Event)> {
let mut state = self.state.lock().unwrap();
let WatcherState { ref mut events, .. } = *state;
mem::take(events)
}
}
impl Watchee {
fn wants_event(&self, event: &Event) -> bool {
match &event.kind {
EventKind::Create(CreateKind::Any)
| EventKind::Remove(RemoveKind::Any)
| EventKind::Modify(ModifyKind::Any)
| EventKind::Modify(ModifyKind::Metadata(MetadataKind::Any)) => {
if event.paths.len() == 1 {
self.applies_to_path(&event.paths[0])
} else {
info!(
"Rejecting event {:?} with incorrect paths. Expected 1 found {}.",
event,
event.paths.len()
);
false
}
}
EventKind::Modify(ModifyKind::Name(RenameMode::Both)) => {
if event.paths.len() == 2 {
//There will be two paths. First is "from" and other is "to".
self.applies_to_path(&event.paths[0]) || self.applies_to_path(&event.paths[1])
} else {
info!(
"Rejecting event {:?} with incorrect paths. Expected 2 found {}.",
event,
event.paths.len()
);
false
}
}
_ => false,
}
}
fn applies_to_path(&self, path: &Path) -> bool {
let general_case = if path.starts_with(&self.path) {
(self.recursive || self.path == path) || path.parent() == Some(&self.path)
} else {
false
};
if let Some(ref filter) = self.filter {
general_case && filter(path)
} else {
general_case
}
}
}
impl Notify for RpcPeer {
fn notify(&self) {
self.schedule_idle(crate::tabs::WATCH_IDLE_TOKEN);
}
}
impl fmt::Debug for Watchee {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Watchee path: {:?}, r {}, t {} f {}",
self.path,
self.recursive,
self.token.0,
self.filter.is_some()
)
}
}
fn mode_from_bool(is_recursive: bool) -> RecursiveMode {
if is_recursive {
RecursiveMode::Recursive
} else {
RecursiveMode::NonRecursive
}
}
#[cfg(test)]
extern crate tempdir;
#[cfg(test)]
mod tests {
use super::*;
use crossbeam_channel::unbounded;
use notify::EventKind;
use std::ffi::OsStr;
use std::fs;
use std::io::Write;
use std::thread;
use std::time::{Duration, Instant};
impl PartialEq<usize> for WatchToken {
fn eq(&self, other: &usize) -> bool {
self.0 == *other
}
}
impl From<usize> for WatchToken {
fn from(err: usize) -> WatchToken {
WatchToken(err)
}
}
impl Notify for crossbeam_channel::Sender<bool> {
fn notify(&self) {
self.send(true).expect("send shouldn't fail")
}
}
// Sleep for `duration` in milliseconds
pub fn sleep(millis: u64) {
thread::sleep(Duration::from_millis(millis));
}
// Sleep for `duration` in milliseconds if running on OS X
pub fn sleep_if_macos(millis: u64) {
if cfg!(target_os = "macos") {
sleep(millis)
}
}
pub fn recv_all<T>(rx: &crossbeam_channel::Receiver<T>, duration: Duration) -> Vec<T> {
let start = Instant::now();
let mut events = Vec::new();
while start.elapsed() < duration {
match rx.recv_timeout(Duration::from_millis(50)) {
Ok(event) => events.push(event),
Err(crossbeam_channel::RecvTimeoutError::Timeout) => (),
Err(e) => panic!("unexpected channel err: {:?}", e),
}
}
events
}
// from https://github.com/passcod/notify/blob/master/tests/utils/mod.rs
pub trait TestHelpers {
/// Return path relative to the TempDir. Directory separator must
/// be a forward slash, and will be converted to the platform's
/// native separator.
fn mkpath(&self, p: &str) -> PathBuf;
/// Create file or directory. Directories must contain the phrase
/// "dir" otherwise they will be interpreted as files.
fn create(&self, p: &str);
/// Create all files and directories in the `paths` list.
/// Directories must contain the phrase "dir" otherwise they
/// will be interpreted as files.
fn create_all(&self, paths: Vec<&str>);
/// Rename file or directory.
fn rename(&self, a: &str, b: &str);
///// Toggle "other" rights on linux and os x and "readonly" on windows
//fn chmod(&self, p: &str);
/// Write some data to a file
fn write(&self, p: &str);
/// Remove file or directory
fn remove(&self, p: &str);
}
impl TestHelpers for tempdir::TempDir {
fn mkpath(&self, p: &str) -> PathBuf {
let mut path = self.path().canonicalize().expect("failed to canonalize path");
for part in p.split('/').collect::<Vec<_>>() {
if part != "." {
path.push(part);
}
}
path
}
fn create(&self, p: &str) {
let path = self.mkpath(p);
if path.components().last().unwrap().as_os_str().to_str().unwrap().contains("dir") {
fs::create_dir_all(path).expect("failed to create directory");
} else {
let parent = path.parent().expect("failed to get parent directory").to_owned();
if !parent.exists() {
fs::create_dir_all(parent).expect("failed to create parent directory");
}
fs::File::create(path).expect("failed to create file");
}
}
fn create_all(&self, paths: Vec<&str>) {
for p in paths {
self.create(p);
}
}
fn rename(&self, a: &str, b: &str) {
let path_a = self.mkpath(a);
let path_b = self.mkpath(b);
fs::rename(&path_a, &path_b).expect("failed to rename file or directory");
}
fn write(&self, p: &str) {
let path = self.mkpath(p);
let mut file =
fs::OpenOptions::new().write(true).open(path).expect("failed to open file");
file.write_all(b"some data").expect("failed to write to file");
file.sync_all().expect("failed to sync file");
}
fn remove(&self, p: &str) {
let path = self.mkpath(p);
if path.is_dir() {
fs::remove_dir(path).expect("failed to remove directory");
} else {
fs::remove_file(path).expect("failed to remove file");
}
}
}
#[test]
fn test_applies_to_path() {
let mut w = Watchee {
path: PathBuf::from("/hi/there/"),
recursive: false,
token: WatchToken(1),
filter: None,
};
assert!(w.applies_to_path(&PathBuf::from("/hi/there/friend.txt")));
assert!(w.applies_to_path(&PathBuf::from("/hi/there/")));
assert!(!w.applies_to_path(&PathBuf::from("/hi/there/dear/friend.txt")));
assert!(!w.applies_to_path(&PathBuf::from("/oh/hi/there/")));
w.recursive = true;
assert!(w.applies_to_path(&PathBuf::from("/hi/there/dear/friend.txt")));
assert!(w.applies_to_path(&PathBuf::from("/hi/there/friend.txt")));
assert!(w.applies_to_path(&PathBuf::from("/hi/there/")));
w.filter = Some(Box::new(|p| p.extension().and_then(OsStr::to_str) == Some("txt")));
assert!(w.applies_to_path(&PathBuf::from("/hi/there/dear/friend.txt")));
assert!(w.applies_to_path(&PathBuf::from("/hi/there/friend.txt")));
assert!(!w.applies_to_path(&PathBuf::from("/hi/there/")));
assert!(!w.applies_to_path(&PathBuf::from("/hi/there/friend.exe")));
assert!(w.applies_to_path(&PathBuf::from("/hi/there/my/old/sweet/pal.txt")));
}
//https://github.com/passcod/notify/issues/131
#[test]
#[cfg(unix)]
fn test_crash_repro() {
let (tx, _rx) = unbounded();
let path = PathBuf::from("/bin/cat");
let mut w = watcher(tx, Duration::from_secs(1)).unwrap();
w.watch(&path, RecursiveMode::NonRecursive).unwrap();
sleep(20);
w.watch(&path, RecursiveMode::NonRecursive).unwrap();
w.unwatch(&path).unwrap();
}
#[test]
fn recurse_with_contained() {
let (tx, rx) = unbounded();
let tmp = tempdir::TempDir::new("xi-test-recurse-contained").unwrap();
let mut w = FileWatcher::new(tx);
tmp.create("adir/dir2/file");
sleep_if_macos(35_000);
w.watch(&tmp.mkpath("adir"), true, 1.into());
sleep(10);
w.watch(&tmp.mkpath("adir/dir2/file"), false, 2.into());
sleep(10);
w.unwatch(&tmp.mkpath("adir"), 1.into());
sleep(10);
tmp.write("adir/dir2/file");
let _ = recv_all(&rx, Duration::from_millis(1000));
let events = w.take_events();
assert_eq!(
events,
vec![
(
2.into(),
Event::new(EventKind::Modify(ModifyKind::Any))
.add_path(tmp.mkpath("adir/dir2/file"))
.set_flag(Flag::Notice)
),
(
2.into(),
Event::new(EventKind::Modify(ModifyKind::Any))
.add_path(tmp.mkpath("adir/dir2/file"))
),
]
);
}
#[test]
fn two_watchers_one_file() {
let (tx, rx) = unbounded();
let tmp = tempdir::TempDir::new("xi-test-two-watchers").unwrap();
tmp.create("my_file");
sleep_if_macos(30_100);
let mut w = FileWatcher::new(tx);
w.watch(&tmp.mkpath("my_file"), false, 1.into());
sleep_if_macos(10);
w.watch(&tmp.mkpath("my_file"), false, 2.into());
sleep_if_macos(10);
tmp.write("my_file");
let _ = recv_all(&rx, Duration::from_millis(1000));
let events = w.take_events();
assert_eq!(
events,
vec![
(
1.into(),
Event::new(EventKind::Modify(ModifyKind::Any))
.add_path(tmp.mkpath("my_file"))
.set_flag(Flag::Notice)
),
(
2.into(),
Event::new(EventKind::Modify(ModifyKind::Any))
.add_path(tmp.mkpath("my_file"))
.set_flag(Flag::Notice)
),
(
1.into(),
Event::new(EventKind::Modify(ModifyKind::Any)).add_path(tmp.mkpath("my_file"))
),
(
2.into(),
Event::new(EventKind::Modify(ModifyKind::Any)).add_path(tmp.mkpath("my_file"))
),
]
);
assert_eq!(w.state.lock().unwrap().watchees.len(), 2);
w.unwatch(&tmp.mkpath("my_file"), 1.into());
assert_eq!(w.state.lock().unwrap().watchees.len(), 1);
sleep_if_macos(1000);
let path = tmp.mkpath("my_file");
tmp.remove("my_file");
sleep_if_macos(1000);
let _ = recv_all(&rx, Duration::from_millis(1000));
let events = w.take_events();
assert!(events.contains(&(
2.into(),
Event::new(EventKind::Remove(RemoveKind::Any))
.add_path(path.clone())
.set_flag(Flag::Notice)
)));
assert!(!events.contains(&(
1.into(),
Event::new(EventKind::Remove(RemoveKind::Any)).add_path(path).set_flag(Flag::Notice)
)));
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/core.rs | rust/core-lib/src/core.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io;
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use serde_json::Value;
use xi_rpc::{Error as RpcError, Handler, ReadError, RemoteError, RpcCtx};
use crate::plugin_rpc::{PluginCommand, PluginNotification, PluginRequest};
use crate::plugins::{Plugin, PluginId};
use crate::rpc::*;
use crate::tabs::{CoreState, ViewId};
/// A reference to the main core state.
///
/// # Note
///
/// Various items of initial setup are dependent on how the client
/// is configured, so we defer instantiating state until we have that
/// information.
pub enum XiCore {
// TODO: profile startup, and determine what things (such as theme loading)
// we should be doing before client_init.
Waiting,
Running(Arc<Mutex<CoreState>>),
}
/// A weak reference to the main state. This is passed to plugin threads.
#[derive(Clone)]
pub struct WeakXiCore(Weak<Mutex<CoreState>>);
#[allow(dead_code)]
impl XiCore {
pub fn new() -> Self {
XiCore::Waiting
}
/// Returns `true` if the `client_started` has not been received.
fn is_waiting(&self) -> bool {
matches!(*self, XiCore::Waiting)
}
/// Returns a guard to the core state. A convenience around `Mutex::lock`.
///
/// # Panics
///
/// Panics if core has not yet received the `client_started` message.
pub fn inner(&self) -> MutexGuard<CoreState> {
match self {
XiCore::Running(ref inner) => inner.lock().unwrap(),
XiCore::Waiting => panic!(
"core does not start until client_started \
RPC is received"
),
}
}
/// Returns a new reference to the core state, if core is running.
fn weak_self(&self) -> Option<WeakXiCore> {
match self {
XiCore::Running(ref inner) => Some(WeakXiCore(Arc::downgrade(inner))),
XiCore::Waiting => None,
}
}
}
/// Handler for messages originating with the frontend.
impl Handler for XiCore {
type Notification = CoreNotification;
type Request = CoreRequest;
fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) {
use self::CoreNotification::*;
// We allow tracing to be enabled before event `client_started`
if let TracingConfig { enabled } = rpc {
match enabled {
true => xi_trace::enable_tracing(),
false => xi_trace::disable_tracing(),
}
info!("tracing in core = {:?}", enabled);
if self.is_waiting() {
return;
}
}
// wait for client_started before setting up inner
if let ClientStarted { ref config_dir, ref client_extras_dir } = rpc {
assert!(self.is_waiting(), "client_started can only be sent once");
let state =
CoreState::new(ctx.get_peer(), config_dir.clone(), client_extras_dir.clone());
let state = Arc::new(Mutex::new(state));
*self = XiCore::Running(state);
let weak_self = self.weak_self().unwrap();
self.inner().finish_setup(weak_self);
}
self.inner().client_notification(rpc);
}
fn handle_request(&mut self, _ctx: &RpcCtx, rpc: Self::Request) -> Result<Value, RemoteError> {
self.inner().client_request(rpc)
}
fn idle(&mut self, _ctx: &RpcCtx, token: usize) {
self.inner().handle_idle(token);
}
}
impl WeakXiCore {
/// Attempts to upgrade the weak reference. Essentially a wrapper
/// for `Arc::upgrade`.
fn upgrade(&self) -> Option<XiCore> {
self.0.upgrade().map(XiCore::Running)
}
/// Called immediately after attempting to start a plugin,
/// from the plugin's thread.
pub fn plugin_connect(&self, plugin: Result<Plugin, io::Error>) {
if let Some(core) = self.upgrade() {
core.inner().plugin_connect(plugin)
}
}
/// Called from a plugin runloop thread when the runloop exits.
pub fn plugin_exit(&self, plugin: PluginId, error: Result<(), ReadError>) {
if let Some(core) = self.upgrade() {
core.inner().plugin_exit(plugin, error)
}
}
/// Handles the result of an update sent to a plugin.
///
/// All plugins must acknowledge when they are sent a new update, so that
/// core can track which revisions are still 'live', that is can still
/// be the base revision for a delta. Once a plugin has acknowledged a new
/// revision, it can no longer send deltas against any older revision.
pub fn handle_plugin_update(
&self,
plugin: PluginId,
view: ViewId,
response: Result<Value, RpcError>,
) {
if let Some(core) = self.upgrade() {
let _t = xi_trace::trace_block("WeakXiCore::plugin_update", &["core"]);
core.inner().plugin_update(plugin, view, response);
}
}
}
/// Handler for messages originating from plugins.
impl Handler for WeakXiCore {
type Notification = PluginCommand<PluginNotification>;
type Request = PluginCommand<PluginRequest>;
fn handle_notification(&mut self, ctx: &RpcCtx, rpc: Self::Notification) {
let PluginCommand { view_id, plugin_id, cmd } = rpc;
if let Some(core) = self.upgrade() {
core.inner().plugin_notification(ctx, view_id, plugin_id, cmd)
}
}
fn handle_request(&mut self, ctx: &RpcCtx, rpc: Self::Request) -> Result<Value, RemoteError> {
let PluginCommand { view_id, plugin_id, cmd } = rpc;
if let Some(core) = self.upgrade() {
core.inner().plugin_request(ctx, view_id, plugin_id, cmd)
} else {
Err(RemoteError::custom(0, "core is missing", None))
}
}
}
#[cfg(test)]
/// Returns a non-functional `WeakXiRef`, needed to mock other types.
pub fn dummy_weak_core() -> WeakXiCore {
use xi_rpc::test_utils::DummyPeer;
use xi_rpc::Peer;
let peer = Box::new(DummyPeer);
let state = CoreState::new(&peer.box_clone(), None, None);
let core = Arc::new(Mutex::new(state));
WeakXiCore(Arc::downgrade(&core))
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/backspace.rs | rust/core-lib/src/backspace.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Calc start of a backspace delete interval
use xi_rope::{Cursor, Rope};
use crate::config::BufferItems;
use crate::line_offset::{LineOffset, LogicalLines};
use crate::selection::SelRegion;
use xi_unicode::*;
#[allow(clippy::cognitive_complexity)]
pub fn offset_for_delete_backwards(region: &SelRegion, text: &Rope, config: &BufferItems) -> usize {
if !region.is_caret() {
region.min()
} else {
// backspace deletes max(1, tab_size) contiguous spaces
let (_, c) = LogicalLines.offset_to_line_col(text, region.start);
let tab_off = c % config.tab_size;
let tab_size = config.tab_size;
let tab_size = if tab_off == 0 { tab_size } else { tab_off };
let tab_start = region.start.saturating_sub(tab_size);
let preceded_by_spaces =
region.start > 0 && (tab_start..region.start).all(|i| text.byte_at(i) == b' ');
if preceded_by_spaces && config.translate_tabs_to_spaces && config.use_tab_stops {
tab_start
} else {
#[derive(PartialEq)]
enum State {
Start,
Lf,
BeforeKeycap,
BeforeVsAndKeycap,
BeforeEmojiModifier,
BeforeVSAndEmojiModifier,
BeforeVS,
BeforeEmoji,
BeforeZwj,
BeforeVSAndZWJ,
OddNumberedRIS,
EvenNumberedRIS,
InTagSequence,
Finished,
}
let mut state = State::Start;
let mut tmp_offset = region.end;
let mut delete_code_point_count = 0;
let mut last_seen_vs_code_point_count = 0;
while state != State::Finished && tmp_offset > 0 {
let mut cursor = Cursor::new(text, tmp_offset);
let code_point = cursor.prev_codepoint().unwrap_or('0');
tmp_offset = text.prev_codepoint_offset(tmp_offset).unwrap_or(0);
match state {
State::Start => {
delete_code_point_count = 1;
if code_point == '\n' {
state = State::Lf;
} else if is_variation_selector(code_point) {
state = State::BeforeVS;
} else if code_point.is_regional_indicator_symbol() {
state = State::OddNumberedRIS;
} else if code_point.is_emoji_modifier() {
state = State::BeforeEmojiModifier;
} else if code_point.is_emoji_combining_enclosing_keycap() {
state = State::BeforeKeycap;
} else if code_point.is_emoji() {
state = State::BeforeEmoji;
} else if code_point.is_emoji_cancel_tag() {
state = State::InTagSequence;
} else {
state = State::Finished;
}
}
State::Lf => {
if code_point == '\r' {
delete_code_point_count += 1;
}
state = State::Finished;
}
State::OddNumberedRIS => {
if code_point.is_regional_indicator_symbol() {
delete_code_point_count += 1;
state = State::EvenNumberedRIS
} else {
state = State::Finished
}
}
State::EvenNumberedRIS => {
if code_point.is_regional_indicator_symbol() {
delete_code_point_count -= 1;
state = State::OddNumberedRIS;
} else {
state = State::Finished;
}
}
State::BeforeKeycap => {
if is_variation_selector(code_point) {
last_seen_vs_code_point_count = 1;
state = State::BeforeVsAndKeycap;
} else {
if is_keycap_base(code_point) {
delete_code_point_count += 1;
}
state = State::Finished;
}
}
State::BeforeVsAndKeycap => {
if is_keycap_base(code_point) {
delete_code_point_count += last_seen_vs_code_point_count + 1;
}
state = State::Finished;
}
State::BeforeEmojiModifier => {
if is_variation_selector(code_point) {
last_seen_vs_code_point_count = 1;
state = State::BeforeVSAndEmojiModifier;
} else {
if code_point.is_emoji_modifier_base() {
delete_code_point_count += 1;
}
state = State::Finished;
}
}
State::BeforeVSAndEmojiModifier => {
if code_point.is_emoji_modifier_base() {
delete_code_point_count += last_seen_vs_code_point_count + 1;
}
state = State::Finished;
}
State::BeforeVS => {
if code_point.is_emoji() {
delete_code_point_count += 1;
state = State::BeforeEmoji;
} else {
if !is_variation_selector(code_point) {
//TODO: UCharacter.getCombiningClass(codePoint) == 0
delete_code_point_count += 1;
}
state = State::Finished;
}
}
State::BeforeEmoji => {
if code_point.is_zwj() {
state = State::BeforeZwj;
} else {
state = State::Finished;
}
}
State::BeforeZwj => {
if code_point.is_emoji() {
delete_code_point_count += 2;
state = if code_point.is_emoji_modifier() {
State::BeforeEmojiModifier
} else {
State::BeforeEmoji
};
} else if is_variation_selector(code_point) {
last_seen_vs_code_point_count = 1;
state = State::BeforeVSAndZWJ;
} else {
state = State::Finished;
}
}
State::BeforeVSAndZWJ => {
if code_point.is_emoji() {
delete_code_point_count += last_seen_vs_code_point_count + 2;
last_seen_vs_code_point_count = 0;
state = State::BeforeEmoji;
} else {
state = State::Finished;
}
}
State::InTagSequence => {
if code_point.is_tag_spec_char() {
delete_code_point_count += 1;
} else if code_point.is_emoji() {
delete_code_point_count += 1;
state = State::Finished;
} else {
delete_code_point_count = 1;
state = State::Finished;
}
}
State::Finished => {
break;
}
}
}
let mut start = region.end;
while delete_code_point_count > 0 {
start = text.prev_codepoint_offset(start).unwrap_or(0);
delete_code_point_count -= 1;
}
start
}
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/find.rs | rust/core-lib/src/find.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Module for searching text.
use std::cmp::{max, min};
use std::iter;
use crate::annotations::{AnnotationRange, AnnotationSlice, AnnotationType, ToAnnotation};
use crate::line_offset::LineOffset;
use crate::selection::{InsertDrift, SelRegion, Selection};
use crate::view::View;
use crate::word_boundaries::WordCursor;
use regex::{Regex, RegexBuilder};
use xi_rope::delta::DeltaRegion;
use xi_rope::find::{find, is_multiline_regex, CaseMatching};
use xi_rope::{Cursor, Interval, LinesMetric, Metric, Rope, RopeDelta};
const REGEX_SIZE_LIMIT: usize = 1000000;
/// Information about search queries and number of matches for find
#[derive(Serialize, Deserialize, Debug)]
pub struct FindStatus {
/// Identifier for the current search query.
id: usize,
/// The current search query.
chars: Option<String>,
/// Whether the active search is case matching.
case_sensitive: Option<bool>,
/// Whether the search query is considered as regular expression.
is_regex: Option<bool>,
/// Query only matches whole words.
whole_words: Option<bool>,
/// Total number of matches.
matches: usize,
/// Line numbers which have find results.
lines: Vec<usize>,
}
/// Contains logic to search text
pub struct Find {
/// Uniquely identifies this search query.
id: usize,
/// The occurrences, which determine the highlights, have been updated.
hls_dirty: bool,
/// The currently active search string.
search_string: Option<String>,
/// The case matching setting for the currently active search.
case_matching: CaseMatching,
/// The search query should be considered as regular expression.
regex: Option<Regex>,
/// Query matches only whole words.
whole_words: bool,
/// The set of all known find occurrences (highlights).
occurrences: Selection,
}
impl Find {
pub fn new(id: usize) -> Find {
Find {
id,
hls_dirty: true,
search_string: None,
case_matching: CaseMatching::CaseInsensitive,
regex: None,
whole_words: false,
occurrences: Selection::new(),
}
}
pub fn id(&self) -> usize {
self.id
}
pub fn occurrences(&self) -> &Selection {
&self.occurrences
}
pub fn hls_dirty(&self) -> bool {
self.hls_dirty
}
pub fn find_status(&self, view: &View, text: &Rope, matches_only: bool) -> FindStatus {
if matches_only {
FindStatus {
id: self.id,
chars: None,
case_sensitive: None,
is_regex: None,
whole_words: None,
matches: self.occurrences.len(),
lines: Vec::new(),
}
} else {
FindStatus {
id: self.id,
chars: self.search_string.clone(),
case_sensitive: Some(self.case_matching == CaseMatching::Exact),
is_regex: Some(self.regex.is_some()),
whole_words: Some(self.whole_words),
matches: self.occurrences.len(),
lines: self
.occurrences
.iter()
.map(|o| view.offset_to_line_col(text, o.min()).0 + 1)
.collect(),
}
}
}
pub fn set_hls_dirty(&mut self, is_dirty: bool) {
self.hls_dirty = is_dirty
}
pub fn update_highlights(&mut self, text: &Rope, delta: &RopeDelta) {
// update search highlights for changed regions
if self.search_string.is_some() {
// invalidate occurrences around deletion positions
for DeltaRegion { old_offset, len, .. } in delta.iter_deletions() {
self.occurrences.delete_range(old_offset, old_offset + len, false);
}
self.occurrences = self.occurrences.apply_delta(delta, false, InsertDrift::Default);
// invalidate occurrences around insert positions
for DeltaRegion { new_offset, len, .. } in delta.iter_inserts() {
// also invalidate previous occurrence since it might expand after insertion
// eg. for regex .* every insertion after match will be part of match
self.occurrences.delete_range(
new_offset.saturating_sub(1),
new_offset + len,
false,
);
}
// update find for the whole delta and everything after
let (iv, new_len) = delta.summary();
// get last valid occurrence that was unaffected by the delta
let start = match self.occurrences.regions_in_range(0, iv.start()).last() {
Some(reg) => reg.end,
None => 0,
};
// invalidate all search results from the point of the last valid search result until ...
let is_multiline = LinesMetric::next(self.search_string.as_ref().unwrap(), 0).is_some();
if is_multiline || self.is_multiline_regex() {
// ... the end of the file
self.occurrences.delete_range(iv.start(), text.len(), false);
self.update_find(text, start, text.len(), false);
} else {
// ... the end of the line including line break
let mut cursor = Cursor::new(text, iv.end() + new_len);
let end_of_line = match cursor.next::<LinesMetric>() {
Some(end) => end,
None if cursor.pos() == text.len() => cursor.pos(),
_ => return,
};
self.occurrences.delete_range(iv.start(), end_of_line, false);
self.update_find(text, start, end_of_line, false);
}
}
}
/// Returns `true` if the search query is a multi-line regex.
pub(crate) fn is_multiline_regex(&self) -> bool {
self.regex.is_some() && is_multiline_regex(self.search_string.as_ref().unwrap())
}
/// Unsets the search and removes all highlights from the view.
pub fn unset(&mut self) {
self.search_string = None;
self.occurrences = Selection::new();
self.hls_dirty = true;
}
/// Sets find parameters and search query. Returns `true` if parameters have been updated.
/// Returns `false` to indicate that parameters haven't change.
pub(crate) fn set_find(
&mut self,
search_string: &str,
case_sensitive: bool,
is_regex: bool,
whole_words: bool,
) -> bool {
if search_string.is_empty() {
self.unset();
}
let case_matching =
if case_sensitive { CaseMatching::Exact } else { CaseMatching::CaseInsensitive };
if let Some(ref s) = self.search_string {
if s == search_string
&& case_matching == self.case_matching
&& self.regex.is_some() == is_regex
&& self.whole_words == whole_words
{
// search parameters did not change
return false;
}
}
self.unset();
self.search_string = Some(search_string.to_string());
self.case_matching = case_matching;
self.whole_words = whole_words;
// create regex from untrusted input
self.regex = match is_regex {
false => None,
true => RegexBuilder::new(search_string)
.size_limit(REGEX_SIZE_LIMIT)
.case_insensitive(case_matching == CaseMatching::CaseInsensitive)
.build()
.ok(),
};
true
}
/// Execute the search on the provided text in the range provided by `start` and `end`.
pub fn update_find(&mut self, text: &Rope, start: usize, end: usize, include_slop: bool) {
if self.search_string.is_none() {
return;
}
// extend the search by twice the string length (twice, because case matching may increase
// the length of an occurrence)
let slop = if include_slop { self.search_string.as_ref().unwrap().len() * 2 } else { 0 };
let search_string = self.search_string.as_ref().unwrap();
// expand region to be able to find occurrences around the region's edges
let expanded_start = max(start, slop) - slop;
let expanded_end = min(end + slop, text.len());
let from = text.at_or_prev_codepoint_boundary(expanded_start).unwrap_or(0);
let to = text.at_or_next_codepoint_boundary(expanded_end).unwrap_or(text.len());
let mut to_cursor = Cursor::new(text, to);
let _ = to_cursor.next_leaf();
let sub_text = text.subseq(Interval::new(0, to_cursor.pos()));
let mut find_cursor = Cursor::new(&sub_text, from);
let mut raw_lines = text.lines_raw(from..to);
while let Some(start) = find(
&mut find_cursor,
&mut raw_lines,
self.case_matching,
search_string,
self.regex.as_ref(),
) {
let end = find_cursor.pos();
if self.whole_words && !self.is_matching_whole_words(text, start, end) {
raw_lines = text.lines_raw(find_cursor.pos()..to);
continue;
}
let region = SelRegion::new(start, end);
let (_, e) = self.occurrences.add_range_distinct(region);
// in case of ambiguous search results (e.g. search "aba" in "ababa"),
// the search result closer to the beginning of the file wins
if e != end {
// Skip the search result and keep the occurrence that is closer to
// the beginning of the file. Re-align the cursor to the kept
// occurrence
find_cursor.set(e);
raw_lines = text.lines_raw(find_cursor.pos()..to);
continue;
}
// in case current cursor matches search result (for example query a* matches)
// all cursor positions, then cursor needs to be increased so that search
// continues at next position. Otherwise, search will result in overflow since
// search will always repeat at current cursor position.
if start == end {
// determine whether end of text is reached and stop search or increase
// cursor manually
if end + 1 >= text.len() {
break;
} else {
find_cursor.set(end + 1);
}
}
// update line iterator so that line starts at current cursor position
raw_lines = text.lines_raw(find_cursor.pos()..to);
}
self.hls_dirty = true;
}
/// Return the occurrence closest to the provided selection `sel`. If searched is reversed then
/// the occurrence closest to the start of the selection is returned. `wrapped` indicates that
/// if the end of the text is reached the search continues from the start.
pub fn next_occurrence(
&self,
text: &Rope,
reverse: bool,
wrapped: bool,
sel: &Selection,
) -> Option<SelRegion> {
if self.occurrences.len() == 0 {
return None;
}
let (sel_start, sel_end) = match sel.last() {
Some(last) if last.is_caret() =>
// if last selection is caret then allow the current position to be part of the occurrence
{
(last.min(), last.max())
}
Some(last) if !last.is_caret() =>
// if the last selection is not a caret then continue searching after the caret
{
(last.min(), last.max() + 1)
}
_ => (0, 0),
};
if reverse {
let next_occurrence = match sel_start.checked_sub(1) {
Some(search_end) => self.occurrences.regions_in_range(0, search_end).last(),
None => None,
};
if next_occurrence.is_none() && !wrapped {
// get previous unselected occurrence
return self
.occurrences
.regions_in_range(0, text.len())
.iter()
.cloned()
.filter(|o| sel.regions_in_range(o.min(), o.max()).is_empty())
.collect::<Vec<SelRegion>>()
.last()
.cloned();
}
next_occurrence.cloned()
} else {
let next_occurrence = self.occurrences.regions_in_range(sel_end, text.len()).first();
if next_occurrence.is_none() && !wrapped {
// get next unselected occurrence
return self
.occurrences
.regions_in_range(0, text.len())
.iter()
.cloned()
.filter(|o| sel.regions_in_range(o.min(), o.max()).is_empty())
.collect::<Vec<SelRegion>>()
.first()
.cloned();
}
next_occurrence.cloned()
}
}
/// Checks if the start and end of a match is matching whole words.
fn is_matching_whole_words(&self, text: &Rope, start: usize, end: usize) -> bool {
let mut word_end_cursor = WordCursor::new(text, end - 1);
let mut word_start_cursor = WordCursor::new(text, start + 1);
if let Some(start_boundary) = word_start_cursor.prev_boundary() {
if start_boundary != start {
return false;
}
}
if let Some(end_boundary) = word_end_cursor.next_boundary() {
if end_boundary != end {
return false;
}
}
true
}
}
/// Implementing the `ToAnnotation` trait allows to convert finds to annotations.
impl ToAnnotation for Find {
fn get_annotations(&self, interval: Interval, view: &View, text: &Rope) -> AnnotationSlice {
let regions = self.occurrences.regions_in_range(interval.start(), interval.end());
let ranges = regions
.iter()
.map(|region| {
let (start_line, start_col) = view.offset_to_line_col(text, region.min());
let (end_line, end_col) = view.offset_to_line_col(text, region.max());
AnnotationRange { start_line, start_col, end_line, end_col }
})
.collect::<Vec<AnnotationRange>>();
let payload = iter::repeat(json!({"id": self.id})).take(ranges.len()).collect::<Vec<_>>();
AnnotationSlice::new(AnnotationType::Find, ranges, Some(payload))
}
}
#[cfg(test)]
mod tests {
use super::*;
use xi_rope::DeltaBuilder;
#[test]
fn find() {
let base_text = Rope::from("hello world");
let mut find = Find::new(1);
find.set_find("world", false, false, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 1);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(6, 11)));
}
#[test]
fn find_whole_words() {
let base_text = Rope::from("hello world\n many worlds");
let mut find = Find::new(1);
find.set_find("world", false, false, true);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 1);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(6, 11)));
}
#[test]
fn find_case_sensitive() {
let base_text = Rope::from("hello world\n HELLO WORLD");
let mut find = Find::new(1);
find.set_find("world", true, false, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 1);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(6, 11)));
}
#[test]
fn find_multiline() {
let base_text = Rope::from("hello world\n HELLO WORLD");
let mut find = Find::new(1);
find.set_find("hello world\n HELLO", true, false, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 1);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(0, 18)));
}
#[test]
fn find_regex() {
let base_text = Rope::from("hello world\n HELLO WORLD");
let mut find = Find::new(1);
find.set_find("hello \\w+", false, true, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 2);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(0, 11)));
find.set_find("h.llo", true, true, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 1);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(0, 5)));
find.set_find(".*", false, true, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 3);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(0, 11)));
}
#[test]
fn find_regex_multiline() {
let base_text = Rope::from("hello world\n HELLO WORLD");
let mut find = Find::new(1);
find.set_find("(.*\n.*)+", true, true, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 1);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(0, 12)));
}
#[test]
fn find_multiline_regex() {
let mut find = Find::new(1);
find.set_find("a", true, true, false);
assert_eq!(find.is_multiline_regex(), false);
find.set_find(".*", true, true, false);
assert_eq!(find.is_multiline_regex(), false);
find.set_find("\\n", true, true, false);
assert_eq!(find.is_multiline_regex(), true);
}
#[test]
fn find_slop() {
let base_text = Rope::from("aaa bbb aaa bbb aaa x");
let mut find = Find::new(1);
find.set_find("aaa", true, true, false);
find.update_find(&base_text, 2, base_text.len(), false);
assert_eq!(find.occurrences().len(), 2);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(8, 11)));
find.update_find(&base_text, 3, base_text.len(), true);
assert_eq!(find.occurrences().len(), 3);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(0, 3)));
}
#[test]
fn find_next_occurrence() {
let base_text = Rope::from("aaa bbb aaa bbb aaa x");
let mut find = Find::new(1);
find.set_find("aaa", true, true, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 3);
assert_eq!(
find.next_occurrence(&base_text, false, false, &Selection::new()),
Some(SelRegion::new(0, 3))
);
let mut prev_selection = Selection::new();
prev_selection.add_region(SelRegion::new(0, 3));
assert_eq!(
find.next_occurrence(&base_text, false, false, &prev_selection),
Some(SelRegion::new(8, 11))
);
let mut prev_selection = Selection::new();
prev_selection.add_region(SelRegion::new(19, 19));
assert_eq!(
find.next_occurrence(&base_text, false, true, &prev_selection),
Some(SelRegion::new(16, 19))
);
let mut prev_selection = Selection::new();
prev_selection.add_region(SelRegion::new(20, 20));
assert_eq!(
find.next_occurrence(&base_text, false, false, &prev_selection),
Some(SelRegion::new(0, 3))
);
}
#[test]
fn find_previous_occurrence() {
let base_text = Rope::from("aaa bbb aaa bbb aaa x");
let mut find = Find::new(1);
find.set_find("aaa", true, true, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 3);
assert_eq!(
find.next_occurrence(&base_text, true, false, &Selection::new()),
Some(SelRegion::new(16, 19))
);
let mut prev_selection = Selection::new();
prev_selection.add_region(SelRegion::new(20, 20));
assert_eq!(find.next_occurrence(&base_text, true, true, &Selection::new()), None);
}
#[test]
fn unset_find() {
let base_text = Rope::from("aaa bbb aaa bbb aaa x");
let mut find = Find::new(1);
find.set_find("aaa", true, true, false);
find.update_find(&base_text, 0, base_text.len(), false);
assert_eq!(find.occurrences().len(), 3);
find.unset();
assert_eq!(find.occurrences().len(), 0);
}
#[test]
fn update_find_edit() {
let base_text = Rope::from("a b a c");
let mut find = Find::new(1);
find.set_find("a", false, false, false);
find.update_find(&base_text, 0, base_text.len(), false);
let mut builder = DeltaBuilder::new(base_text.len());
builder.replace(0..0, "a ".into());
assert_eq!(find.occurrences().len(), 2);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(0, 1)));
assert_eq!(find.occurrences().last(), Some(&SelRegion::new(4, 5)));
}
#[test]
fn update_find_multiline_edit() {
let base_text = Rope::from("x\n a\n b\n a\n c");
let mut find = Find::new(1);
find.set_find("a", false, false, false);
find.update_find(&base_text, 0, base_text.len(), false);
let mut builder = DeltaBuilder::new(base_text.len());
builder.replace(2..2, " a\n b\n a\n".into());
assert_eq!(find.occurrences().len(), 2);
assert_eq!(find.occurrences().first(), Some(&SelRegion::new(3, 4)));
assert_eq!(find.occurrences().last(), Some(&SelRegion::new(9, 10)));
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/client.rs | rust/core-lib/src/client.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Requests and notifications from the core to front-ends.
use std::time::Instant;
use serde_json::{self, Value};
use xi_rpc::{self, RpcPeer};
use crate::config::Table;
use crate::plugins::rpc::ClientPluginInfo;
use crate::plugins::Command;
use crate::styles::ThemeSettings;
use crate::syntax::LanguageId;
use crate::tabs::ViewId;
use crate::width_cache::{WidthReq, WidthResponse};
/// An interface to the frontend.
pub struct Client(RpcPeer);
impl Client {
pub fn new(peer: RpcPeer) -> Self {
Client(peer)
}
pub fn update_view(&self, view_id: ViewId, update: &Update) {
self.0.send_rpc_notification(
"update",
&json!({
"view_id": view_id,
"update": update,
}),
);
}
pub fn scroll_to(&self, view_id: ViewId, line: usize, col: usize) {
self.0.send_rpc_notification(
"scroll_to",
&json!({
"view_id": view_id,
"line": line,
"col": col,
}),
);
}
pub fn config_changed(&self, view_id: ViewId, changes: &Table) {
self.0.send_rpc_notification(
"config_changed",
&json!({
"view_id": view_id,
"changes": changes,
}),
);
}
pub fn available_themes(&self, theme_names: Vec<String>) {
self.0.send_rpc_notification("available_themes", &json!({ "themes": theme_names }))
}
pub fn available_languages(&self, languages: Vec<LanguageId>) {
self.0.send_rpc_notification("available_languages", &json!({ "languages": languages }))
}
pub fn theme_changed(&self, name: &str, theme: &ThemeSettings) {
self.0.send_rpc_notification(
"theme_changed",
&json!({
"name": name,
"theme": theme,
}),
);
}
pub fn language_changed(&self, view_id: ViewId, new_lang: &LanguageId) {
self.0.send_rpc_notification(
"language_changed",
&json!({
"view_id": view_id,
"language_id": new_lang,
}),
);
}
/// Notify the client that a plugin has started.
pub fn plugin_started(&self, view_id: ViewId, plugin: &str) {
self.0.send_rpc_notification(
"plugin_started",
&json!({
"view_id": view_id,
"plugin": plugin,
}),
);
}
/// Notify the client that a plugin has stopped.
///
/// `code` is not currently used; in the future may be used to
/// pass an exit code.
pub fn plugin_stopped(&self, view_id: ViewId, plugin: &str, code: i32) {
self.0.send_rpc_notification(
"plugin_stopped",
&json!({
"view_id": view_id,
"plugin": plugin,
"code": code,
}),
);
}
/// Notify the client of the available plugins.
pub fn available_plugins(&self, view_id: ViewId, plugins: &[ClientPluginInfo]) {
self.0.send_rpc_notification(
"available_plugins",
&json!({
"view_id": view_id,
"plugins": plugins }),
);
}
pub fn update_cmds(&self, view_id: ViewId, plugin: &str, cmds: &[Command]) {
self.0.send_rpc_notification(
"update_cmds",
&json!({
"view_id": view_id,
"plugin": plugin,
"cmds": cmds,
}),
);
}
pub fn def_style(&self, style: &Value) {
self.0.send_rpc_notification("def_style", style)
}
pub fn find_status(&self, view_id: ViewId, queries: &Value) {
self.0.send_rpc_notification(
"find_status",
&json!({
"view_id": view_id,
"queries": queries,
}),
);
}
pub fn replace_status(&self, view_id: ViewId, replace: &Value) {
self.0.send_rpc_notification(
"replace_status",
&json!({
"view_id": view_id,
"status": replace,
}),
);
}
/// Ask front-end to measure widths of strings.
pub fn measure_width(&self, reqs: &[WidthReq]) -> Result<WidthResponse, xi_rpc::Error> {
let req_json = serde_json::to_value(reqs).expect("failed to serialize width req");
let resp = self.0.send_rpc_request("measure_width", &req_json)?;
Ok(serde_json::from_value(resp).expect("failed to deserialize width response"))
}
pub fn alert<S: AsRef<str>>(&self, msg: S) {
self.0.send_rpc_notification("alert", &json!({ "msg": msg.as_ref() }));
}
pub fn add_status_item(
&self,
view_id: ViewId,
source: &str,
key: &str,
value: &str,
alignment: &str,
) {
self.0.send_rpc_notification(
"add_status_item",
&json!({
"view_id": view_id,
"source": source,
"key": key,
"value": value,
"alignment": alignment
}),
);
}
pub fn update_status_item(&self, view_id: ViewId, key: &str, value: &str) {
self.0.send_rpc_notification(
"update_status_item",
&json!({
"view_id": view_id,
"key": key,
"value": value,
}),
);
}
pub fn remove_status_item(&self, view_id: ViewId, key: &str) {
self.0.send_rpc_notification(
"remove_status_item",
&json!({
"view_id": view_id,
"key": key,
}),
);
}
pub fn show_hover(&self, view_id: ViewId, request_id: usize, result: String) {
self.0.send_rpc_notification(
"show_hover",
&json!({
"view_id": view_id,
"request_id": request_id,
"result": result,
}),
)
}
pub fn schedule_idle(&self, token: usize) {
self.0.schedule_idle(token)
}
pub fn schedule_timer(&self, timeout: Instant, token: usize) {
self.0.schedule_timer(timeout, token);
}
}
#[derive(Debug, Serialize)]
pub struct Update {
pub(crate) ops: Vec<UpdateOp>,
pub(crate) pristine: bool,
pub(crate) annotations: Vec<Value>,
}
#[derive(Debug, Serialize)]
pub(crate) struct UpdateOp {
op: OpType,
n: usize,
#[serde(skip_serializing_if = "Option::is_none")]
lines: Option<Vec<Value>>,
#[serde(rename = "ln")]
#[serde(skip_serializing_if = "Option::is_none")]
first_line_number: Option<usize>,
}
impl UpdateOp {
pub(crate) fn invalidate(n: usize) -> Self {
UpdateOp { op: OpType::Invalidate, n, lines: None, first_line_number: None }
}
pub(crate) fn skip(n: usize) -> Self {
UpdateOp { op: OpType::Skip, n, lines: None, first_line_number: None }
}
pub(crate) fn copy(n: usize, line: usize) -> Self {
UpdateOp { op: OpType::Copy, n, lines: None, first_line_number: Some(line) }
}
pub(crate) fn insert(lines: Vec<Value>) -> Self {
UpdateOp { op: OpType::Insert, n: lines.len(), lines: Some(lines), first_line_number: None }
}
pub(crate) fn update(lines: Vec<Value>, line_opt: Option<usize>) -> Self {
UpdateOp {
op: OpType::Update,
n: lines.len(),
lines: Some(lines),
first_line_number: line_opt,
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
enum OpType {
#[serde(rename = "ins")]
Insert,
Skip,
Invalidate,
Copy,
Update,
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/syntax.rs | rust/core-lib/src/syntax.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Very basic syntax detection.
use std::borrow::Borrow;
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
use std::sync::Arc;
use crate::config::Table;
/// The canonical identifier for a particular `LanguageDefinition`.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[allow(clippy::rc_buffer)] // suppress clippy; TODO consider addressing
// the warning by changing String to str
pub struct LanguageId(Arc<String>);
/// Describes a `LanguageDefinition`. Although these are provided by plugins,
/// they are a fundamental concept in core, used to determine things like
/// plugin activations and active user config tables.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageDefinition {
pub name: LanguageId,
pub extensions: Vec<String>,
pub first_line_match: Option<String>,
pub scope: String,
#[serde(skip)]
pub default_config: Option<Table>,
}
/// A repository of all loaded `LanguageDefinition`s.
#[derive(Debug, Default)]
pub struct Languages {
// NOTE: BTreeMap is used for sorting the languages by name alphabetically
named: BTreeMap<LanguageId, Arc<LanguageDefinition>>,
extensions: HashMap<String, Arc<LanguageDefinition>>,
}
impl Languages {
pub fn new(language_defs: &[LanguageDefinition]) -> Self {
let mut named = BTreeMap::new();
let mut extensions = HashMap::new();
for lang in language_defs.iter() {
let lang_arc = Arc::new(lang.clone());
named.insert(lang.name.clone(), lang_arc.clone());
for ext in &lang.extensions {
extensions.insert(ext.clone(), lang_arc.clone());
}
}
Languages { named, extensions }
}
pub fn language_for_path(&self, path: &Path) -> Option<Arc<LanguageDefinition>> {
path.extension()
.or_else(|| path.file_name())
.and_then(|ext| self.extensions.get(ext.to_str().unwrap_or_default()))
.map(Arc::clone)
}
pub fn language_for_name<S>(&self, name: S) -> Option<Arc<LanguageDefinition>>
where
S: AsRef<str>,
{
self.named.get(name.as_ref()).map(Arc::clone)
}
/// Returns a Vec of any `LanguageDefinition`s which exist
/// in `self` but not `other`.
pub fn difference(&self, other: &Languages) -> Vec<Arc<LanguageDefinition>> {
self.named
.iter()
.filter(|(k, _)| !other.named.contains_key(*k))
.map(|(_, v)| v.clone())
.collect()
}
pub fn iter(&self) -> impl Iterator<Item = &Arc<LanguageDefinition>> {
self.named.values()
}
}
impl AsRef<str> for LanguageId {
fn as_ref(&self) -> &str {
self.0.as_ref()
}
}
// let's us use &str to query a HashMap with `LanguageId` keys
impl Borrow<str> for LanguageId {
fn borrow(&self) -> &str {
self.0.as_ref()
}
}
impl<'a> From<&'a str> for LanguageId {
fn from(src: &'a str) -> LanguageId {
LanguageId(Arc::new(src.into()))
}
}
// for testing
#[cfg(test)]
impl LanguageDefinition {
pub(crate) fn simple(name: &str, exts: &[&str], scope: &str, config: Option<Table>) -> Self {
LanguageDefinition {
name: name.into(),
extensions: exts.iter().map(|s| (*s).into()).collect(),
first_line_match: None,
scope: scope.into(),
default_config: config,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn language_for_path() {
let ld_rust = LanguageDefinition {
name: LanguageId::from("Rust"),
extensions: vec![String::from("rs")],
scope: String::from("source.rust"),
first_line_match: None,
default_config: None,
};
let ld_commit_msg = LanguageDefinition {
name: LanguageId::from("Git Commit"),
extensions: vec![
String::from("COMMIT_EDITMSG"),
String::from("MERGE_MSG"),
String::from("TAG_EDITMSG"),
],
scope: String::from("text.git.commit"),
first_line_match: None,
default_config: None,
};
let languages = Languages::new(&[ld_rust.clone(), ld_commit_msg.clone()]);
assert_eq!(
ld_rust.name,
languages.language_for_path(Path::new("/path/test.rs")).unwrap().name
);
assert_eq!(
ld_commit_msg.name,
languages.language_for_path(Path::new("/path/COMMIT_EDITMSG")).unwrap().name
);
assert_eq!(
ld_commit_msg.name,
languages.language_for_path(Path::new("/path/MERGE_MSG")).unwrap().name
);
assert_eq!(
ld_commit_msg.name,
languages.language_for_path(Path::new("/path/TAG_EDITMSG")).unwrap().name
);
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/whitespace.rs | rust/core-lib/src/whitespace.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Utilities for detecting and working with indentation.
extern crate xi_rope;
use std::collections::BTreeMap;
use xi_rope::Rope;
/// An enumeration of legal indentation types.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Indentation {
Tabs,
Spaces(usize),
}
/// A struct representing the mixed indentation error.
#[derive(Debug)]
pub struct MixedIndentError;
impl Indentation {
/// Parses a rope for indentation settings.
pub fn parse(rope: &Rope) -> Result<Option<Self>, MixedIndentError> {
let lines = rope.lines_raw(..);
let mut tabs = false;
let mut spaces: BTreeMap<usize, usize> = BTreeMap::new();
for line in lines {
match Indentation::parse_line(&line) {
Ok(Some(Indentation::Spaces(size))) => {
let counter = spaces.entry(size).or_insert(0);
*counter += 1;
}
Ok(Some(Indentation::Tabs)) => tabs = true,
Ok(None) => continue,
Err(e) => return Err(e),
}
}
match (tabs, !spaces.is_empty()) {
(true, true) => Err(MixedIndentError),
(true, false) => Ok(Some(Indentation::Tabs)),
(false, true) => {
let tab_size = extract_count(spaces);
if tab_size > 0 {
Ok(Some(Indentation::Spaces(tab_size)))
} else {
Ok(None)
}
}
_ => Ok(None),
}
}
/// Detects the indentation on a specific line.
/// Parses whitespace until first occurrence of something else
pub fn parse_line(line: &str) -> Result<Option<Self>, MixedIndentError> {
let mut spaces = 0;
for char in line.as_bytes() {
match char {
b' ' => spaces += 1,
b'\t' if spaces > 0 => return Err(MixedIndentError),
b'\t' => return Ok(Some(Indentation::Tabs)),
_ => break,
}
}
if spaces > 0 {
Ok(Some(Indentation::Spaces(spaces)))
} else {
Ok(None)
}
}
}
/// Uses a heuristic to calculate the greatest common denominator of most used indentation depths.
///
/// As BTreeMaps are ordered by value, using take on the iterator ensures the indentation levels
/// most frequently used in the file are extracted.
fn extract_count(spaces: BTreeMap<usize, usize>) -> usize {
let mut take_size = 4;
if spaces.len() < take_size {
take_size = spaces.len();
}
// Fold results using GCD, skipping numbers which result in gcd returning 1
spaces.iter().take(take_size).fold(0, |a, (b, _)| {
let d = gcd(a, *b);
if d == 1 {
a
} else {
d
}
})
}
/// Simple implementation to calculate greatest common divisor, based on Euclid's algorithm
fn gcd(a: usize, b: usize) -> usize {
if a == 0 {
b
} else if b == 0 || a == b {
a
} else {
let mut a = a;
let mut b = b;
while b > 0 {
let r = a % b;
a = b;
b = r;
}
a
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gcd_calculates_correctly() {
assert_eq!(21, gcd(1071, 462));
assert_eq!(6, gcd(270, 192));
}
#[test]
fn line_gets_two_spaces() {
let result = Indentation::parse_line(" ");
let expected = Indentation::Spaces(2);
assert_eq!(result.unwrap(), Some(expected));
}
#[test]
fn line_gets_tabs() {
let result = Indentation::parse_line("\t");
let expected = Indentation::Tabs;
assert_eq!(result.unwrap(), Some(expected));
}
#[test]
fn line_errors_mixed_indent() {
let result = Indentation::parse_line(" \t");
assert!(result.is_err());
}
#[test]
fn rope_gets_two_spaces() {
let result = Indentation::parse(&Rope::from(
r#"
// This is a comment
Testing
Indented
Even more indented
# Comment
# Comment
# Comment
"#,
));
let expected = Indentation::Spaces(2);
assert_eq!(result.unwrap(), Some(expected));
}
#[test]
fn rope_gets_four_spaces() {
let result = Indentation::parse(&Rope::from(
r#"
fn my_fun_func(&self,
another_arg: usize) -> Fun {
/* Random comment describing program behavior */
Fun::from(another_arg)
}
"#,
));
let expected = Indentation::Spaces(4);
assert_eq!(result.unwrap(), Some(expected));
}
#[test]
fn rope_returns_none() {
let result = Indentation::parse(&Rope::from(
r#"# Readme example
1. One space.
But the majority is still 0.
"#,
));
assert_eq!(result.unwrap(), None);
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/recorder.rs | rust/core-lib/src/recorder.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Manages recording and enables playback for client sent events.
//!
//! Clients can store multiple, named recordings.
use std::collections::HashMap;
use xi_trace::trace_block;
use crate::edit_types::{BufferEvent, EventDomain};
/// A container that manages and holds all recordings for the current editing session
pub(crate) struct Recorder {
active_recording: Option<String>,
recording_buffer: Vec<EventDomain>,
recordings: HashMap<String, Recording>,
}
impl Recorder {
pub(crate) fn new() -> Recorder {
Recorder {
active_recording: None,
recording_buffer: Vec::new(),
recordings: HashMap::new(),
}
}
pub(crate) fn is_recording(&self) -> bool {
self.active_recording.is_some()
}
/// Starts or stops the specified recording.
///
///
/// There are three outcome behaviors:
/// - If the current recording name is specified, the active recording is saved
/// - If no recording name is specified, the currently active recording is saved
/// - If a recording name other than the active recording is specified,
/// the current recording will be thrown out and will be switched to the new name
///
/// In addition to the above:
/// - If the recording was saved, there is no active recording
/// - If the recording was switched, there will be a new active recording
pub(crate) fn toggle_recording(&mut self, recording_name: Option<String>) {
let is_recording = self.is_recording();
let last_recording = self.active_recording.take();
match (is_recording, &last_recording, &recording_name) {
(true, Some(last_recording), None) => {
self.save_recording_buffer(last_recording.clone())
}
(true, Some(last_recording), Some(recording_name)) => {
if last_recording != recording_name {
self.recording_buffer.clear();
} else {
self.save_recording_buffer(last_recording.clone());
return;
}
}
_ => {}
}
self.active_recording = recording_name;
}
/// Saves an event into the currently active recording.
///
/// Every sequential `BufferEvent::Insert` event will be merged together to cut down the number of
/// `Editor::commit_delta` calls we need to make when playing back.
pub(crate) fn record(&mut self, current_event: EventDomain) {
assert!(self.is_recording());
let recording_buffer = &mut self.recording_buffer;
if recording_buffer.last().is_none() {
recording_buffer.push(current_event);
return;
}
{
let last_event = recording_buffer.last_mut().unwrap();
if let (
EventDomain::Buffer(BufferEvent::Insert(old_characters)),
EventDomain::Buffer(BufferEvent::Insert(new_characters)),
) = (last_event, ¤t_event)
{
old_characters.push_str(new_characters);
return;
}
}
recording_buffer.push(current_event);
}
/// Iterates over a specified recording's buffer and runs the specified action
/// on each event.
pub(crate) fn play<F>(&self, recording_name: &str, action: F)
where
F: FnMut(&EventDomain),
{
let is_current_recording: bool = self
.active_recording
.as_ref()
.map_or(false, |current_recording| current_recording == recording_name);
if is_current_recording {
warn!("Cannot play recording while it's currently active!");
return;
}
if let Some(recording) = self.recordings.get(recording_name) {
recording.play(action);
}
}
/// Completely removes the specified recording from the Recorder
pub(crate) fn clear(&mut self, recording_name: &str) {
self.recordings.remove(recording_name);
}
/// Cleans the recording buffer by filtering out any undo or redo events and then saving it
/// with the specified name.
///
/// A recording should not store any undos or redos--
/// call this once a recording is 'finalized.'
fn save_recording_buffer(&mut self, recording_name: String) {
let mut saw_undo = false;
let mut saw_redo = false;
// Walk the recording backwards and remove any undo / redo events
let filtered: Vec<EventDomain> = self
.recording_buffer
.clone()
.into_iter()
.rev()
.filter(|event| {
if let EventDomain::Buffer(event) = event {
return match event {
BufferEvent::Undo => {
saw_undo = !saw_redo;
saw_redo = false;
false
}
BufferEvent::Redo => {
saw_redo = !saw_undo;
saw_undo = false;
false
}
_ => {
let ret = !saw_undo;
saw_undo = false;
saw_redo = false;
ret
}
};
}
true
})
.collect::<Vec<EventDomain>>()
.into_iter()
.rev()
.collect();
let current_recording = Recording::new(filtered);
self.recordings.insert(recording_name, current_recording);
self.recording_buffer.clear();
}
}
struct Recording {
events: Vec<EventDomain>,
}
impl Recording {
fn new(events: Vec<EventDomain>) -> Recording {
Recording { events }
}
/// Iterates over the recording buffer and runs the specified action
/// on each event.
fn play<F>(&self, action: F)
where
F: FnMut(&EventDomain),
{
let _guard = trace_block("Recording::play", &["core", "recording"]);
self.events.iter().for_each(action)
}
}
// Tests for filtering undo / redo from the recording buffer
// A = Event
// B = Event
// U = Undo
// R = Redo
#[cfg(test)]
mod tests {
use crate::edit_types::{BufferEvent, EventDomain};
use crate::recorder::Recorder;
#[test]
fn play_recording() {
let mut recorder = Recorder::new();
let recording_name = String::new();
let mut expected_events: Vec<EventDomain> = vec![
BufferEvent::Indent.into(),
BufferEvent::Outdent.into(),
BufferEvent::DuplicateLine.into(),
BufferEvent::Transpose.into(),
];
recorder.toggle_recording(Some(recording_name.clone()));
for event in expected_events.iter().rev() {
recorder.record(event.clone());
}
recorder.toggle_recording(Some(recording_name.clone()));
recorder.play(&recording_name, |event| {
// We shouldn't iterate more times than we added items!
let expected_event = expected_events.pop();
assert!(expected_event.is_some());
// Should be the event we expect
assert_eq!(*event, expected_event.unwrap());
});
// We should have iterated over everything we inserted
assert_eq!(expected_events.len(), 0);
}
#[test]
fn play_only_after_saved() {
let mut recorder = Recorder::new();
let recording_name = String::new();
let expected_events: Vec<EventDomain> = vec![
BufferEvent::Indent.into(),
BufferEvent::Outdent.into(),
BufferEvent::DuplicateLine.into(),
BufferEvent::Transpose.into(),
];
recorder.toggle_recording(Some(recording_name.clone()));
for event in expected_events.iter().rev() {
recorder.record(event.clone());
}
recorder.play(&recording_name, |_| {
// We shouldn't have any events to play since nothing was saved!
assert!(false);
});
}
#[test]
fn prevent_same_playback() {
let mut recorder = Recorder::new();
let recording_name = String::new();
let expected_events: Vec<EventDomain> = vec![
BufferEvent::Indent.into(),
BufferEvent::Outdent.into(),
BufferEvent::DuplicateLine.into(),
BufferEvent::Transpose.into(),
];
recorder.toggle_recording(Some(recording_name.clone()));
for event in expected_events.iter().rev() {
recorder.record(event.clone());
}
recorder.toggle_recording(Some(recording_name.clone()));
recorder.toggle_recording(Some(recording_name.clone()));
recorder.play(&recording_name, |_| {
// We shouldn't be able to play a recording while recording with the same name
assert!(false);
});
}
#[test]
fn clear_recording() {
let mut recorder = Recorder::new();
let recording_name = String::new();
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Outdent.into());
recorder.record(BufferEvent::Indent.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(recorder.recordings.get(&recording_name).unwrap().events.len(), 4);
recorder.clear(&recording_name);
assert!(recorder.recordings.get(&recording_name).is_none());
}
#[test]
fn multiple_recordings() {
let mut recorder = Recorder::new();
let recording_a = "a".to_string();
let recording_b = "b".to_string();
recorder.toggle_recording(Some(recording_a.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.toggle_recording(Some(recording_a.clone()));
recorder.toggle_recording(Some(recording_b.clone()));
recorder.record(BufferEvent::Outdent.into());
recorder.record(BufferEvent::Indent.into());
recorder.toggle_recording(Some(recording_b.clone()));
assert_eq!(
recorder.recordings.get(&recording_a).unwrap().events,
vec![BufferEvent::Transpose.into(), BufferEvent::DuplicateLine.into()]
);
assert_eq!(
recorder.recordings.get(&recording_b).unwrap().events,
vec![BufferEvent::Outdent.into(), BufferEvent::Indent.into()]
);
recorder.clear(&recording_a);
assert!(recorder.recordings.get(&recording_a).is_none());
assert!(recorder.recordings.get(&recording_b).is_some());
}
#[test]
fn text_playback() {
let mut recorder = Recorder::new();
let recording_name = String::new();
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Insert("Foo".to_owned()).into());
recorder.record(BufferEvent::Insert("B".to_owned()).into());
recorder.record(BufferEvent::Insert("A".to_owned()).into());
recorder.record(BufferEvent::Insert("R".to_owned()).into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Insert("FooBAR".to_owned()).into()]
);
}
#[test]
fn basic_undo() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Undo removes last item, redo only affects undo
// A U B R => B
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Redo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::DuplicateLine.into()]
);
}
#[test]
fn basic_undo_swapped() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Swapping order of undo and redo from the basic test should give us a different leftover item
// A R B U => A
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Undo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into()]
);
}
#[test]
fn redo_cancels_undo() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Redo cancels out an undo
// A U R B => A B
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into(), BufferEvent::DuplicateLine.into()]
);
}
#[test]
fn undo_cancels_redo() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Undo should cancel a redo, preventing it from canceling another undo
// A U R U => _
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::Undo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(recorder.recordings.get(&recording_name).unwrap().events, vec![]);
}
#[test]
fn undo_as_first_item() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Undo shouldn't do anything as the first item
// U A B R => A B
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Undo.into());
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Redo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into(), BufferEvent::DuplicateLine.into()]
);
}
#[test]
fn redo_as_first_item() {
let mut recorder = Recorder::new();
let recording_name = String::new();
// Redo shouldn't do anything as the first item
// R A B U => A
recorder.toggle_recording(Some(recording_name.clone()));
recorder.record(BufferEvent::Redo.into());
recorder.record(BufferEvent::Transpose.into());
recorder.record(BufferEvent::DuplicateLine.into());
recorder.record(BufferEvent::Undo.into());
recorder.toggle_recording(Some(recording_name.clone()));
assert_eq!(
recorder.recordings.get(&recording_name).unwrap().events,
vec![BufferEvent::Transpose.into()]
);
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/file.rs | rust/core-lib/src/file.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Interactions with the file system.
use std::collections::HashMap;
use std::ffi::OsString;
use std::fmt;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::str;
use std::time::SystemTime;
use xi_rope::Rope;
use xi_rpc::RemoteError;
use crate::tabs::BufferId;
#[cfg(feature = "notify")]
use crate::tabs::OPEN_FILE_EVENT_TOKEN;
#[cfg(feature = "notify")]
use crate::watcher::FileWatcher;
#[cfg(target_family = "unix")]
use std::{fs::Permissions, os::unix::fs::PermissionsExt};
const UTF8_BOM: &str = "\u{feff}";
/// Tracks all state related to open files.
pub struct FileManager {
open_files: HashMap<PathBuf, BufferId>,
file_info: HashMap<BufferId, FileInfo>,
/// A monitor of filesystem events, for things like reloading changed files.
#[cfg(feature = "notify")]
watcher: FileWatcher,
}
#[derive(Debug)]
pub struct FileInfo {
pub encoding: CharacterEncoding,
pub path: PathBuf,
pub mod_time: Option<SystemTime>,
pub has_changed: bool,
#[cfg(target_family = "unix")]
pub permissions: Option<u32>,
}
pub enum FileError {
Io(io::Error, PathBuf),
UnknownEncoding(PathBuf),
HasChanged(PathBuf),
}
#[derive(Debug, Clone, Copy)]
pub enum CharacterEncoding {
Utf8,
Utf8WithBom,
}
impl FileManager {
#[cfg(feature = "notify")]
pub fn new(watcher: FileWatcher) -> Self {
FileManager { open_files: HashMap::new(), file_info: HashMap::new(), watcher }
}
#[cfg(not(feature = "notify"))]
pub fn new() -> Self {
FileManager { open_files: HashMap::new(), file_info: HashMap::new() }
}
#[cfg(feature = "notify")]
pub fn watcher(&mut self) -> &mut FileWatcher {
&mut self.watcher
}
pub fn get_info(&self, id: BufferId) -> Option<&FileInfo> {
self.file_info.get(&id)
}
pub fn get_editor(&self, path: &Path) -> Option<BufferId> {
self.open_files.get(path).cloned()
}
/// Returns `true` if this file is open and has changed on disk.
/// This state is stashed.
pub fn check_file(&mut self, path: &Path, id: BufferId) -> bool {
if let Some(info) = self.file_info.get_mut(&id) {
let mod_t = get_mod_time(path);
if mod_t != info.mod_time {
info.has_changed = true
}
return info.has_changed;
}
false
}
pub fn open(&mut self, path: &Path, id: BufferId) -> Result<Rope, FileError> {
if !path.exists() {
return Ok(Rope::from(""));
}
let (rope, info) = try_load_file(path)?;
self.open_files.insert(path.to_owned(), id);
if self.file_info.insert(id, info).is_none() {
#[cfg(feature = "notify")]
self.watcher.watch(path, false, OPEN_FILE_EVENT_TOKEN);
}
Ok(rope)
}
pub fn close(&mut self, id: BufferId) {
if let Some(info) = self.file_info.remove(&id) {
self.open_files.remove(&info.path);
#[cfg(feature = "notify")]
self.watcher.unwatch(&info.path, OPEN_FILE_EVENT_TOKEN);
}
}
pub fn save(&mut self, path: &Path, text: &Rope, id: BufferId) -> Result<(), FileError> {
let is_existing = self.file_info.contains_key(&id);
if is_existing {
self.save_existing(path, text, id)
} else {
self.save_new(path, text, id)
}
}
fn save_new(&mut self, path: &Path, text: &Rope, id: BufferId) -> Result<(), FileError> {
try_save(path, text, CharacterEncoding::Utf8, self.get_info(id))
.map_err(|e| FileError::Io(e, path.to_owned()))?;
let info = FileInfo {
encoding: CharacterEncoding::Utf8,
path: path.to_owned(),
mod_time: get_mod_time(path),
has_changed: false,
#[cfg(target_family = "unix")]
permissions: get_permissions(path),
};
self.open_files.insert(path.to_owned(), id);
self.file_info.insert(id, info);
#[cfg(feature = "notify")]
self.watcher.watch(path, false, OPEN_FILE_EVENT_TOKEN);
Ok(())
}
fn save_existing(&mut self, path: &Path, text: &Rope, id: BufferId) -> Result<(), FileError> {
let prev_path = self.file_info[&id].path.clone();
if prev_path != path {
self.save_new(path, text, id)?;
self.open_files.remove(&prev_path);
#[cfg(feature = "notify")]
self.watcher.unwatch(&prev_path, OPEN_FILE_EVENT_TOKEN);
} else if self.file_info[&id].has_changed {
return Err(FileError::HasChanged(path.to_owned()));
} else {
let encoding = self.file_info[&id].encoding;
try_save(path, text, encoding, self.get_info(id))
.map_err(|e| FileError::Io(e, path.to_owned()))?;
self.file_info.get_mut(&id).unwrap().mod_time = get_mod_time(path);
}
Ok(())
}
}
fn try_load_file<P>(path: P) -> Result<(Rope, FileInfo), FileError>
where
P: AsRef<Path>,
{
// TODO: support for non-utf8
// it's arguable that the rope crate should have file loading functionality
let mut f =
File::open(path.as_ref()).map_err(|e| FileError::Io(e, path.as_ref().to_owned()))?;
let mut bytes = Vec::new();
f.read_to_end(&mut bytes).map_err(|e| FileError::Io(e, path.as_ref().to_owned()))?;
let encoding = CharacterEncoding::guess(&bytes);
let rope = try_decode(bytes, encoding, path.as_ref())?;
let info = FileInfo {
encoding,
mod_time: get_mod_time(&path),
#[cfg(target_family = "unix")]
permissions: get_permissions(&path),
path: path.as_ref().to_owned(),
has_changed: false,
};
Ok((rope, info))
}
#[allow(unused)]
fn try_save(
path: &Path,
text: &Rope,
encoding: CharacterEncoding,
file_info: Option<&FileInfo>,
) -> io::Result<()> {
let tmp_extension = path.extension().map_or_else(
|| OsString::from("swp"),
|ext| {
let mut ext = ext.to_os_string();
ext.push(".swp");
ext
},
);
let tmp_path = &path.with_extension(tmp_extension);
let mut f = File::create(tmp_path)?;
match encoding {
CharacterEncoding::Utf8WithBom => f.write_all(UTF8_BOM.as_bytes())?,
CharacterEncoding::Utf8 => (),
}
for chunk in text.iter_chunks(..text.len()) {
f.write_all(chunk.as_bytes())?;
}
fs::rename(tmp_path, path)?;
#[cfg(target_family = "unix")]
{
if let Some(info) = file_info {
fs::set_permissions(path, Permissions::from_mode(info.permissions.unwrap_or(0o644)))
.unwrap_or_else(|e| {
warn!("Couldn't set permissions on file {} due to error {}", path.display(), e)
});
}
}
Ok(())
}
fn try_decode(bytes: Vec<u8>, encoding: CharacterEncoding, path: &Path) -> Result<Rope, FileError> {
match encoding {
CharacterEncoding::Utf8 => Ok(Rope::from(
str::from_utf8(&bytes).map_err(|_e| FileError::UnknownEncoding(path.to_owned()))?,
)),
CharacterEncoding::Utf8WithBom => {
let s = String::from_utf8(bytes)
.map_err(|_e| FileError::UnknownEncoding(path.to_owned()))?;
Ok(Rope::from(&s[UTF8_BOM.len()..]))
}
}
}
impl CharacterEncoding {
fn guess(s: &[u8]) -> Self {
if s.starts_with(UTF8_BOM.as_bytes()) {
CharacterEncoding::Utf8WithBom
} else {
CharacterEncoding::Utf8
}
}
}
/// Returns the modification timestamp for the file at a given path,
/// if present.
fn get_mod_time<P: AsRef<Path>>(path: P) -> Option<SystemTime> {
File::open(path).and_then(|f| f.metadata()).and_then(|meta| meta.modified()).ok()
}
/// Returns the file permissions for the file at a given path on UNIXy systems,
/// if present.
#[cfg(target_family = "unix")]
fn get_permissions<P: AsRef<Path>>(path: P) -> Option<u32> {
File::open(path).and_then(|f| f.metadata()).map(|meta| meta.permissions().mode()).ok()
}
impl From<FileError> for RemoteError {
fn from(src: FileError) -> RemoteError {
//TODO: when we migrate to using the failure crate for error handling,
// this should return a better message
let code = src.error_code();
let message = src.to_string();
RemoteError::custom(code, message, None)
}
}
impl FileError {
fn error_code(&self) -> i64 {
match self {
FileError::Io(_, _) => 5,
FileError::UnknownEncoding(_) => 6,
FileError::HasChanged(_) => 7,
}
}
}
impl fmt::Display for FileError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FileError::Io(ref e, ref p) => write!(f, "{}. File path: {:?}", e, p),
FileError::UnknownEncoding(ref p) => write!(f, "Error decoding file: {:?}", p),
FileError::HasChanged(ref p) => write!(
f,
"File has changed on disk. \
Please save elsewhere and reload the file. File path: {:?}",
p
),
}
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/edit_types.rs | rust/core-lib/src/edit_types.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A bunch of boilerplate for converting the `EditNotification`s we receive
//! from the client into the events we use internally.
//!
//! This simplifies code elsewhere, and makes it easier to route events to
//! the editor or view as appropriate.
use crate::movement::Movement;
use crate::rpc::{
EditNotification, FindQuery, GestureType, LineRange, MouseAction, Position,
SelectionGranularity, SelectionModifier,
};
use crate::view::Size;
/// Events that only modify view state
#[derive(Debug, PartialEq, Clone)]
pub(crate) enum ViewEvent {
Move(Movement),
ModifySelection(Movement),
SelectAll,
Scroll(LineRange),
AddSelectionAbove,
AddSelectionBelow,
Click(MouseAction),
Drag(MouseAction),
Gesture { line: u64, col: u64, ty: GestureType },
GotoLine { line: u64 },
Find { chars: String, case_sensitive: bool, regex: bool, whole_words: bool },
MultiFind { queries: Vec<FindQuery> },
FindNext { wrap_around: bool, allow_same: bool, modify_selection: SelectionModifier },
FindPrevious { wrap_around: bool, allow_same: bool, modify_selection: SelectionModifier },
FindAll,
HighlightFind { visible: bool },
SelectionForFind { case_sensitive: bool },
Replace { chars: String, preserve_case: bool },
SelectionForReplace,
SelectionIntoLines,
CollapseSelections,
}
/// Events that modify the buffer
#[derive(Debug, PartialEq, Clone)]
pub(crate) enum BufferEvent {
Delete { movement: Movement, kill: bool },
Backspace,
Transpose,
Undo,
Redo,
Uppercase,
Lowercase,
Capitalize,
Indent,
Outdent,
Insert(String),
Paste(String),
InsertNewline,
InsertTab,
Yank,
ReplaceNext,
ReplaceAll,
DuplicateLine,
IncreaseNumber,
DecreaseNumber,
}
/// An event that needs special handling
#[derive(Debug, PartialEq, Clone)]
pub(crate) enum SpecialEvent {
DebugRewrap,
DebugWrapWidth,
DebugPrintSpans,
Resize(Size),
RequestLines(LineRange),
RequestHover { request_id: usize, position: Option<Position> },
DebugToggleComment,
Reindent,
ToggleRecording(Option<String>),
PlayRecording(String),
ClearRecording(String),
}
#[derive(Debug, PartialEq, Clone)]
pub(crate) enum EventDomain {
View(ViewEvent),
Buffer(BufferEvent),
Special(SpecialEvent),
}
impl From<BufferEvent> for EventDomain {
fn from(src: BufferEvent) -> EventDomain {
EventDomain::Buffer(src)
}
}
impl From<ViewEvent> for EventDomain {
fn from(src: ViewEvent) -> EventDomain {
EventDomain::View(src)
}
}
impl From<SpecialEvent> for EventDomain {
fn from(src: SpecialEvent) -> EventDomain {
EventDomain::Special(src)
}
}
#[rustfmt::skip]
impl From<EditNotification> for EventDomain {
fn from(src: EditNotification) -> EventDomain {
use self::EditNotification::*;
match src {
Insert { chars } =>
BufferEvent::Insert(chars).into(),
Paste { chars } =>
BufferEvent::Paste(chars).into(),
DeleteForward =>
BufferEvent::Delete {
movement: Movement::Right,
kill: false
}.into(),
DeleteBackward =>
BufferEvent::Backspace.into(),
DeleteWordForward =>
BufferEvent::Delete {
movement: Movement::RightWord,
kill: false
}.into(),
DeleteWordBackward =>
BufferEvent::Delete {
movement: Movement::LeftWord,
kill: false
}.into(),
DeleteToEndOfParagraph =>
BufferEvent::Delete {
movement: Movement::EndOfParagraphKill,
kill: true
}.into(),
DeleteToBeginningOfLine =>
BufferEvent::Delete {
movement: Movement::LeftOfLine,
kill: false
}.into(),
InsertNewline =>
BufferEvent::InsertNewline.into(),
InsertTab =>
BufferEvent::InsertTab.into(),
MoveUp =>
ViewEvent::Move(Movement::Up).into(),
MoveUpAndModifySelection =>
ViewEvent::ModifySelection(Movement::Up).into(),
MoveDown =>
ViewEvent::Move(Movement::Down).into(),
MoveDownAndModifySelection =>
ViewEvent::ModifySelection(Movement::Down).into(),
MoveLeft | MoveBackward =>
ViewEvent::Move(Movement::Left).into(),
MoveLeftAndModifySelection =>
ViewEvent::ModifySelection(Movement::Left).into(),
MoveRight | MoveForward =>
ViewEvent::Move(Movement::Right).into(),
MoveRightAndModifySelection =>
ViewEvent::ModifySelection(Movement::Right).into(),
MoveWordLeft =>
ViewEvent::Move(Movement::LeftWord).into(),
MoveWordLeftAndModifySelection =>
ViewEvent::ModifySelection(Movement::LeftWord).into(),
MoveWordRight =>
ViewEvent::Move(Movement::RightWord).into(),
MoveWordRightAndModifySelection =>
ViewEvent::ModifySelection(Movement::RightWord).into(),
MoveToBeginningOfParagraph =>
ViewEvent::Move(Movement::StartOfParagraph).into(),
MoveToBeginningOfParagraphAndModifySelection =>
ViewEvent::ModifySelection(Movement::StartOfParagraph).into(),
MoveToEndOfParagraph =>
ViewEvent::Move(Movement::EndOfParagraph).into(),
MoveToEndOfParagraphAndModifySelection =>
ViewEvent::ModifySelection(Movement::EndOfParagraph).into(),
MoveToLeftEndOfLine =>
ViewEvent::Move(Movement::LeftOfLine).into(),
MoveToLeftEndOfLineAndModifySelection =>
ViewEvent::ModifySelection(Movement::LeftOfLine).into(),
MoveToRightEndOfLine =>
ViewEvent::Move(Movement::RightOfLine).into(),
MoveToRightEndOfLineAndModifySelection =>
ViewEvent::ModifySelection(Movement::RightOfLine).into(),
MoveToBeginningOfDocument =>
ViewEvent::Move(Movement::StartOfDocument).into(),
MoveToBeginningOfDocumentAndModifySelection =>
ViewEvent::ModifySelection(Movement::StartOfDocument).into(),
MoveToEndOfDocument =>
ViewEvent::Move(Movement::EndOfDocument).into(),
MoveToEndOfDocumentAndModifySelection =>
ViewEvent::ModifySelection(Movement::EndOfDocument).into(),
ScrollPageUp =>
ViewEvent::Move(Movement::UpPage).into(),
PageUpAndModifySelection =>
ViewEvent::ModifySelection(Movement::UpPage).into(),
ScrollPageDown =>
ViewEvent::Move(Movement::DownPage).into(),
PageDownAndModifySelection =>
ViewEvent::ModifySelection(Movement::DownPage).into(),
SelectAll => ViewEvent::SelectAll.into(),
AddSelectionAbove => ViewEvent::AddSelectionAbove.into(),
AddSelectionBelow => ViewEvent::AddSelectionBelow.into(),
Scroll(range) => ViewEvent::Scroll(range).into(),
Resize(size) => SpecialEvent::Resize(size).into(),
GotoLine { line } => ViewEvent::GotoLine { line }.into(),
RequestLines(range) => SpecialEvent::RequestLines(range).into(),
Yank => BufferEvent::Yank.into(),
Transpose => BufferEvent::Transpose.into(),
Click(action) => ViewEvent::Click(action).into(),
Drag(action) => ViewEvent::Drag(action).into(),
Gesture { line, col, ty } => {
// Translate deprecated gesture types into the new format
let new_ty = match ty {
GestureType::PointSelect => {
warn!("The point_select gesture is deprecated; use select instead");
GestureType::Select {granularity: SelectionGranularity::Point, multi: false}
}
GestureType::ToggleSel => {
warn!("The toggle_sel gesture is deprecated; use select instead");
GestureType::Select { granularity: SelectionGranularity::Point, multi: true}
}
GestureType::WordSelect => {
warn!("The word_select gesture is deprecated; use select instead");
GestureType::Select { granularity: SelectionGranularity::Word, multi: false}
}
GestureType::MultiWordSelect => {
warn!("The multi_word_select gesture is deprecated; use select instead");
GestureType::Select { granularity: SelectionGranularity::Word, multi: true}
}
GestureType::LineSelect => {
warn!("The line_select gesture is deprecated; use select instead");
GestureType::Select { granularity: SelectionGranularity::Line, multi: false}
}
GestureType::MultiLineSelect => {
warn!("The multi_line_select gesture is deprecated; use select instead");
GestureType::Select { granularity: SelectionGranularity::Line, multi: true}
}
GestureType::RangeSelect => {
warn!("The range_select gesture is deprecated; use select_extend instead");
GestureType::SelectExtend { granularity: SelectionGranularity::Point }
}
_ => ty
};
ViewEvent::Gesture { line, col, ty: new_ty }.into()
},
Undo => BufferEvent::Undo.into(),
Redo => BufferEvent::Redo.into(),
Find { chars, case_sensitive, regex, whole_words } =>
ViewEvent::Find { chars, case_sensitive, regex, whole_words }.into(),
MultiFind { queries } =>
ViewEvent::MultiFind { queries }.into(),
FindNext { wrap_around, allow_same, modify_selection } =>
ViewEvent::FindNext { wrap_around, allow_same, modify_selection }.into(),
FindPrevious { wrap_around, allow_same, modify_selection } =>
ViewEvent::FindPrevious { wrap_around, allow_same, modify_selection }.into(),
FindAll => ViewEvent::FindAll.into(),
DebugRewrap => SpecialEvent::DebugRewrap.into(),
DebugWrapWidth => SpecialEvent::DebugWrapWidth.into(),
DebugPrintSpans => SpecialEvent::DebugPrintSpans.into(),
Uppercase => BufferEvent::Uppercase.into(),
Lowercase => BufferEvent::Lowercase.into(),
Capitalize => BufferEvent::Capitalize.into(),
Indent => BufferEvent::Indent.into(),
Outdent => BufferEvent::Outdent.into(),
Reindent => SpecialEvent::Reindent.into(),
DebugToggleComment => SpecialEvent::DebugToggleComment.into(),
HighlightFind { visible } => ViewEvent::HighlightFind { visible }.into(),
SelectionForFind { case_sensitive } =>
ViewEvent::SelectionForFind { case_sensitive }.into(),
Replace { chars, preserve_case } =>
ViewEvent::Replace { chars, preserve_case }.into(),
ReplaceNext => BufferEvent::ReplaceNext.into(),
ReplaceAll => BufferEvent::ReplaceAll.into(),
SelectionForReplace => ViewEvent::SelectionForReplace.into(),
RequestHover { request_id, position } =>
SpecialEvent::RequestHover { request_id, position }.into(),
SelectionIntoLines => ViewEvent::SelectionIntoLines.into(),
DuplicateLine => BufferEvent::DuplicateLine.into(),
IncreaseNumber => BufferEvent::IncreaseNumber.into(),
DecreaseNumber => BufferEvent::DecreaseNumber.into(),
ToggleRecording { recording_name } => SpecialEvent::ToggleRecording(recording_name).into(),
PlayRecording { recording_name } => SpecialEvent::PlayRecording(recording_name).into(),
ClearRecording { recording_name } => SpecialEvent::ClearRecording(recording_name).into(),
CollapseSelections => ViewEvent::CollapseSelections.into(),
}
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/selection.rs | rust/core-lib/src/selection.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Data structures representing (multiple) selections and cursors.
use std::cmp::{max, min};
use std::fmt;
use std::ops::Deref;
use crate::annotations::{AnnotationRange, AnnotationSlice, AnnotationType, ToAnnotation};
use crate::index_set::remove_n_at;
use crate::line_offset::LineOffset;
use crate::view::View;
use xi_rope::{Interval, Rope, RopeDelta, Transformer};
/// A type representing horizontal measurements. This is currently in units
/// that are not very well defined except that ASCII characters count as
/// 1 each. It will change.
pub type HorizPos = usize;
/// Indicates if an edit should try to drift inside or outside nearby selections. If the selection
/// is zero width, that is, it is a caret, this value will be ignored, the equivalent of the
/// `Default` value.
#[derive(Copy, Clone)]
pub enum InsertDrift {
/// Indicates this edit should happen within any (non-caret) selections if possible.
Inside,
/// Indicates this edit should happen outside any selections if possible.
Outside,
/// Indicates to do whatever the `after` bool says to do
Default,
}
/// A set of zero or more selection regions, representing a selection state.
#[derive(Default, Debug, Clone)]
pub struct Selection {
// An invariant: regions[i].max() <= regions[i+1].min()
// and < if either is_caret()
regions: Vec<SelRegion>,
}
impl Selection {
/// Creates a new empty selection.
pub fn new() -> Selection {
Selection::default()
}
/// Creates a selection with a single region.
pub fn new_simple(region: SelRegion) -> Selection {
Selection { regions: vec![region] }
}
/// Clear the selection.
pub fn clear(&mut self) {
self.regions.clear();
}
/// Collapse all selections into a single caret.
pub fn collapse(&mut self) {
self.regions.truncate(1);
self.regions[0].start = self.regions[0].end;
}
// The smallest index so that offset > region.max() for all preceding
// regions.
pub fn search(&self, offset: usize) -> usize {
if self.regions.is_empty() || offset > self.regions.last().unwrap().max() {
return self.regions.len();
}
match self.regions.binary_search_by(|r| r.max().cmp(&offset)) {
Ok(ix) => ix,
Err(ix) => ix,
}
}
/// Add a region to the selection. This method implements merging logic.
///
/// Two non-caret regions merge if their interiors intersect; merely
/// touching at the edges does not cause a merge. A caret merges with
/// a non-caret if it is in the interior or on either edge. Two carets
/// merge if they are the same offset.
///
/// Performance note: should be O(1) if the new region strictly comes
/// after all the others in the selection, otherwise O(n).
pub fn add_region(&mut self, region: SelRegion) {
let mut ix = self.search(region.min());
if ix == self.regions.len() {
self.regions.push(region);
return;
}
let mut region = region;
let mut end_ix = ix;
if self.regions[ix].min() <= region.min() {
if self.regions[ix].should_merge(region) {
region = region.merge_with(self.regions[ix]);
} else {
ix += 1;
}
end_ix += 1;
}
while end_ix < self.regions.len() && region.should_merge(self.regions[end_ix]) {
region = region.merge_with(self.regions[end_ix]);
end_ix += 1;
}
if ix == end_ix {
self.regions.insert(ix, region);
} else {
self.regions[ix] = region;
remove_n_at(&mut self.regions, ix + 1, end_ix - ix - 1);
}
}
/// Gets a slice of regions that intersect the given range. Regions that
/// merely touch the range at the edges are also included, so it is the
/// caller's responsibility to further trim them, in particular to only
/// display one caret in the upstream/downstream cases.
///
/// Performance note: O(log n).
pub fn regions_in_range(&self, start: usize, end: usize) -> &[SelRegion] {
let first = self.search(start);
let mut last = self.search(end);
if last < self.regions.len() && self.regions[last].min() <= end {
last += 1;
}
&self.regions[first..last]
}
/// Deletes all the regions that intersect or (if delete_adjacent = true) touch the given range.
pub fn delete_range(&mut self, start: usize, end: usize, delete_adjacent: bool) {
let mut first = self.search(start);
let mut last = self.search(end);
if first >= self.regions.len() {
return;
}
if !delete_adjacent && self.regions[first].max() == start {
first += 1;
}
if last < self.regions.len()
&& ((delete_adjacent && self.regions[last].min() <= end)
|| (!delete_adjacent && self.regions[last].min() < end))
{
last += 1;
}
remove_n_at(&mut self.regions, first, last - first);
}
/// Add a region to the selection. This method does not merge regions and does not allow
/// ambiguous regions (regions that overlap).
///
/// On ambiguous regions, the region with the lower start position wins. That is, in such a
/// case, the new region is either not added at all, because there is an ambiguous region with
/// a lower start position, or existing regions that intersect with the new region but do
/// not start before the new region, are deleted.
#[allow(clippy::suspicious_operation_groupings)]
pub fn add_range_distinct(&mut self, region: SelRegion) -> (usize, usize) {
let mut ix = self.search(region.min());
if ix < self.regions.len() && self.regions[ix].max() == region.min() {
ix += 1;
}
if ix < self.regions.len() {
// in case of ambiguous regions the region closer to the left wins
let occ = &self.regions[ix];
let is_eq = occ.min() == region.min() && occ.max() == region.max();
let is_intersect_before = region.min() >= occ.min() && occ.max() > region.min();
if is_eq || is_intersect_before {
return (occ.min(), occ.max());
}
}
// delete ambiguous regions to the right
let mut last = self.search(region.max());
if last < self.regions.len() && self.regions[last].min() < region.max() {
last += 1;
}
remove_n_at(&mut self.regions, ix, last - ix);
if ix == self.regions.len() {
self.regions.push(region);
} else {
self.regions.insert(ix, region);
}
(self.regions[ix].min(), self.regions[ix].max())
}
/// Computes a new selection based on applying a delta to the old selection.
///
/// When new text is inserted at a caret, the new caret can be either before
/// or after the inserted text, depending on the `after` parameter.
///
/// Whether or not the preceding selections are restored depends on the keep_selections
/// value (only set to true on transpose).
pub fn apply_delta(&self, delta: &RopeDelta, after: bool, drift: InsertDrift) -> Selection {
let mut result = Selection::new();
let mut transformer = Transformer::new(delta);
for region in self.iter() {
let is_caret = region.start == region.end;
let is_region_forward = region.start < region.end;
let (start_after, end_after) = match (drift, is_caret) {
(InsertDrift::Inside, false) => (!is_region_forward, is_region_forward),
(InsertDrift::Outside, false) => (is_region_forward, !is_region_forward),
_ => (after, after),
};
let new_region = SelRegion::new(
transformer.transform(region.start, start_after),
transformer.transform(region.end, end_after),
)
.with_affinity(region.affinity);
result.add_region(new_region);
}
result
}
}
/// Implementing the `ToAnnotation` trait allows to convert selections to annotations.
impl ToAnnotation for Selection {
fn get_annotations(&self, interval: Interval, view: &View, text: &Rope) -> AnnotationSlice {
let regions = self.regions_in_range(interval.start(), interval.end());
let ranges = regions
.iter()
.map(|region| {
let (start_line, start_col) = view.offset_to_line_col(text, region.min());
let (end_line, end_col) = view.offset_to_line_col(text, region.max());
AnnotationRange { start_line, start_col, end_line, end_col }
})
.collect::<Vec<AnnotationRange>>();
AnnotationSlice::new(AnnotationType::Selection, ranges, None)
}
}
/// Implementing the Deref trait allows callers to easily test `is_empty`, iterate
/// through all ranges, etc.
impl Deref for Selection {
type Target = [SelRegion];
fn deref(&self) -> &[SelRegion] {
&self.regions
}
}
/// The "affinity" of a cursor which is sitting exactly on a line break.
///
/// We say "cursor" here rather than "caret" because (depending on presentation)
/// the front-end may draw a cursor even when the region is not a caret.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Affinity {
/// The cursor should be displayed downstream of the line break. For
/// example, if the buffer is "abcd", and the cursor is on a line break
/// after "ab", it should be displayed on the second line before "cd".
Downstream,
/// The cursor should be displayed upstream of the line break. For
/// example, if the buffer is "abcd", and the cursor is on a line break
/// after "ab", it should be displayed on the previous line after "ab".
Upstream,
}
impl Default for Affinity {
fn default() -> Affinity {
Affinity::Downstream
}
}
/// A type representing a single contiguous region of a selection. We use the
/// term "caret" (sometimes also "cursor", more loosely) to refer to a selection
/// region with an empty interior. A "non-caret region" is one with a non-empty
/// interior (i.e. `start != end`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct SelRegion {
/// The inactive edge of a selection, as a byte offset. When
/// equal to end, the selection range acts as a caret.
pub start: usize,
/// The active edge of a selection, as a byte offset.
pub end: usize,
/// A saved horizontal position (used primarily for line up/down movement).
pub horiz: Option<HorizPos>,
/// The affinity of the cursor.
pub affinity: Affinity,
}
impl SelRegion {
/// Returns a new region.
pub fn new(start: usize, end: usize) -> Self {
Self { start, end, horiz: None, affinity: Affinity::default() }
}
/// Returns a new caret region (`start == end`).
pub fn caret(pos: usize) -> Self {
Self { start: pos, end: pos, horiz: None, affinity: Affinity::default() }
}
/// Returns a region with the given horizontal position.
pub fn with_horiz(self, horiz: Option<HorizPos>) -> Self {
Self { horiz, ..self }
}
/// Returns a region with the given affinity.
pub fn with_affinity(self, affinity: Affinity) -> Self {
Self { affinity, ..self }
}
/// Gets the earliest offset within the region, ie the minimum of both edges.
pub fn min(self) -> usize {
min(self.start, self.end)
}
/// Gets the latest offset within the region, ie the maximum of both edges.
pub fn max(self) -> usize {
max(self.start, self.end)
}
/// Determines whether the region is a caret (ie has an empty interior).
pub fn is_caret(self) -> bool {
self.start == self.end
}
/// Determines whether the region's affinity is upstream.
pub fn is_upstream(self) -> bool {
self.affinity == Affinity::Upstream
}
// Indicate whether this region should merge with the next.
// Assumption: regions are sorted (self.min() <= other.min())
#[allow(clippy::suspicious_operation_groupings)] // clippy doesn't like comparing min() to max()
fn should_merge(self, other: SelRegion) -> bool {
other.min() < self.max()
|| ((self.is_caret() || other.is_caret()) && other.min() == self.max())
}
// Merge self with an overlapping region.
// Retains direction of self.
fn merge_with(self, other: SelRegion) -> SelRegion {
let is_forward = self.end >= self.start;
let new_min = min(self.min(), other.min());
let new_max = max(self.max(), other.max());
let (start, end) = if is_forward { (new_min, new_max) } else { (new_max, new_min) };
// Could try to preserve horiz/affinity from one of the
// sources, but very likely not worth it.
SelRegion::new(start, end)
}
}
impl<'a> From<&'a SelRegion> for Interval {
fn from(src: &'a SelRegion) -> Interval {
Interval::new(src.min(), src.max())
}
}
impl From<Interval> for SelRegion {
fn from(src: Interval) -> SelRegion {
SelRegion::new(src.start, src.end)
}
}
impl From<SelRegion> for Selection {
fn from(region: SelRegion) -> Self {
Self::new_simple(region)
}
}
impl fmt::Display for Selection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.regions.len() == 1 {
self.regions[0].fmt(f)?;
} else {
write!(f, "[ {}", &self.regions[0])?;
for region in &self.regions[1..] {
write!(f, ", {}", region)?;
}
write!(f, " ]")?;
}
Ok(())
}
}
impl fmt::Display for SelRegion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_caret() {
write!(f, "{}|", self.start)?;
} else if self.start < self.end {
write!(f, "{}..{}|", self.start, self.end)?;
} else {
write!(f, "|{}..{}", self.end, self.start)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::{InsertDrift, SelRegion, Selection};
use std::ops::Deref;
use xi_rope::{DeltaBuilder, Interval};
fn r(start: usize, end: usize) -> SelRegion {
SelRegion::new(start, end)
}
#[test]
fn empty() {
let s = Selection::new();
assert!(s.is_empty());
assert_eq!(s.deref(), &[]);
}
#[test]
fn simple_region() {
let s = Selection::new_simple(r(3, 5));
assert!(!s.is_empty());
assert_eq!(s.deref(), &[r(3, 5)]);
}
#[test]
fn from_selregion() {
let s: Selection = r(3, 5).into();
assert!(!s.is_empty());
assert_eq!(s.deref(), &[r(3, 5)]);
}
#[test]
fn delete_range() {
let mut s = Selection::new_simple(r(3, 5));
s.delete_range(1, 2, true);
assert_eq!(s.deref(), &[r(3, 5)]);
s.delete_range(1, 3, false);
assert_eq!(s.deref(), &[r(3, 5)]);
s.delete_range(1, 3, true);
assert_eq!(s.deref(), &[]);
let mut s = Selection::new_simple(r(3, 5));
s.delete_range(5, 6, false);
assert_eq!(s.deref(), &[r(3, 5)]);
s.delete_range(5, 6, true);
assert_eq!(s.deref(), &[]);
let mut s = Selection::new_simple(r(3, 5));
s.delete_range(2, 4, false);
assert_eq!(s.deref(), &[]);
assert_eq!(s.deref(), &[]);
let mut s = Selection::new();
s.add_region(r(3, 5));
s.add_region(r(7, 8));
s.delete_range(2, 10, false);
assert_eq!(s.deref(), &[]);
}
#[test]
fn simple_regions_in_range() {
let s = Selection::new_simple(r(3, 5));
assert_eq!(s.regions_in_range(0, 1), &[]);
assert_eq!(s.regions_in_range(0, 2), &[]);
assert_eq!(s.regions_in_range(0, 3), &[r(3, 5)]);
assert_eq!(s.regions_in_range(0, 4), &[r(3, 5)]);
assert_eq!(s.regions_in_range(5, 6), &[r(3, 5)]);
assert_eq!(s.regions_in_range(6, 7), &[]);
}
#[test]
fn caret_regions_in_range() {
let s = Selection::new_simple(r(4, 4));
assert_eq!(s.regions_in_range(0, 1), &[]);
assert_eq!(s.regions_in_range(0, 2), &[]);
assert_eq!(s.regions_in_range(0, 3), &[]);
assert_eq!(s.regions_in_range(0, 4), &[r(4, 4)]);
assert_eq!(s.regions_in_range(4, 4), &[r(4, 4)]);
assert_eq!(s.regions_in_range(4, 5), &[r(4, 4)]);
assert_eq!(s.regions_in_range(5, 6), &[]);
}
#[test]
fn merge_regions() {
let mut s = Selection::new();
s.add_region(r(3, 5));
assert_eq!(s.deref(), &[r(3, 5)]);
s.add_region(r(7, 9));
assert_eq!(s.deref(), &[r(3, 5), r(7, 9)]);
s.add_region(r(1, 3));
assert_eq!(s.deref(), &[r(1, 3), r(3, 5), r(7, 9)]);
s.add_region(r(4, 6));
assert_eq!(s.deref(), &[r(1, 3), r(3, 6), r(7, 9)]);
s.add_region(r(2, 8));
assert_eq!(s.deref(), &[r(1, 9)]);
s.add_region(r(10, 8));
assert_eq!(s.deref(), &[r(10, 1)]);
s.clear();
assert_eq!(s.deref(), &[]);
s.add_region(r(1, 4));
s.add_region(r(4, 5));
s.add_region(r(5, 6));
s.add_region(r(6, 9));
assert_eq!(s.deref(), &[r(1, 4), r(4, 5), r(5, 6), r(6, 9)]);
s.add_region(r(2, 8));
assert_eq!(s.deref(), &[r(1, 9)]);
}
#[test]
fn merge_carets() {
let mut s = Selection::new();
s.add_region(r(1, 1));
assert_eq!(s.deref(), &[r(1, 1)]);
s.add_region(r(3, 3));
assert_eq!(s.deref(), &[r(1, 1), r(3, 3)]);
s.add_region(r(2, 2));
assert_eq!(s.deref(), &[r(1, 1), r(2, 2), r(3, 3)]);
s.add_region(r(1, 1));
assert_eq!(s.deref(), &[r(1, 1), r(2, 2), r(3, 3)]);
}
#[test]
fn merge_region_caret() {
let mut s = Selection::new();
s.add_region(r(3, 5));
assert_eq!(s.deref(), &[r(3, 5)]);
s.add_region(r(3, 3));
assert_eq!(s.deref(), &[r(3, 5)]);
s.add_region(r(4, 4));
assert_eq!(s.deref(), &[r(3, 5)]);
s.add_region(r(5, 5));
assert_eq!(s.deref(), &[r(3, 5)]);
s.add_region(r(6, 6));
assert_eq!(s.deref(), &[r(3, 5), r(6, 6)]);
}
#[test]
fn merge_reverse() {
let mut s = Selection::new();
s.add_region(r(5, 3));
assert_eq!(s.deref(), &[r(5, 3)]);
s.add_region(r(9, 7));
assert_eq!(s.deref(), &[r(5, 3), r(9, 7)]);
s.add_region(r(3, 1));
assert_eq!(s.deref(), &[r(3, 1), r(5, 3), r(9, 7)]);
s.add_region(r(6, 4));
assert_eq!(s.deref(), &[r(3, 1), r(6, 3), r(9, 7)]);
s.add_region(r(8, 2));
assert_eq!(s.deref(), &[r(9, 1)]);
}
#[test]
fn apply_delta_outside_drift() {
let mut s = Selection::new();
s.add_region(r(0, 4));
s.add_region(r(4, 8));
assert_eq!(s.deref(), &[r(0, 4), r(4, 8)]);
// simulate outside edit between two adjacent selections
// like "texthere!" -> "text here!"
// the space should be outside the selections
let mut builder = DeltaBuilder::new("texthere!".len());
builder.replace(Interval::new(4, 4), " ".into());
let s2 = s.apply_delta(&builder.build(), true, InsertDrift::Outside);
assert_eq!(s2.deref(), &[r(0, 4), r(5, 9)]);
}
#[test]
fn apply_delta_inside_drift() {
let mut s = Selection::new();
s.add_region(r(1, 2));
assert_eq!(s.deref(), &[r(1, 2)]);
// simulate inside edit on either end of selection
// like "abc" -> "abbbc"
// if b was selected at beginning, inside edit should cause all bs to be selected after
let mut builder = DeltaBuilder::new("abc".len());
builder.replace(Interval::new(1, 1), "b".into());
builder.replace(Interval::new(2, 2), "b".into());
let s2 = s.apply_delta(&builder.build(), true, InsertDrift::Inside);
assert_eq!(s2.deref(), &[r(1, 4)]);
}
#[test]
fn apply_delta_drift_ignored_for_carets() {
let mut s = Selection::new();
s.add_region(r(1, 1));
assert_eq!(s.deref(), &[r(1, 1)]);
let mut builder = DeltaBuilder::new("ab".len());
builder.replace(Interval::new(1, 1), "b".into());
let s2 = s.apply_delta(&builder.build(), true, InsertDrift::Inside);
assert_eq!(s2.deref(), &[r(2, 2)]);
let mut builder = DeltaBuilder::new("ab".len());
builder.replace(Interval::new(1, 1), "b".into());
let s3 = s.apply_delta(&builder.build(), false, InsertDrift::Inside);
assert_eq!(s3.deref(), &[r(1, 1)]);
}
#[test]
fn display() {
let mut s = Selection::new();
s.add_region(r(1, 1));
assert_eq!(s.to_string(), "1|");
s.add_region(r(3, 5));
s.add_region(r(8, 6));
assert_eq!(s.to_string(), "[ 1|, 3..5|, |6..8 ]");
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/word_boundaries.rs | rust/core-lib/src/word_boundaries.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Segmentation of word boundaries. Note: this current implementation
//! is intended to work for code. Future work is to make it Unicode aware.
use xi_rope::{Cursor, Rope, RopeInfo};
pub struct WordCursor<'a> {
inner: Cursor<'a, RopeInfo>,
}
impl<'a> WordCursor<'a> {
pub fn new(text: &'a Rope, pos: usize) -> WordCursor<'a> {
let inner = Cursor::new(text, pos);
WordCursor { inner }
}
/// Get previous boundary, and set the cursor at the boundary found.
pub fn prev_boundary(&mut self) -> Option<usize> {
if let Some(ch) = self.inner.prev_codepoint() {
let mut prop = get_word_property(ch);
let mut candidate = self.inner.pos();
while let Some(prev) = self.inner.prev_codepoint() {
let prop_prev = get_word_property(prev);
if classify_boundary(prop_prev, prop).is_start() {
break;
}
prop = prop_prev;
candidate = self.inner.pos();
}
self.inner.set(candidate);
return Some(candidate);
}
None
}
/// Get next boundary, and set the cursor at the boundary found.
pub fn next_boundary(&mut self) -> Option<usize> {
if let Some(ch) = self.inner.next_codepoint() {
let mut prop = get_word_property(ch);
let mut candidate = self.inner.pos();
while let Some(next) = self.inner.next_codepoint() {
let prop_next = get_word_property(next);
if classify_boundary(prop, prop_next).is_end() {
break;
}
prop = prop_next;
candidate = self.inner.pos();
}
self.inner.set(candidate);
return Some(candidate);
}
None
}
/// Return the selection for the word containing the current cursor. The
/// cursor is moved to the end of that selection.
pub fn select_word(&mut self) -> (usize, usize) {
let initial = self.inner.pos();
let init_prop_after = self.inner.next_codepoint().map(get_word_property);
self.inner.set(initial);
let init_prop_before = self.inner.prev_codepoint().map(get_word_property);
let mut start = initial;
let init_boundary = if let (Some(pb), Some(pa)) = (init_prop_before, init_prop_after) {
classify_boundary_initial(pb, pa)
} else {
WordBoundary::Both
};
let mut prop_after = init_prop_after;
let mut prop_before = init_prop_before;
if prop_after.is_none() {
start = self.inner.pos();
prop_after = prop_before;
prop_before = self.inner.prev_codepoint().map(get_word_property);
}
while let (Some(pb), Some(pa)) = (prop_before, prop_after) {
if start == initial {
if init_boundary.is_start() {
break;
}
} else if !init_boundary.is_boundary() {
if classify_boundary(pb, pa).is_boundary() {
break;
}
} else if classify_boundary(pb, pa).is_start() {
break;
}
start = self.inner.pos();
prop_after = prop_before;
prop_before = self.inner.prev_codepoint().map(get_word_property);
}
self.inner.set(initial);
let mut end = initial;
prop_after = init_prop_after;
prop_before = init_prop_before;
if prop_before.is_none() {
prop_before = self.inner.next_codepoint().map(get_word_property);
end = self.inner.pos();
prop_after = self.inner.next_codepoint().map(get_word_property);
}
while let (Some(pb), Some(pa)) = (prop_before, prop_after) {
if end == initial {
if init_boundary.is_end() {
break;
}
} else if !init_boundary.is_boundary() {
if classify_boundary(pb, pa).is_boundary() {
break;
}
} else if classify_boundary(pb, pa).is_end() {
break;
}
end = self.inner.pos();
prop_before = prop_after;
prop_after = self.inner.next_codepoint().map(get_word_property);
}
self.inner.set(end);
(start, end)
}
}
#[derive(PartialEq, Eq)]
enum WordBoundary {
Interior,
Start, // a boundary indicating the end of a word
End, // a boundary indicating the start of a word
Both,
}
impl WordBoundary {
fn is_start(&self) -> bool {
*self == WordBoundary::Start || *self == WordBoundary::Both
}
fn is_end(&self) -> bool {
*self == WordBoundary::End || *self == WordBoundary::Both
}
fn is_boundary(&self) -> bool {
*self != WordBoundary::Interior
}
}
fn classify_boundary(prev: WordProperty, next: WordProperty) -> WordBoundary {
use self::WordBoundary::*;
use self::WordProperty::*;
match (prev, next) {
(Lf, _) => Both,
(_, Lf) => Both,
(Space, Other) => Start,
(Space, Punctuation) => Start,
(Punctuation, Other) => Start,
(Other, Space) => End,
(Punctuation, Space) => End,
(Other, Punctuation) => End,
_ => Interior,
}
}
fn classify_boundary_initial(prev: WordProperty, next: WordProperty) -> WordBoundary {
use self::WordBoundary::*;
use self::WordProperty::*;
match (prev, next) {
(Lf, Other) => Start,
(Other, Lf) => End,
(Lf, Space) => Interior,
(Lf, Punctuation) => Interior,
(Space, Lf) => Interior,
(Punctuation, Lf) => Interior,
(Space, Punctuation) => Interior,
(Punctuation, Space) => Interior,
_ => classify_boundary(prev, next),
}
}
#[derive(Copy, Clone)]
enum WordProperty {
Lf,
Space,
Punctuation,
Other, // includes letters and all of non-ascii unicode
}
fn get_word_property(codepoint: char) -> WordProperty {
if codepoint <= ' ' {
// TODO: deal with \r
if codepoint == '\n' {
return WordProperty::Lf;
}
return WordProperty::Space;
} else if codepoint <= '\u{3f}' {
// Hardcoded: !"#$%&'()*+,-./:;<=>?
if (0xfc00fffe00000000u64 >> (codepoint as u32)) & 1 != 0 {
return WordProperty::Punctuation;
}
} else if codepoint <= '\u{7f}' {
// Hardcoded: @[\]^`{|}~
if (0x7800000178000001u64 >> ((codepoint as u32) & 0x3f)) & 1 != 0 {
return WordProperty::Punctuation;
}
}
WordProperty::Other
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/rpc.rs | rust/core-lib/src/rpc.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The main RPC protocol, for communication between `xi-core` and the client.
//!
//! We rely on [Serde] for serialization and deserialization between
//! the JSON-RPC protocol and the types here.
//!
//! [Serde]: https://serde.rs
use std::path::PathBuf;
use serde::de::{self, Deserialize, Deserializer};
use serde::ser::{self, Serialize, Serializer};
use serde_json::{self, Value};
use crate::config::{ConfigDomainExternal, Table};
use crate::plugins::PlaceholderRpc;
use crate::syntax::LanguageId;
use crate::tabs::ViewId;
use crate::view::Size;
// =============================================================================
// Command types
// =============================================================================
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[doc(hidden)]
pub struct EmptyStruct {}
/// The notifications which make up the base of the protocol.
///
/// # Note
///
/// For serialization, all identifiers are converted to "snake_case".
///
/// # Examples
///
/// The `close_view` command:
///
/// ```
/// # extern crate xi_core_lib as xi_core;
/// extern crate serde_json;
/// use crate::xi_core::rpc::CoreNotification;
///
/// let json = r#"{
/// "method": "close_view",
/// "params": { "view_id": "view-id-1" }
/// }"#;
///
/// let cmd: CoreNotification = serde_json::from_str(&json).unwrap();
/// match cmd {
/// CoreNotification::CloseView { .. } => (), // expected
/// other => panic!("Unexpected variant"),
/// }
/// ```
///
/// The `client_started` command:
///
/// ```
/// # extern crate xi_core_lib as xi_core;
/// extern crate serde_json;
/// use crate::xi_core::rpc::CoreNotification;
///
/// let json = r#"{
/// "method": "client_started",
/// "params": {}
/// }"#;
///
/// let cmd: CoreNotification = serde_json::from_str(&json).unwrap();
/// match cmd {
/// CoreNotification::ClientStarted { .. } => (), // expected
/// other => panic!("Unexpected variant"),
/// }
/// ```
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
pub enum CoreNotification {
/// The 'edit' namespace, for view-specific editor actions.
///
/// The params object has internal `method` and `params` members,
/// which are parsed into the appropriate `EditNotification`.
///
/// # Note:
///
/// All edit commands (notifications and requests) include in their
/// inner params object a `view_id` field. On the xi-core side, we
/// pull out this value during parsing, and use it for routing.
///
/// For more on the edit commands, see [`EditNotification`] and
/// [`EditRequest`].
///
/// [`EditNotification`]: enum.EditNotification.html
/// [`EditRequest`]: enum.EditRequest.html
///
/// # Examples
///
/// ```
/// # extern crate xi_core_lib as xi_core;
/// #[macro_use]
/// extern crate serde_json;
/// use crate::xi_core::rpc::*;
/// # fn main() {
/// let edit = EditCommand {
/// view_id: 1.into(),
/// cmd: EditNotification::Insert { chars: "hello!".into() },
/// };
/// let rpc = CoreNotification::Edit(edit);
/// let expected = json!({
/// "method": "edit",
/// "params": {
/// "method": "insert",
/// "view_id": "view-id-1",
/// "params": {
/// "chars": "hello!",
/// }
/// }
/// });
/// assert_eq!(serde_json::to_value(&rpc).unwrap(), expected);
/// # }
/// ```
Edit(EditCommand<EditNotification>),
/// The 'plugin' namespace, for interacting with plugins.
///
/// As with edit commands, the params object has is a nested RPC,
/// with the name of the command included as the `command` field.
///
/// (this should be changed to more accurately reflect the behaviour
/// of the edit commands).
///
/// For the available commands, see [`PluginNotification`].
///
/// [`PluginNotification`]: enum.PluginNotification.html
///
/// # Examples
///
/// ```
/// # extern crate xi_core_lib as xi_core;
/// #[macro_use]
/// extern crate serde_json;
/// use crate::xi_core::rpc::*;
/// # fn main() {
/// let rpc = CoreNotification::Plugin(
/// PluginNotification::Start {
/// view_id: 1.into(),
/// plugin_name: "syntect".into(),
/// });
///
/// let expected = json!({
/// "method": "plugin",
/// "params": {
/// "command": "start",
/// "view_id": "view-id-1",
/// "plugin_name": "syntect",
/// }
/// });
/// assert_eq!(serde_json::to_value(&rpc).unwrap(), expected);
/// # }
/// ```
Plugin(PluginNotification),
/// Tells `xi-core` to close the specified view.
CloseView { view_id: ViewId },
/// Tells `xi-core` to save the contents of the specified view's
/// buffer to the specified path.
Save { view_id: ViewId, file_path: String },
/// Tells `xi-core` to set the theme.
SetTheme { theme_name: String },
/// Notifies `xi-core` that the client has started.
ClientStarted {
#[serde(default)]
config_dir: Option<PathBuf>,
/// Path to additional plugins, included by the client.
#[serde(default)]
client_extras_dir: Option<PathBuf>,
},
/// Updates the user's config for the given domain. Where keys in
/// `changes` are `null`, those keys are cleared in the user config
/// for that domain; otherwise the config is updated with the new
/// value.
///
/// Note: If the client is using file-based config, the only valid
/// domain argument is `ConfigDomain::UserOverride(_)`, which
/// represents non-persistent view-specific settings, such as when
/// a user manually changes whitespace settings for a given view.
ModifyUserConfig { domain: ConfigDomainExternal, changes: Table },
/// Control whether the tracing infrastructure is enabled.
/// This propagates to all peers that should respond by toggling its own
/// infrastructure on/off.
TracingConfig { enabled: bool },
/// Save trace data to the given path. The core will first send
/// CoreRequest::CollectTrace to all peers to collect the samples.
SaveTrace { destination: PathBuf, frontend_samples: Value },
/// Tells `xi-core` to set the language id for the view.
SetLanguage { view_id: ViewId, language_id: LanguageId },
}
/// The requests which make up the base of the protocol.
///
/// All requests expect a response.
///
/// # Examples
///
/// The `new_view` command:
///
/// ```
/// # extern crate xi_core_lib as xi_core;
/// extern crate serde_json;
/// use crate::xi_core::rpc::CoreRequest;
///
/// let json = r#"{
/// "method": "new_view",
/// "params": { "file_path": "~/my_very_fun_file.rs" }
/// }"#;
///
/// let cmd: CoreRequest = serde_json::from_str(&json).unwrap();
/// match cmd {
/// CoreRequest::NewView { .. } => (), // expected
/// other => panic!("Unexpected variant {:?}", other),
/// }
/// ```
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
pub enum CoreRequest {
/// The 'edit' namespace, for view-specific requests.
Edit(EditCommand<EditRequest>),
/// Tells `xi-core` to create a new view. If the `file_path`
/// argument is present, `xi-core` should attempt to open the file
/// at that location.
///
/// Returns the view identifier that should be used to interact
/// with the newly created view.
NewView { file_path: Option<String> },
/// Returns the current collated config object for the given view.
GetConfig { view_id: ViewId },
/// Returns the contents of the buffer for a given `ViewId`.
/// In the future this might also be used to return structured data (such
/// as for printing).
DebugGetContents { view_id: ViewId },
}
/// A helper type, which extracts the `view_id` field from edit
/// requests and notifications.
///
/// Edit requests and notifications have 'method', 'params', and
/// 'view_id' param members. We use this wrapper, which has custom
/// `Deserialize` and `Serialize` implementations, to pull out the
/// `view_id` field.
///
/// # Examples
///
/// ```
/// # extern crate xi_core_lib as xi_core;
/// extern crate serde_json;
/// use crate::xi_core::rpc::*;
///
/// let json = r#"{
/// "view_id": "view-id-1",
/// "method": "scroll",
/// "params": [0, 6]
/// }"#;
///
/// let cmd: EditCommand<EditNotification> = serde_json::from_str(&json).unwrap();
/// match cmd.cmd {
/// EditNotification::Scroll( .. ) => (), // expected
/// other => panic!("Unexpected variant {:?}", other),
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct EditCommand<T> {
pub view_id: ViewId,
pub cmd: T,
}
/// The smallest unit of text that a gesture can select
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone)]
#[serde(rename_all = "snake_case")]
pub enum SelectionGranularity {
/// Selects any point or character range
Point,
/// Selects one word at a time
Word,
/// Selects one line at a time
Line,
}
/// An enum representing touch and mouse gestures applied to the text.
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Copy, Clone)]
#[serde(rename_all = "snake_case")]
pub enum GestureType {
Select { granularity: SelectionGranularity, multi: bool },
SelectExtend { granularity: SelectionGranularity },
Drag,
// Deprecated
PointSelect,
ToggleSel,
RangeSelect,
LineSelect,
WordSelect,
MultiLineSelect,
MultiWordSelect,
}
/// An inclusive range.
///
/// # Note:
///
/// Several core protocol commands use a params array to pass arguments
/// which are named, internally. this type use custom Serialize /
/// Deserialize impls to accommodate this.
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct LineRange {
pub first: i64,
pub last: i64,
}
/// A mouse event. See the note for [`LineRange`].
///
/// [`LineRange`]: enum.LineRange.html
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct MouseAction {
pub line: u64,
pub column: u64,
pub flags: u64,
pub click_count: Option<u64>,
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
pub struct Position {
pub line: usize,
pub column: usize,
}
/// Represents how the current selection is modified (used by find
/// operations).
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub enum SelectionModifier {
None,
Set,
Add,
AddRemovingCurrent,
}
impl Default for SelectionModifier {
fn default() -> SelectionModifier {
SelectionModifier::Set
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub struct FindQuery {
pub id: Option<usize>,
pub chars: String,
pub case_sensitive: bool,
#[serde(default)]
pub regex: bool,
#[serde(default)]
pub whole_words: bool,
}
/// The edit-related notifications.
///
/// Alongside the [`EditRequest`] members, these commands constitute
/// the API for interacting with a particular window and document.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
pub enum EditNotification {
Insert {
chars: String,
},
Paste {
chars: String,
},
DeleteForward,
DeleteBackward,
DeleteWordForward,
DeleteWordBackward,
DeleteToEndOfParagraph,
DeleteToBeginningOfLine,
InsertNewline,
InsertTab,
MoveUp,
MoveUpAndModifySelection,
MoveDown,
MoveDownAndModifySelection,
MoveLeft,
// synoynm for `MoveLeft`
MoveBackward,
MoveLeftAndModifySelection,
MoveRight,
// synoynm for `MoveRight`
MoveForward,
MoveRightAndModifySelection,
MoveWordLeft,
MoveWordLeftAndModifySelection,
MoveWordRight,
MoveWordRightAndModifySelection,
MoveToBeginningOfParagraph,
MoveToBeginningOfParagraphAndModifySelection,
MoveToEndOfParagraph,
MoveToEndOfParagraphAndModifySelection,
MoveToLeftEndOfLine,
MoveToLeftEndOfLineAndModifySelection,
MoveToRightEndOfLine,
MoveToRightEndOfLineAndModifySelection,
MoveToBeginningOfDocument,
MoveToBeginningOfDocumentAndModifySelection,
MoveToEndOfDocument,
MoveToEndOfDocumentAndModifySelection,
ScrollPageUp,
PageUpAndModifySelection,
ScrollPageDown,
PageDownAndModifySelection,
SelectAll,
AddSelectionAbove,
AddSelectionBelow,
Scroll(LineRange),
Resize(Size),
GotoLine {
line: u64,
},
RequestLines(LineRange),
Yank,
Transpose,
Click(MouseAction),
Drag(MouseAction),
Gesture {
line: u64,
col: u64,
ty: GestureType,
},
Undo,
Redo,
Find {
chars: String,
case_sensitive: bool,
#[serde(default)]
regex: bool,
#[serde(default)]
whole_words: bool,
},
MultiFind {
queries: Vec<FindQuery>,
},
FindNext {
#[serde(default)]
wrap_around: bool,
#[serde(default)]
allow_same: bool,
#[serde(default)]
modify_selection: SelectionModifier,
},
FindPrevious {
#[serde(default)]
wrap_around: bool,
#[serde(default)]
allow_same: bool,
#[serde(default)]
modify_selection: SelectionModifier,
},
FindAll,
DebugRewrap,
DebugWrapWidth,
/// Prints the style spans present in the active selection.
DebugPrintSpans,
DebugToggleComment,
Uppercase,
Lowercase,
Capitalize,
Reindent,
Indent,
Outdent,
/// Indicates whether find highlights should be rendered
HighlightFind {
visible: bool,
},
SelectionForFind {
#[serde(default)]
case_sensitive: bool,
},
Replace {
chars: String,
#[serde(default)]
preserve_case: bool,
},
ReplaceNext,
ReplaceAll,
SelectionForReplace,
RequestHover {
request_id: usize,
position: Option<Position>,
},
SelectionIntoLines,
DuplicateLine,
IncreaseNumber,
DecreaseNumber,
ToggleRecording {
recording_name: Option<String>,
},
PlayRecording {
recording_name: String,
},
ClearRecording {
recording_name: String,
},
CollapseSelections,
}
/// The edit related requests.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
pub enum EditRequest {
/// Cuts the active selection, returning their contents,
/// or `Null` if the selection was empty.
Cut,
/// Copies the active selection, returning their contents or
/// or `Null` if the selection was empty.
Copy,
}
/// The plugin related notifications.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(tag = "command")]
#[serde(rename_all = "snake_case")]
pub enum PluginNotification {
Start { view_id: ViewId, plugin_name: String },
Stop { view_id: ViewId, plugin_name: String },
PluginRpc { view_id: ViewId, receiver: String, rpc: PlaceholderRpc },
}
// Serialize / Deserialize
impl<T: Serialize> Serialize for EditCommand<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut v = serde_json::to_value(&self.cmd).map_err(ser::Error::custom)?;
v["view_id"] = json!(self.view_id);
v.serialize(serializer)
}
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for EditCommand<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct InnerId {
view_id: ViewId,
}
let mut v = Value::deserialize(deserializer)?;
let helper = InnerId::deserialize(&v).map_err(de::Error::custom)?;
let InnerId { view_id } = helper;
// if params are empty, remove them
let remove_params = match v.get("params") {
Some(&Value::Object(ref obj)) => obj.is_empty() && T::deserialize(v.clone()).is_err(),
Some(&Value::Array(ref arr)) => arr.is_empty() && T::deserialize(v.clone()).is_err(),
Some(_) => {
return Err(de::Error::custom(
"'params' field, if present, must be object or array.",
));
}
None => false,
};
if remove_params {
v.as_object_mut().map(|v| v.remove("params"));
}
let cmd = T::deserialize(v).map_err(de::Error::custom)?;
Ok(EditCommand { view_id, cmd })
}
}
impl Serialize for MouseAction {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
#[derive(Serialize)]
struct Helper(u64, u64, u64, Option<u64>);
let as_tup = Helper(self.line, self.column, self.flags, self.click_count);
as_tup.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for MouseAction {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let v: Vec<u64> = Vec::deserialize(deserializer)?;
let click_count = if v.len() == 4 { Some(v[3]) } else { None };
Ok(MouseAction { line: v[0], column: v[1], flags: v[2], click_count })
}
}
impl Serialize for LineRange {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let as_tup = (self.first, self.last);
as_tup.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for LineRange {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct TwoTuple(i64, i64);
let tup = TwoTuple::deserialize(deserializer)?;
Ok(LineRange { first: tup.0, last: tup.1 })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tabs::ViewId;
#[test]
fn test_serialize_edit_command() {
// Ensure that an EditCommand can be serialized and then correctly deserialized.
let message: String = "hello world".into();
let edit = EditCommand {
view_id: ViewId(1),
cmd: EditNotification::Insert { chars: message.clone() },
};
let json = serde_json::to_string(&edit).unwrap();
let cmd: EditCommand<EditNotification> = serde_json::from_str(&json).unwrap();
assert_eq!(cmd.view_id, edit.view_id);
if let EditNotification::Insert { chars } = cmd.cmd {
assert_eq!(chars, message);
}
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/edit_ops.rs | rust/core-lib/src/edit_ops.rs | // Copyright 2020 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Functions for editing ropes.
use std::borrow::Cow;
use std::collections::BTreeSet;
use xi_rope::{Cursor, DeltaBuilder, Interval, LinesMetric, Rope, RopeDelta};
use crate::backspace::offset_for_delete_backwards;
use crate::config::BufferItems;
use crate::line_offset::{LineOffset, LogicalLines};
use crate::linewrap::Lines;
use crate::movement::{region_movement, Movement};
use crate::selection::{SelRegion, Selection};
use crate::word_boundaries::WordCursor;
#[derive(Debug, Copy, Clone)]
pub enum IndentDirection {
In,
Out,
}
/// Replaces the selection with the text `T`.
pub fn insert<T: Into<Rope>>(base: &Rope, regions: &[SelRegion], text: T) -> RopeDelta {
let rope = text.into();
let mut builder = DeltaBuilder::new(base.len());
for region in regions {
let iv = Interval::new(region.min(), region.max());
builder.replace(iv, rope.clone());
}
builder.build()
}
/// Leaves the current selection untouched, but surrounds it with two insertions.
pub fn surround<BT, AT>(
base: &Rope,
regions: &[SelRegion],
before_text: BT,
after_text: AT,
) -> RopeDelta
where
BT: Into<Rope>,
AT: Into<Rope>,
{
let mut builder = DeltaBuilder::new(base.len());
let before_rope = before_text.into();
let after_rope = after_text.into();
for region in regions {
let before_iv = Interval::new(region.min(), region.min());
builder.replace(before_iv, before_rope.clone());
let after_iv = Interval::new(region.max(), region.max());
builder.replace(after_iv, after_rope.clone());
}
builder.build()
}
pub fn duplicate_line(base: &Rope, regions: &[SelRegion], config: &BufferItems) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
// get affected lines or regions
let mut to_duplicate = BTreeSet::new();
for region in regions {
let (first_line, _) = LogicalLines.offset_to_line_col(base, region.min());
let line_start = LogicalLines.offset_of_line(base, first_line);
let mut cursor = match region.is_caret() {
true => Cursor::new(base, line_start),
false => {
// duplicate all lines together that are part of the same selections
let (last_line, _) = LogicalLines.offset_to_line_col(base, region.max());
let line_end = LogicalLines.offset_of_line(base, last_line);
Cursor::new(base, line_end)
}
};
if let Some(line_end) = cursor.next::<LinesMetric>() {
to_duplicate.insert((line_start, line_end));
}
}
for (start, end) in to_duplicate {
// insert duplicates
let iv = Interval::new(start, start);
builder.replace(iv, base.slice(start..end));
// last line does not have new line character so it needs to be manually added
if end == base.len() {
builder.replace(iv, Rope::from(&config.line_ending))
}
}
builder.build()
}
/// Used when the user presses the backspace key. If no delta is returned, then nothing changes.
pub fn delete_backward(base: &Rope, regions: &[SelRegion], config: &BufferItems) -> RopeDelta {
// TODO: this function is workable but probably overall code complexity
// could be improved by implementing a "backspace" movement instead.
let mut builder = DeltaBuilder::new(base.len());
for region in regions {
let start = offset_for_delete_backwards(region, base, config);
let iv = Interval::new(start, region.max());
if !iv.is_empty() {
builder.delete(iv);
}
}
builder.build()
}
/// Common logic for a number of delete methods. For each region in the
/// selection, if the selection is a caret, delete the region between
/// the caret and the movement applied to the caret, otherwise delete
/// the region.
///
/// If `save` is set, the tuple will contain a rope with the deleted text.
///
/// # Arguments
///
/// * `height` - viewport height
pub(crate) fn delete_by_movement(
base: &Rope,
regions: &[SelRegion],
lines: &Lines,
movement: Movement,
height: usize,
save: bool,
) -> (RopeDelta, Option<Rope>) {
// We compute deletions as a selection because the merge logic
// is convenient. Another possibility would be to make the delta
// builder able to handle overlapping deletions (with union semantics).
let mut deletions = Selection::new();
for &r in regions {
if r.is_caret() {
let new_region = region_movement(movement, r, lines, height, base, true);
deletions.add_region(new_region);
} else {
deletions.add_region(r);
}
}
let kill_ring = if save {
let saved = extract_sel_regions(base, &deletions).unwrap_or_default();
Some(Rope::from(saved))
} else {
None
};
(delete_sel_regions(base, &deletions), kill_ring)
}
/// Deletes the given regions.
pub(crate) fn delete_sel_regions(base: &Rope, sel_regions: &[SelRegion]) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for region in sel_regions {
let iv = Interval::new(region.min(), region.max());
if !iv.is_empty() {
builder.delete(iv);
}
}
builder.build()
}
/// Extracts non-caret selection regions into a string,
/// joining multiple regions with newlines.
pub(crate) fn extract_sel_regions<'a>(
base: &'a Rope,
sel_regions: &[SelRegion],
) -> Option<Cow<'a, str>> {
let mut saved = None;
for region in sel_regions {
if !region.is_caret() {
let val = base.slice_to_cow(region);
match saved {
None => saved = Some(val),
Some(ref mut s) => {
s.to_mut().push('\n');
s.to_mut().push_str(&val);
}
}
}
}
saved
}
pub fn insert_newline(base: &Rope, regions: &[SelRegion], config: &BufferItems) -> RopeDelta {
insert(base, regions, &config.line_ending)
}
pub fn insert_tab(base: &Rope, regions: &[SelRegion], config: &BufferItems) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
let const_tab_text = get_tab_text(config, None);
for region in regions {
let line_range = LogicalLines.get_line_range(base, region);
if line_range.len() > 1 {
for line in line_range {
let offset = LogicalLines.line_col_to_offset(base, line, 0);
let iv = Interval::new(offset, offset);
builder.replace(iv, Rope::from(const_tab_text));
}
} else {
let (_, col) = LogicalLines.offset_to_line_col(base, region.start);
let mut tab_size = config.tab_size;
tab_size = tab_size - (col % tab_size);
let tab_text = get_tab_text(config, Some(tab_size));
let iv = Interval::new(region.min(), region.max());
builder.replace(iv, Rope::from(tab_text));
}
}
builder.build()
}
/// Indents or outdents lines based on selection and user's tab settings.
/// Uses a BTreeSet to holds the collection of lines to modify.
/// Preserves cursor position and current selection as much as possible.
/// Tries to have behavior consistent with other editors like Atom,
/// Sublime and VSCode, with non-caret selections not being modified.
pub fn modify_indent(
base: &Rope,
regions: &[SelRegion],
config: &BufferItems,
direction: IndentDirection,
) -> RopeDelta {
let mut lines = BTreeSet::new();
let tab_text = get_tab_text(config, None);
for region in regions {
let line_range = LogicalLines.get_line_range(base, region);
for line in line_range {
lines.insert(line);
}
}
match direction {
IndentDirection::In => indent(base, lines, tab_text),
IndentDirection::Out => outdent(base, lines, tab_text),
}
}
fn indent(base: &Rope, lines: BTreeSet<usize>, tab_text: &str) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for line in lines {
let offset = LogicalLines.line_col_to_offset(base, line, 0);
let interval = Interval::new(offset, offset);
builder.replace(interval, Rope::from(tab_text));
}
builder.build()
}
fn outdent(base: &Rope, lines: BTreeSet<usize>, tab_text: &str) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for line in lines {
let offset = LogicalLines.line_col_to_offset(base, line, 0);
let tab_offset = LogicalLines.line_col_to_offset(base, line, tab_text.len());
let interval = Interval::new(offset, tab_offset);
let leading_slice = base.slice_to_cow(interval.start()..interval.end());
if leading_slice == tab_text {
builder.delete(interval);
} else if let Some(first_char_col) = leading_slice.find(|c: char| !c.is_whitespace()) {
let first_char_offset = LogicalLines.line_col_to_offset(base, line, first_char_col);
let interval = Interval::new(offset, first_char_offset);
builder.delete(interval);
}
}
builder.build()
}
pub fn transpose(base: &Rope, regions: &[SelRegion]) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
let mut last = 0;
let mut optional_previous_selection: Option<(Interval, Rope)> =
last_selection_region(regions).map(|®ion| sel_region_to_interval_and_rope(base, region));
for ®ion in regions {
if region.is_caret() {
let mut middle = region.end;
let mut start = base.prev_grapheme_offset(middle).unwrap_or(0);
let mut end = base.next_grapheme_offset(middle).unwrap_or(middle);
// Note: this matches Emac's behavior. It swaps last
// two characters of line if at end of line.
if start >= last {
let end_line_offset =
LogicalLines.offset_of_line(base, LogicalLines.line_of_offset(base, end));
// include end != base.len() because if the editor is entirely empty, we dont' want to pull from empty space
if (end == middle || end == end_line_offset) && end != base.len() {
middle = start;
start = base.prev_grapheme_offset(middle).unwrap_or(0);
end = middle.wrapping_add(1);
}
let interval = Interval::new(start, end);
let before = base.slice_to_cow(start..middle);
let after = base.slice_to_cow(middle..end);
let swapped: String = [after, before].concat();
builder.replace(interval, Rope::from(swapped));
last = end;
}
} else if let Some(previous_selection) = optional_previous_selection {
let current_interval = sel_region_to_interval_and_rope(base, region);
builder.replace(current_interval.0, previous_selection.1);
optional_previous_selection = Some(current_interval);
}
}
builder.build()
}
pub fn transform_text<F: Fn(&str) -> String>(
base: &Rope,
regions: &[SelRegion],
transform_function: F,
) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for region in regions {
let selected_text = base.slice_to_cow(region);
let interval = Interval::new(region.min(), region.max());
builder.replace(interval, Rope::from(transform_function(&selected_text)));
}
builder.build()
}
/// Changes the number(s) under the cursor(s) with the `transform_function`.
/// If there is a number next to or on the beginning of the region, then
/// this number will be replaced with the result of `transform_function` and
/// the cursor will be placed at the end of the number.
/// Some Examples with a increment `transform_function`:
///
/// "|1234" -> "1235|"
/// "12|34" -> "1235|"
/// "-|12" -> "-11|"
/// "another number is 123|]" -> "another number is 124"
///
/// This function also works fine with multiple regions.
pub fn change_number<F: Fn(i128) -> Option<i128>>(
base: &Rope,
regions: &[SelRegion],
transform_function: F,
) -> RopeDelta {
let mut builder = DeltaBuilder::new(base.len());
for region in regions {
let mut cursor = WordCursor::new(base, region.end);
let (mut start, end) = cursor.select_word();
// if the word begins with '-', then it is a negative number
if start > 0 && base.byte_at(start - 1) == (b'-') {
start -= 1;
}
let word = base.slice_to_cow(start..end);
if let Some(number) = word.parse::<i128>().ok().and_then(&transform_function) {
let interval = Interval::new(start, end);
builder.replace(interval, Rope::from(number.to_string()));
}
}
builder.build()
}
// capitalization behaviour is similar to behaviour in XCode
pub fn capitalize_text(base: &Rope, regions: &[SelRegion]) -> (RopeDelta, Selection) {
let mut builder = DeltaBuilder::new(base.len());
let mut final_selection = Selection::new();
for ®ion in regions {
final_selection.add_region(SelRegion::new(region.max(), region.max()));
let mut word_cursor = WordCursor::new(base, region.min());
loop {
// capitalize each word in the current selection
let (start, end) = word_cursor.select_word();
if start < end {
let interval = Interval::new(start, end);
let word = base.slice_to_cow(start..end);
// first letter is uppercase, remaining letters are lowercase
let (first_char, rest) = word.split_at(1);
let capitalized_text = [first_char.to_uppercase(), rest.to_lowercase()].concat();
builder.replace(interval, Rope::from(capitalized_text));
}
if word_cursor.next_boundary().is_none() || end > region.max() {
break;
}
}
}
(builder.build(), final_selection)
}
fn sel_region_to_interval_and_rope(base: &Rope, region: SelRegion) -> (Interval, Rope) {
let as_interval = Interval::new(region.min(), region.max());
let interval_rope = base.subseq(as_interval);
(as_interval, interval_rope)
}
fn last_selection_region(regions: &[SelRegion]) -> Option<&SelRegion> {
for region in regions.iter().rev() {
if !region.is_caret() {
return Some(region);
}
}
None
}
fn get_tab_text(config: &BufferItems, tab_size: Option<usize>) -> &'static str {
let tab_size = tab_size.unwrap_or(config.tab_size);
let tab_text = if config.translate_tabs_to_spaces { n_spaces(tab_size) } else { "\t" };
tab_text
}
fn n_spaces(n: usize) -> &'static str {
let spaces = " ";
assert!(n <= spaces.len());
&spaces[..n]
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/width_cache.rs | rust/core-lib/src/width_cache.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Cache and utilities for doing width measurement.
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use crate::client::Client;
/// A token which can be used to retrieve an actual width value when the
/// batch request is submitted.
///
/// Internally, it is implemented as an index into the `widths` array.
pub type Token = usize;
/// A measured width, in px units.
type Width = f64;
type StyleId = usize;
pub struct WidthCache {
/// maps cache key to index within widths
m: HashMap<WidthCacheKey<'static>, Token>,
widths: Vec<Width>,
}
#[derive(Eq, PartialEq, Hash)]
struct WidthCacheKey<'a> {
id: StyleId,
s: Cow<'a, str>,
}
/// A batched request, so that a number of strings can be measured in a
/// a single RPC.
pub struct WidthBatchReq<'a> {
cache: &'a mut WidthCache,
pending_tok: Token,
req: Vec<WidthReq>,
req_toks: Vec<Vec<Token>>,
// maps style id to index into req/req_toks
req_ids: BTreeMap<StyleId, Token>,
}
/// A request for measuring the widths of strings all of the same style
/// (a request from core to front-end).
#[derive(Serialize, Deserialize)]
pub struct WidthReq {
pub id: StyleId,
pub strings: Vec<String>,
}
/// The response for a batch of [`WidthReq`]s.
pub type WidthResponse = Vec<Vec<Width>>;
/// A trait for types that provide width measurement. In the general case this
/// will be provided by the frontend, but alternative implementations might
/// be provided for faster measurement of 'fixed-width' fonts, or for testing.
pub trait WidthMeasure {
fn measure_width(&self, request: &[WidthReq]) -> Result<WidthResponse, xi_rpc::Error>;
}
impl WidthMeasure for Client {
fn measure_width(&self, request: &[WidthReq]) -> Result<WidthResponse, xi_rpc::Error> {
Client::measure_width(self, request)
}
}
/// A measure in which each codepoint has width of 1.
pub struct CodepointMono;
impl WidthMeasure for CodepointMono {
/// In which each codepoint has width == 1.
fn measure_width(&self, request: &[WidthReq]) -> Result<WidthResponse, xi_rpc::Error> {
Ok(request
.iter()
.map(|r| r.strings.iter().map(|s| s.chars().count() as f64).collect())
.collect())
}
}
impl WidthCache {
pub fn new() -> WidthCache {
WidthCache { m: HashMap::new(), widths: Vec::new() }
}
/// Returns the number of items currently in the cache.
pub(crate) fn len(&self) -> usize {
self.m.len()
}
/// Resolve a previously obtained token into a width value.
pub fn resolve(&self, tok: Token) -> Width {
self.widths[tok]
}
/// Create a new batch of requests.
pub fn batch_req(self: &mut WidthCache) -> WidthBatchReq {
let pending_tok = self.widths.len();
WidthBatchReq {
cache: self,
pending_tok,
req: Vec::new(),
req_toks: Vec::new(),
req_ids: BTreeMap::new(),
}
}
}
impl<'a> WidthBatchReq<'a> {
/// Request measurement of one string/style pair within the batch.
pub fn request(&mut self, id: StyleId, s: &str) -> Token {
let key = WidthCacheKey { id, s: Cow::Borrowed(s) };
if let Some(tok) = self.cache.m.get(&key) {
return *tok;
}
// cache miss, add the request
let key = WidthCacheKey { id, s: Cow::Owned(s.to_owned()) };
let req = &mut self.req;
let req_toks = &mut self.req_toks;
let id_off = *self.req_ids.entry(id).or_insert_with(|| {
let id_off = req.len();
req.push(WidthReq { id, strings: Vec::new() });
req_toks.push(Vec::new());
id_off
});
// To avoid this second clone, we could potentially do a tricky thing where
// we extract the strings from the WidthReq. Probably not worth it though.
req[id_off].strings.push(s.to_owned());
let tok = self.pending_tok;
self.cache.m.insert(key, tok);
self.pending_tok += 1;
req_toks[id_off].push(tok);
tok
}
/// Resolves pending measurements to concrete widths using the provided [`WidthMeasure`].
/// On success, the tokens given by `request` will resolve in the cache.
pub fn resolve_pending<T: WidthMeasure + ?Sized>(
&mut self,
handler: &T,
) -> Result<(), xi_rpc::Error> {
// The 0.0 values should all get replaced with actual widths, assuming the
// shape of the response from the front-end matches that of the request.
if self.pending_tok > self.cache.widths.len() {
self.cache.widths.resize(self.pending_tok, 0.0);
let widths = handler.measure_width(&self.req)?;
for (w, t) in widths.iter().zip(self.req_toks.iter()) {
for (width, tok) in w.iter().zip(t.iter()) {
self.cache.widths[*tok] = *width;
}
}
}
Ok(())
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/line_offset.rs | rust/core-lib/src/line_offset.rs | // Copyright 2020 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(clippy::range_plus_one)]
use std::ops::Range;
use xi_rope::Rope;
use crate::linewrap::Lines;
use crate::selection::SelRegion;
/// A trait from which lines and columns in a document can be calculated
/// into offsets inside a rope an vice versa.
pub trait LineOffset {
// use own breaks if present, or text if not (no line wrapping)
/// Returns the byte offset corresponding to the given line.
fn offset_of_line(&self, text: &Rope, line: usize) -> usize {
text.offset_of_line(line)
}
/// Returns the visible line number containing the given offset.
fn line_of_offset(&self, text: &Rope, offset: usize) -> usize {
text.line_of_offset(offset)
}
// How should we count "column"? Valid choices include:
// * Unicode codepoints
// * grapheme clusters
// * Unicode width (so CJK counts as 2)
// * Actual measurement in text layout
// * Code units in some encoding
//
// Of course, all these are identical for ASCII. For now we use UTF-8 code units
// for simplicity.
fn offset_to_line_col(&self, text: &Rope, offset: usize) -> (usize, usize) {
let line = self.line_of_offset(text, offset);
(line, offset - self.offset_of_line(text, line))
}
fn line_col_to_offset(&self, text: &Rope, line: usize, col: usize) -> usize {
let mut offset = self.offset_of_line(text, line).saturating_add(col);
if offset >= text.len() {
offset = text.len();
if self.line_of_offset(text, offset) <= line {
return offset;
}
} else {
// Snap to grapheme cluster boundary
offset = text.prev_grapheme_offset(offset + 1).unwrap();
}
// clamp to end of line
let next_line_offset = self.offset_of_line(text, line + 1);
if offset >= next_line_offset {
if let Some(prev) = text.prev_grapheme_offset(next_line_offset) {
offset = prev;
}
}
offset
}
/// Get the line range of a selected region.
fn get_line_range(&self, text: &Rope, region: &SelRegion) -> Range<usize> {
let (first_line, _) = self.offset_to_line_col(text, region.min());
let (mut last_line, last_col) = self.offset_to_line_col(text, region.max());
if last_col == 0 && last_line > first_line {
last_line -= 1;
}
first_line..(last_line + 1)
}
}
/// A struct from which the default definitions for `offset_of_line`
/// and `line_of_offset` can be accessed, and think in logical lines.
pub struct LogicalLines;
impl LineOffset for LogicalLines {}
impl LineOffset for xi_rope::breaks::Breaks {
fn offset_of_line(&self, _text: &Rope, line: usize) -> usize {
self.count_base_units::<xi_rope::breaks::BreaksMetric>(line)
}
fn line_of_offset(&self, text: &Rope, offset: usize) -> usize {
let offset = offset.min(text.len());
self.count::<xi_rope::breaks::BreaksMetric>(offset)
}
}
impl LineOffset for Lines {
fn offset_of_line(&self, text: &Rope, line: usize) -> usize {
self.offset_of_visual_line(text, line)
}
fn line_of_offset(&self, text: &Rope, offset: usize) -> usize {
self.visual_line_of_offset(text, offset)
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/movement.rs | rust/core-lib/src/movement.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Representation and calculation of movement within a lineoffset.
use std::cmp::max;
use crate::line_offset::LineOffset;
use crate::selection::{HorizPos, SelRegion, Selection};
use crate::word_boundaries::WordCursor;
use xi_rope::{Cursor, LinesMetric, Rope};
/// The specification of a movement.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Movement {
/// Move to the left by one grapheme cluster.
Left,
/// Move to the right by one grapheme cluster.
Right,
/// Move to the left by one word.
LeftWord,
/// Move to the right by one word.
RightWord,
/// Move to left end of visible line.
LeftOfLine,
/// Move to right end of visible line.
RightOfLine,
/// Move up one visible line.
Up,
/// Move down one visible line.
Down,
/// Move up one viewport height.
UpPage,
/// Move down one viewport height.
DownPage,
/// Move up to the next line that can preserve the cursor position.
UpExactPosition,
/// Move down to the next line that can preserve the cursor position.
DownExactPosition,
/// Move to the start of the text line.
StartOfParagraph,
/// Move to the end of the text line.
EndOfParagraph,
/// Move to the end of the text line, or next line if already at end.
EndOfParagraphKill,
/// Move to the start of the document.
StartOfDocument,
/// Move to the end of the document
EndOfDocument,
}
/// Compute movement based on vertical motion by the given number of lines.
///
/// Note: in non-exceptional cases, this function preserves the `horiz`
/// field of the selection region.
fn vertical_motion(
r: SelRegion,
lo: &dyn LineOffset,
text: &Rope,
line_delta: isize,
modify: bool,
) -> (usize, Option<HorizPos>) {
let (col, line) = selection_position(r, lo, text, line_delta < 0, modify);
let n_lines = lo.line_of_offset(text, text.len());
// This code is quite careful to avoid integer overflow.
// TODO: write tests to verify
if line_delta < 0 && (-line_delta as usize) > line {
return (0, Some(col));
}
let line = if line_delta < 0 {
line - (-line_delta as usize)
} else {
line.saturating_add(line_delta as usize)
};
if line > n_lines {
return (text.len(), Some(col));
}
let new_offset = lo.line_col_to_offset(text, line, col);
(new_offset, Some(col))
}
/// Compute movement based on vertical motion by the given number of lines skipping
/// any line that is shorter than the current cursor position.
fn vertical_motion_exact_pos(
r: SelRegion,
lo: &dyn LineOffset,
text: &Rope,
move_up: bool,
modify: bool,
) -> (usize, Option<HorizPos>) {
let (col, init_line) = selection_position(r, lo, text, move_up, modify);
let n_lines = lo.line_of_offset(text, text.len());
let mut line_length =
lo.offset_of_line(text, init_line.saturating_add(1)) - lo.offset_of_line(text, init_line);
if move_up && init_line == 0 {
return (lo.line_col_to_offset(text, init_line, col), Some(col));
}
let mut line = if move_up { init_line - 1 } else { init_line.saturating_add(1) };
// If the active columns is longer than the current line, use the current line length.
let col = if line_length < col { line_length - 1 } else { col };
loop {
line_length = lo.offset_of_line(text, line + 1) - lo.offset_of_line(text, line);
// If the line is longer than the current cursor position, break.
// We use > instead of >= because line_length includes newline.
if line_length > col {
break;
}
// If you are trying to add a selection past the end of the file or before the first line, return original selection
if line >= n_lines || (line == 0 && move_up) {
line = init_line;
break;
}
line = if move_up { line - 1 } else { line.saturating_add(1) };
}
(lo.line_col_to_offset(text, line, col), Some(col))
}
/// Based on the current selection position this will return the cursor position, the current line, and the
/// total number of lines of the file.
fn selection_position(
r: SelRegion,
lo: &dyn LineOffset,
text: &Rope,
move_up: bool,
modify: bool,
) -> (HorizPos, usize) {
// The active point of the selection
let active = if modify {
r.end
} else if move_up {
r.min()
} else {
r.max()
};
let col = if let Some(col) = r.horiz { col } else { lo.offset_to_line_col(text, active).1 };
let line = lo.line_of_offset(text, active);
(col, line)
}
/// When paging through a file, the number of lines from the previous page
/// that will also be visible in the next.
const SCROLL_OVERLAP: isize = 2;
/// Computes the actual desired amount of scrolling (generally slightly
/// less than the height of the viewport, to allow overlap).
fn scroll_height(height: usize) -> isize {
max(height as isize - SCROLL_OVERLAP, 1)
}
/// Compute the result of movement on one selection region.
///
/// # Arguments
///
/// * `height` - viewport height
pub fn region_movement(
m: Movement,
r: SelRegion,
lo: &dyn LineOffset,
height: usize,
text: &Rope,
modify: bool,
) -> SelRegion {
let (offset, horiz) = match m {
Movement::Left => {
if r.is_caret() || modify {
if let Some(offset) = text.prev_grapheme_offset(r.end) {
(offset, None)
} else {
(0, r.horiz)
}
} else {
(r.min(), None)
}
}
Movement::Right => {
if r.is_caret() || modify {
if let Some(offset) = text.next_grapheme_offset(r.end) {
(offset, None)
} else {
(r.end, r.horiz)
}
} else {
(r.max(), None)
}
}
Movement::LeftWord => {
let mut word_cursor = WordCursor::new(text, r.end);
let offset = word_cursor.prev_boundary().unwrap_or(0);
(offset, None)
}
Movement::RightWord => {
let mut word_cursor = WordCursor::new(text, r.end);
let offset = word_cursor.next_boundary().unwrap_or_else(|| text.len());
(offset, None)
}
Movement::LeftOfLine => {
let line = lo.line_of_offset(text, r.end);
let offset = lo.offset_of_line(text, line);
(offset, None)
}
Movement::RightOfLine => {
let line = lo.line_of_offset(text, r.end);
let mut offset = text.len();
// calculate end of line
let next_line_offset = lo.offset_of_line(text, line + 1);
if line < lo.line_of_offset(text, offset) {
if let Some(prev) = text.prev_grapheme_offset(next_line_offset) {
offset = prev;
}
}
(offset, None)
}
Movement::Up => vertical_motion(r, lo, text, -1, modify),
Movement::Down => vertical_motion(r, lo, text, 1, modify),
Movement::UpExactPosition => vertical_motion_exact_pos(r, lo, text, true, modify),
Movement::DownExactPosition => vertical_motion_exact_pos(r, lo, text, false, modify),
Movement::StartOfParagraph => {
// Note: TextEdit would start at modify ? r.end : r.min()
let mut cursor = Cursor::new(text, r.end);
let offset = cursor.prev::<LinesMetric>().unwrap_or(0);
(offset, None)
}
Movement::EndOfParagraph => {
// Note: TextEdit would start at modify ? r.end : r.max()
let mut offset = r.end;
let mut cursor = Cursor::new(text, offset);
if let Some(next_para_offset) = cursor.next::<LinesMetric>() {
if cursor.is_boundary::<LinesMetric>() {
if let Some(eol) = text.prev_grapheme_offset(next_para_offset) {
offset = eol;
}
} else if cursor.pos() == text.len() {
offset = text.len();
}
(offset, None)
} else {
//in this case we are already on a last line so just moving to EOL
(text.len(), None)
}
}
Movement::EndOfParagraphKill => {
// Note: TextEdit would start at modify ? r.end : r.max()
let mut offset = r.end;
let mut cursor = Cursor::new(text, offset);
if let Some(next_para_offset) = cursor.next::<LinesMetric>() {
offset = next_para_offset;
if cursor.is_boundary::<LinesMetric>() {
if let Some(eol) = text.prev_grapheme_offset(next_para_offset) {
if eol != r.end {
offset = eol;
}
}
}
}
(offset, None)
}
Movement::UpPage => vertical_motion(r, lo, text, -scroll_height(height), modify),
Movement::DownPage => vertical_motion(r, lo, text, scroll_height(height), modify),
Movement::StartOfDocument => (0, None),
Movement::EndOfDocument => (text.len(), None),
};
SelRegion::new(if modify { r.start } else { offset }, offset).with_horiz(horiz)
}
/// Compute a new selection by applying a movement to an existing selection.
///
/// In a multi-region selection, this function applies the movement to each
/// region in the selection, and returns the union of the results.
///
/// If `modify` is `true`, the selections are modified, otherwise the results
/// of individual region movements become carets.
///
/// # Arguments
///
/// * `height` - viewport height
pub fn selection_movement(
m: Movement,
s: &Selection,
lo: &dyn LineOffset,
height: usize,
text: &Rope,
modify: bool,
) -> Selection {
let mut result = Selection::new();
for &r in s.iter() {
let new_region = region_movement(m, r, lo, height, text, modify);
result.add_region(new_region);
}
result
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/index_set.rs | rust/core-lib/src/index_set.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A data structure for manipulating sets of indices (typically used for
//! representing valid lines).
// Note: this data structure has nontrivial overlap with Subset in the rope
// crate. Maybe we don't need both.
use std::cmp::{max, min, Ordering};
use xi_rope::{RopeDelta, Transformer};
pub struct IndexSet {
ranges: Vec<(usize, usize)>,
}
pub fn remove_n_at<T: Clone>(v: &mut Vec<T>, index: usize, n: usize) {
match n.cmp(&1) {
Ordering::Equal => {
v.remove(index);
}
Ordering::Greater => {
let new_len = v.len() - n;
for i in index..new_len {
v[i] = v[i + n].clone();
}
v.truncate(new_len);
}
Ordering::Less => (),
}
}
impl IndexSet {
/// Create a new, empty set.
pub fn new() -> IndexSet {
IndexSet { ranges: Vec::new() }
}
/// Clear the set.
pub fn clear(&mut self) {
self.ranges.clear();
}
/// Add the range start..end to the set.
pub fn union_one_range(&mut self, start: usize, end: usize) {
for i in 0..self.ranges.len() {
let (istart, iend) = self.ranges[i];
if start > iend {
continue;
} else if end < istart {
self.ranges.insert(i, (start, end));
return;
} else {
self.ranges[i].0 = min(start, istart);
let mut j = i;
while j + 1 < self.ranges.len() && end >= self.ranges[j + 1].0 {
j += 1;
}
self.ranges[i].1 = max(end, self.ranges[j].1);
remove_n_at(&mut self.ranges, i + 1, j - i);
return;
}
}
self.ranges.push((start, end));
}
/// Deletes the given range from the set.
pub fn delete_range(&mut self, start: usize, end: usize) {
let mut ix = match self.ranges.binary_search_by(|r| r.1.cmp(&start)) {
Ok(ix) => ix,
Err(ix) => ix,
};
let mut del_from = None;
let mut del_len = 0;
while ix < self.ranges.len() {
if self.ranges[ix].0 >= end {
break;
}
if self.ranges[ix].0 < start {
if self.ranges[ix].1 > end {
let range = (end, self.ranges[ix].1);
self.ranges.insert(ix + 1, range);
}
self.ranges[ix].1 = start;
} else if self.ranges[ix].1 > end {
self.ranges[ix].0 = end;
} else {
if del_from.is_none() {
del_from = Some(ix);
}
del_len += 1;
}
ix += 1;
}
if let Some(del_from) = del_from {
remove_n_at(&mut self.ranges, del_from, del_len);
}
}
/// Return an iterator that yields start..end minus the coverage in this set.
pub fn minus_one_range(&self, start: usize, end: usize) -> MinusIter {
let mut ranges = &self.ranges[..];
while !ranges.is_empty() && start >= ranges[0].1 {
ranges = &ranges[1..];
}
MinusIter { ranges, start, end }
}
/// Computes a new set based on applying a delta to the old set. Collapsed regions are removed
/// and contiguous regions are combined.
pub fn apply_delta(&self, delta: &RopeDelta) -> IndexSet {
let mut ranges: Vec<(usize, usize)> = Vec::new();
let mut transformer = Transformer::new(delta);
for &(start, end) in &self.ranges {
let new_range =
(transformer.transform(start, false), transformer.transform(end, false));
if new_range.0 == new_range.1 {
continue; // remove collapsed regions
}
if !ranges.is_empty() {
let ix = ranges.len() - 1;
if ranges[ix].1 == new_range.0 {
ranges[ix] = (ranges[ix].0, new_range.1);
continue;
}
}
ranges.push(new_range);
}
IndexSet { ranges }
}
#[cfg(test)]
fn get_ranges(&self) -> &[(usize, usize)] {
&self.ranges
}
}
/// The iterator generated by `minus_one_range`.
pub struct MinusIter<'a> {
ranges: &'a [(usize, usize)],
start: usize,
end: usize,
}
impl<'a> Iterator for MinusIter<'a> {
type Item = (usize, usize);
fn next(&mut self) -> Option<(usize, usize)> {
while self.start < self.end {
if self.ranges.is_empty() || self.end <= self.ranges[0].0 {
let result = (self.start, self.end);
self.start = self.end;
return Some(result);
}
let result = (self.start, self.ranges[0].0);
self.start = self.ranges[0].1;
self.ranges = &self.ranges[1..];
if result.1 > result.0 {
return Some(result);
}
}
None
}
}
impl<'a> DoubleEndedIterator for MinusIter<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
while self.start < self.end {
if self.ranges.is_empty() || self.ranges[self.ranges.len() - 1].1 <= self.start {
let result = (self.start, self.end);
self.start = self.end;
return Some(result);
}
let last_ix = self.ranges.len() - 1;
let result = (self.ranges[last_ix].1, self.end);
self.end = self.ranges[last_ix].0;
self.ranges = &self.ranges[..last_ix];
if result.1 > result.0 {
return Some(result);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::IndexSet;
#[test]
fn empty_behavior() {
let e = IndexSet::new();
assert_eq!(e.minus_one_range(0, 0).collect::<Vec<_>>(), vec![]);
assert_eq!(e.minus_one_range(3, 5).collect::<Vec<_>>(), vec![(3, 5)]);
}
#[test]
fn single_range_behavior() {
let mut e = IndexSet::new();
e.union_one_range(3, 5);
assert_eq!(e.minus_one_range(0, 0).collect::<Vec<_>>(), vec![]);
assert_eq!(e.minus_one_range(3, 5).collect::<Vec<_>>(), vec![]);
assert_eq!(e.minus_one_range(0, 3).collect::<Vec<_>>(), vec![(0, 3)]);
assert_eq!(e.minus_one_range(0, 4).collect::<Vec<_>>(), vec![(0, 3)]);
assert_eq!(e.minus_one_range(4, 10).collect::<Vec<_>>(), vec![(5, 10)]);
assert_eq!(e.minus_one_range(5, 10).collect::<Vec<_>>(), vec![(5, 10)]);
assert_eq!(e.minus_one_range(0, 10).collect::<Vec<_>>(), vec![(0, 3), (5, 10)]);
}
#[test]
fn two_range_minus() {
let mut e = IndexSet::new();
e.union_one_range(3, 5);
e.union_one_range(7, 9);
assert_eq!(e.minus_one_range(0, 0).collect::<Vec<_>>(), vec![]);
assert_eq!(e.minus_one_range(3, 5).collect::<Vec<_>>(), vec![]);
assert_eq!(e.minus_one_range(0, 3).collect::<Vec<_>>(), vec![(0, 3)]);
assert_eq!(e.minus_one_range(0, 4).collect::<Vec<_>>(), vec![(0, 3)]);
assert_eq!(e.minus_one_range(4, 10).collect::<Vec<_>>(), vec![(5, 7), (9, 10)]);
assert_eq!(e.minus_one_range(5, 10).collect::<Vec<_>>(), vec![(5, 7), (9, 10)]);
assert_eq!(e.minus_one_range(8, 10).collect::<Vec<_>>(), vec![(9, 10)]);
assert_eq!(e.minus_one_range(0, 10).collect::<Vec<_>>(), vec![(0, 3), (5, 7), (9, 10)]);
}
#[test]
fn minus_one_range_double_ended_iter() {
let mut e = IndexSet::new();
e.union_one_range(3, 5);
e.union_one_range(7, 9);
e.union_one_range(12, 15);
let mut iter = e.minus_one_range(4, 13);
assert_eq!(iter.next(), Some((5, 7)));
assert_eq!(iter.next(), Some((9, 12)));
assert_eq!(iter.next(), None);
let mut iter = e.minus_one_range(4, 13);
assert_eq!(iter.next_back(), Some((9, 12)));
assert_eq!(iter.next_back(), Some((5, 7)));
assert_eq!(iter.next_back(), None);
let mut iter = e.minus_one_range(4, 13);
assert_eq!(iter.next_back(), Some((9, 12)));
assert_eq!(iter.next(), Some((5, 7)));
assert_eq!(iter.next_back(), None);
assert_eq!(iter.next(), None);
}
#[test]
fn unions() {
let mut e = IndexSet::new();
e.union_one_range(3, 5);
assert_eq!(e.get_ranges(), &[(3, 5)]);
e.union_one_range(7, 9);
assert_eq!(e.get_ranges(), &[(3, 5), (7, 9)]);
e.union_one_range(1, 2);
assert_eq!(e.get_ranges(), &[(1, 2), (3, 5), (7, 9)]);
e.union_one_range(2, 3);
assert_eq!(e.get_ranges(), &[(1, 5), (7, 9)]);
e.union_one_range(4, 6);
assert_eq!(e.get_ranges(), &[(1, 6), (7, 9)]);
assert_eq!(e.minus_one_range(0, 10).collect::<Vec<_>>(), vec![(0, 1), (6, 7), (9, 10)]);
e.clear();
assert_eq!(e.get_ranges(), &[]);
e.union_one_range(3, 4);
assert_eq!(e.get_ranges(), &[(3, 4)]);
e.union_one_range(5, 6);
assert_eq!(e.get_ranges(), &[(3, 4), (5, 6)]);
e.union_one_range(7, 8);
assert_eq!(e.get_ranges(), &[(3, 4), (5, 6), (7, 8)]);
e.union_one_range(9, 10);
assert_eq!(e.get_ranges(), &[(3, 4), (5, 6), (7, 8), (9, 10)]);
e.union_one_range(11, 12);
assert_eq!(e.get_ranges(), &[(3, 4), (5, 6), (7, 8), (9, 10), (11, 12)]);
e.union_one_range(2, 10);
assert_eq!(e.get_ranges(), &[(2, 10), (11, 12)]);
}
#[test]
fn delete_range() {
let mut e = IndexSet::new();
e.union_one_range(1, 2);
e.union_one_range(4, 6);
e.union_one_range(6, 7);
e.union_one_range(8, 8);
e.union_one_range(10, 12);
e.union_one_range(13, 14);
e.delete_range(5, 11);
assert_eq!(e.get_ranges(), &[(1, 2), (4, 5), (11, 12), (13, 14)]);
let mut e = IndexSet::new();
e.union_one_range(1, 2);
e.union_one_range(4, 6);
e.delete_range(2, 4);
assert_eq!(e.get_ranges(), &[(1, 2), (4, 6)]);
let mut e = IndexSet::new();
e.union_one_range(0, 10);
e.delete_range(4, 6);
assert_eq!(e.get_ranges(), &[(0, 4), (6, 10)]);
}
#[test]
fn apply_delta() {
use xi_rope::{Delta, Interval, Rope};
let mut e = IndexSet::new();
e.union_one_range(1, 3);
e.union_one_range(5, 9);
let d = Delta::simple_edit(Interval::new(2, 2), Rope::from("..."), 10);
let s = e.apply_delta(&d);
assert_eq!(s.get_ranges(), &[(1, 6), (8, 12)]);
let d = Delta::simple_edit(Interval::new(0, 3), Rope::from(""), 10);
let s = e.apply_delta(&d);
assert_eq!(s.get_ranges(), &[(2, 6)]);
let d = Delta::simple_edit(Interval::new(2, 6), Rope::from(""), 10);
let s = e.apply_delta(&d);
assert_eq!(s.get_ranges(), &[(1, 5)]);
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/fuchsia/ledger.rs | rust/core-lib/src/fuchsia/ledger.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Utility functions to make it easier to work with Ledger in Rust
// TODO merge with equivalent module in fuchsia/rust_ledger_example into a library?
use apps_ledger_services_public::*;
use fidl::Error;
use fuchsia::read_entire_vmo;
use magenta::{self, Vmo};
use sha2::{Digest, Sha256};
// Rust emits a warning if matched-on constants aren't all-caps
pub const OK: Status = Status_Ok;
pub const KEY_NOT_FOUND: Status = Status_KeyNotFound;
pub const NEEDS_FETCH: Status = Status_NeedsFetch;
pub const RESULT_COMPLETED: ResultState = ResultState_Completed;
pub fn ledger_crash_callback(res: Result<Status, Error>) {
let status = res.expect("ledger call failed to respond with a status");
assert_eq!(status, Status_Ok, "ledger call failed");
}
#[derive(Debug)]
pub enum ValueError {
NeedsFetch,
LedgerFail(Status),
Vmo(magenta::Status),
}
/// Convert the low level result of getting a key from the ledger into a
/// higher level Rust representation.
pub fn value_result(res: (Status, Option<Vmo>)) -> Result<Option<Vec<u8>>, ValueError> {
match res {
(OK, Some(vmo)) => {
let buffer = read_entire_vmo(&vmo).map_err(ValueError::Vmo)?;
Ok(Some(buffer))
}
(KEY_NOT_FOUND, _) => Ok(None),
(NEEDS_FETCH, _) => Err(ValueError::NeedsFetch),
(status, _) => Err(ValueError::LedgerFail(status)),
}
}
/// Ledger page ids are exactly 16 bytes, so we need a way of determining
/// a unique 16 byte ID that won't collide based on some data we have
pub fn gen_page_id(input_data: &[u8]) -> [u8; 16] {
let mut hasher = Sha256::default();
hasher.input(input_data);
let full_hash = hasher.result();
let full_slice = full_hash.as_slice();
// magic incantation to get the first 16 bytes of the hash
let mut arr: [u8; 16] = Default::default();
arr.as_mut().clone_from_slice(&full_slice[0..16]);
arr
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/fuchsia/sync.rs | rust/core-lib/src/fuchsia/sync.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Architecture for synchronizing a CRDT with the ledger. Separated into a
//! module so that it is easier to add other sync stores later.
use std::io::Write;
use std::sync::mpsc::{Receiver, RecvError, Sender};
use log;
use apps_ledger_services_public::*;
use fidl::{self, Future, Promise};
use fuchsia::read_entire_vmo;
use magenta::{Channel, ChannelOpts, HandleBase};
use serde_json;
use super::ledger::{self, ledger_crash_callback};
use tabs::{BufferContainerRef, BufferIdentifier};
use xi_rope::engine::Engine;
// TODO switch these to bincode
fn state_to_buf(state: &Engine) -> Vec<u8> {
serde_json::to_vec(state).unwrap()
}
fn buf_to_state(buf: &[u8]) -> Result<Engine, serde_json::Error> {
serde_json::from_slice(buf)
}
/// Stores state needed by the container to perform synchronization.
pub struct SyncStore {
page: Page_Proxy,
key: Vec<u8>,
updates: Sender<SyncMsg>,
transaction_pending: bool,
buffer: BufferIdentifier,
}
impl SyncStore {
/// - `page` is a reference to the Ledger page to store data under.
/// - `key` is the key the `Syncable` managed by this `SyncStore` will be stored under.
/// This example only supports storing things under a single key per page.
/// - `updates` is a channel to a `SyncUpdater` that will handle events.
///
/// Returns a sync store and schedules the loading of initial
/// state and subscribes to state updates for this document.
pub fn new(
mut page: Page_Proxy,
key: Vec<u8>,
updates: Sender<SyncMsg>,
buffer: BufferIdentifier,
) -> SyncStore {
let (s1, s2) = Channel::create(ChannelOpts::Normal).unwrap();
let watcher_client = PageWatcher_Client::from_handle(s1.into_handle());
let watcher_client_ptr =
::fidl::InterfacePtr { inner: watcher_client, version: PageWatcher_Metadata::VERSION };
let watcher = PageWatcherServer { updates: updates.clone(), buffer: buffer.clone() };
let _ = fidl::Server::new(watcher, s2).spawn();
let (mut snap, snap_request) = PageSnapshot_new_pair();
page.get_snapshot(snap_request, Some(key.clone()), Some(watcher_client_ptr))
.with(ledger_crash_callback);
let initial_state_chan = updates.clone();
let initial_buffer = buffer.clone();
snap.get(key.clone()).with(move |raw_res| {
match raw_res.map(|res| ledger::value_result(res)) {
Ok(Ok(Some(buf))) => {
initial_state_chan
.send(SyncMsg::NewState {
buffer: initial_buffer,
new_buf: buf,
done: None,
})
.unwrap();
}
Ok(Ok(None)) => (), // No initial state saved yet
Err(err) => error!("FIDL failed on initial response: {:?}", err),
Ok(Err(err)) => error!("Ledger failed to retrieve key: {:?}", err),
}
});
SyncStore { page, key, updates, buffer, transaction_pending: false }
}
/// Called whenever this app changed its own state and would like to
/// persist the changes to the ledger. Changes can't be committed
/// immediately since we have to wait for PageWatcher changes that may not
/// have arrived yet.
pub fn state_changed(&mut self) {
if !self.transaction_pending {
self.transaction_pending = true;
let ready_future = self.page.start_transaction();
let done_chan = self.updates.clone();
let buffer = self.buffer.clone();
ready_future.with(move |res| match res {
Ok(ledger::OK) => {
done_chan.send(SyncMsg::TransactionReady { buffer }).unwrap();
}
Ok(err_status) => error!("Ledger failed to start transaction: {:?}", err_status),
Err(err) => error!("FIDL failed on starting transaction: {:?}", err),
});
}
}
/// Should be called in SyncContainer::transaction_ready to persist the current state.
pub fn commit_transaction(&mut self, state: &Engine) {
assert!(self.transaction_pending, "must call state_changed (and wait) before commit");
self.page.put(self.key.clone(), state_to_buf(state)).with(ledger_crash_callback);
self.page.commit().with(ledger_crash_callback);
self.transaction_pending = false;
}
}
/// All the different asynchronous events the updater thread needs to listen for and act on
pub enum SyncMsg {
NewState {
buffer: BufferIdentifier,
new_buf: Vec<u8>,
done: Option<Promise<Option<PageSnapshot_Server>, fidl::Error>>,
},
TransactionReady {
buffer: BufferIdentifier,
},
/// Shut down the updater thread
Stop,
}
/// We want to be able to register to receive events from inside the
/// `SyncStore`/`SyncContainer` but from there we don't have access to the
/// Mutex that holds the container, so we give channel Senders to all the
/// futures so that they can all trigger events in one place that does have
/// the right reference.
///
/// Additionally, the individual `Editor`s aren't wrapped in a `Mutex` so we
/// have to hold a `BufferContainerRef` and use `BufferIdentifier`s with one
/// `SyncUpdater` for all buffers.
pub struct SyncUpdater<W: Write> {
container_ref: BufferContainerRef<W>,
chan: Receiver<SyncMsg>,
}
impl<W: Write + Send + 'static> SyncUpdater<W> {
pub fn new(container_ref: BufferContainerRef<W>, chan: Receiver<SyncMsg>) -> SyncUpdater<W> {
SyncUpdater { container_ref, chan }
}
/// Run this in a thread, it will return when it encounters an error
/// reading the channel or when the `Stop` message is recieved.
pub fn work(&self) -> Result<(), RecvError> {
loop {
let msg = self.chan.recv()?;
match msg {
SyncMsg::Stop => return Ok(()),
SyncMsg::TransactionReady { buffer } => {
let mut container = self.container_ref.lock();
// if the buffer was closed, hopefully the page connection was as well, which I hope aborts transactions
if let Some(mut editor) = container.editor_for_buffer_mut(&buffer) {
editor.transaction_ready();
}
}
SyncMsg::NewState { new_buf, done, buffer } => {
let mut container = self.container_ref.lock();
match (container.editor_for_buffer_mut(&buffer), buf_to_state(&new_buf)) {
(Some(mut editor), Ok(new_state)) => {
editor.merge_new_state(new_state);
if let Some(promise) = done {
promise.set_ok(None);
}
}
(None, _) => (), // buffer was closed
(_, Err(err)) => error!("Ledger was set to invalid state: {:?}", err),
}
}
}
}
}
}
struct PageWatcherServer {
updates: Sender<SyncMsg>,
buffer: BufferIdentifier,
}
impl PageWatcher for PageWatcherServer {
fn on_change(
&mut self,
page_change: PageChange,
result_state: ResultState,
) -> Future<Option<PageSnapshot_Server>, fidl::Error> {
let (future, done) = Future::make_promise();
let value_opt = page_change.changes.get(0).and_then(|c| c.value.as_ref());
if let (ledger::RESULT_COMPLETED, Some(value_vmo)) = (result_state, value_opt) {
let new_buf = read_entire_vmo(value_vmo).expect("failed to read key Vmo");
self.updates
.send(SyncMsg::NewState { buffer: self.buffer.clone(), new_buf, done: Some(done) })
.unwrap();
} else {
error!("Xi state corrupted, should have one key but has multiple.");
// I don't think this should be a FIDL-level error, so set okay
done.set_ok(None);
}
future
}
}
impl PageWatcher_Stub for PageWatcherServer {
// Use default dispatching, but we could override it here.
}
impl_fidl_stub!(PageWatcherServer: PageWatcher_Stub);
// ============= Conflict resolution
pub fn start_conflict_resolver_factory(ledger: &mut Ledger_Proxy, key: Vec<u8>) {
let (s1, s2) = Channel::create(ChannelOpts::Normal).unwrap();
let resolver_client = ConflictResolverFactory_Client::from_handle(s1.into_handle());
let resolver_client_ptr = ::fidl::InterfacePtr {
inner: resolver_client,
version: ConflictResolverFactory_Metadata::VERSION,
};
let _ = fidl::Server::new(ConflictResolverFactoryServer { key }, s2).spawn();
ledger.set_conflict_resolver_factory(Some(resolver_client_ptr)).with(ledger_crash_callback);
}
struct ConflictResolverFactoryServer {
key: Vec<u8>,
}
impl ConflictResolverFactory for ConflictResolverFactoryServer {
fn get_policy(&mut self, _page_id: Vec<u8>) -> Future<MergePolicy, ::fidl::Error> {
Future::done(Ok(MergePolicy_Custom))
}
/// Our resolvers are the same for every page
fn new_conflict_resolver(&mut self, _page_id: Vec<u8>, resolver: ConflictResolver_Server) {
let _ = fidl::Server::new(
ConflictResolverServer { key: self.key.clone() },
resolver.into_channel(),
)
.spawn();
}
}
impl ConflictResolverFactory_Stub for ConflictResolverFactoryServer {
// Use default dispatching, but we could override it here.
}
impl_fidl_stub!(ConflictResolverFactoryServer: ConflictResolverFactory_Stub);
fn state_from_snapshot<F>(
snapshot: ::fidl::InterfacePtr<PageSnapshot_Client>,
key: Vec<u8>,
done: F,
) where
F: Send + FnOnce(Result<Option<Engine>, ()>) + 'static,
{
assert_eq!(PageSnapshot_Metadata::VERSION, snapshot.version);
let mut snapshot_proxy = PageSnapshot_new_Proxy(snapshot.inner);
// TODO get a reference when too big
snapshot_proxy.get(key).with(move |raw_res| {
let state = match raw_res.map(|res| ledger::value_result(res)) {
// the .ok() has the behavior of acting like invalid state is empty
// and thus deleting invalid state and overwriting it with good state
Ok(Ok(Some(buf))) => Ok(buf_to_state(&buf).ok()),
Ok(Ok(None)) => {
info!("No state in conflicting page");
Ok(None)
}
Err(err) => {
warn!("FIDL failed on initial response: {:?}", err);
Err(())
}
Ok(Err(err)) => {
warn!("Ledger failed to retrieve key: {:?}", err);
Err(())
}
};
done(state);
});
}
struct ConflictResolverServer {
key: Vec<u8>,
}
impl ConflictResolver for ConflictResolverServer {
fn resolve(
&mut self,
left: ::fidl::InterfacePtr<PageSnapshot_Client>,
right: ::fidl::InterfacePtr<PageSnapshot_Client>,
_common_version: Option<::fidl::InterfacePtr<PageSnapshot_Client>>,
result_provider: ::fidl::InterfacePtr<MergeResultProvider_Client>,
) {
// TODO in the futures-rs future, do this in parallel with Future combinators
let key2 = self.key.clone();
state_from_snapshot(left, self.key.clone(), move |e1_opt| {
let key3 = key2.clone();
state_from_snapshot(right, key2, move |e2_opt| {
let result_opt = match (e1_opt, e2_opt) {
(Ok(Some(mut e1)), Ok(Some(e2))) => {
e1.merge(&e2);
Some(e1)
}
// one engine didn't exist yet, I'm not sure if Ledger actually generates a conflict in this case
(Ok(Some(e)), Ok(None)) | (Ok(None), Ok(Some(e))) => Some(e),
// failed to get one of the engines, we can't do the merge properly
(Err(()), _) | (_, Err(())) => None,
// if state is invalid or missing on both sides, can't merge
(Ok(None), Ok(None)) => None,
};
if let Some(out_state) = result_opt {
let buf = state_to_buf(&out_state);
// TODO use a reference here when buf is too big
let new_value = Some(Box::new(BytesOrReference::Bytes(buf)));
let merged = MergedValue {
key: key3,
source: ValueSource_New,
new_value,
priority: Priority_Eager,
};
assert_eq!(MergeResultProvider_Metadata::VERSION, result_provider.version);
let mut result_provider_proxy =
MergeResultProvider_new_Proxy(result_provider.inner);
result_provider_proxy.merge(vec![merged]);
result_provider_proxy.done().with(ledger_crash_callback);
}
});
});
}
}
impl ConflictResolver_Stub for ConflictResolverServer {
// Use default dispatching, but we could override it here.
}
impl_fidl_stub!(ConflictResolverServer: ConflictResolver_Stub);
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/fuchsia/mod.rs | rust/core-lib/src/fuchsia/mod.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod ledger;
pub mod sync;
use magenta::{Status, Vmo};
// TODO: move this into magenta-rs?
pub fn read_entire_vmo(vmo: &Vmo) -> Result<Vec<u8>, Status> {
let size = vmo.get_size()?;
// TODO: how fishy is this cast to usize?
let mut buffer: Vec<u8> = Vec::with_capacity(size as usize);
// TODO: consider using unsafe .set_len() to get uninitialized memory
for _ in 0..size {
buffer.push(0);
}
let bytes_read = vmo.read(buffer.as_mut_slice(), 0)?;
buffer.truncate(bytes_read);
Ok(buffer)
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/plugins/catalog.rs | rust/core-lib/src/plugins/catalog.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Keeping track of available plugins.
use std::collections::HashMap;
use std::fs;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use super::{PluginDescription, PluginName};
use crate::config::table_from_toml_str;
use crate::syntax::Languages;
/// A catalog of all available plugins.
#[derive(Debug, Clone, Default)]
pub struct PluginCatalog {
items: HashMap<PluginName, Arc<PluginDescription>>,
locations: HashMap<PathBuf, Arc<PluginDescription>>,
}
/// Errors that can occur while trying to load a plugin.
#[derive(Debug)]
pub enum PluginLoadError {
Io(io::Error),
/// Malformed manifest
Parse(toml::de::Error),
}
#[allow(dead_code)]
impl<'a> PluginCatalog {
/// Loads any plugins discovered in these paths, replacing any existing
/// plugins.
pub fn reload_from_paths(&mut self, paths: &[PathBuf]) {
self.items.clear();
self.locations.clear();
self.load_from_paths(paths);
}
/// Loads plugins from paths and adds them to existing plugins.
pub fn load_from_paths(&mut self, paths: &[PathBuf]) {
let all_manifests = find_all_manifests(paths);
for manifest_path in &all_manifests {
match load_manifest(manifest_path) {
Err(e) => warn!("error loading plugin {:?}", e),
Ok(manifest) => {
info!("loaded {}", manifest.name);
let manifest = Arc::new(manifest);
self.items.insert(manifest.name.clone(), manifest.clone());
self.locations.insert(manifest_path.clone(), manifest);
}
}
}
}
pub fn make_languages_map(&self) -> Languages {
let all_langs =
self.items.values().flat_map(|plug| plug.languages.iter().cloned()).collect::<Vec<_>>();
Languages::new(all_langs.as_slice())
}
/// Returns an iterator over all plugins in the catalog, in arbitrary order.
pub fn iter(&'a self) -> impl Iterator<Item = Arc<PluginDescription>> + 'a {
self.items.values().cloned()
}
/// Returns an iterator over all plugin names in the catalog,
/// in arbitrary order.
pub fn iter_names(&'a self) -> impl Iterator<Item = &'a PluginName> {
self.items.keys()
}
/// Returns the plugin located at the provided file path.
pub fn get_from_path(&self, path: &PathBuf) -> Option<Arc<PluginDescription>> {
self.items
.values()
.find(|&v| v.exec_path.to_str().unwrap().contains(path.to_str().unwrap()))
.cloned()
}
/// Returns a reference to the named plugin if it exists in the catalog.
pub fn get_named(&self, plugin_name: &str) -> Option<Arc<PluginDescription>> {
self.items.get(plugin_name).map(Arc::clone)
}
/// Removes the named plugin.
pub fn remove_named(&mut self, plugin_name: &str) {
self.items.remove(plugin_name);
}
}
fn find_all_manifests(paths: &[PathBuf]) -> Vec<PathBuf> {
let mut manifest_paths = Vec::new();
for path in paths.iter() {
let manif_path = path.join("manifest.toml");
if manif_path.exists() {
manifest_paths.push(manif_path);
continue;
}
let result = path.read_dir().map(|dir| {
dir.flat_map(|item| item.map(|p| p.path()).ok())
.map(|dir| dir.join("manifest.toml"))
.filter(|f| f.exists())
.for_each(|f| manifest_paths.push(f))
});
if let Err(e) = result {
error!("error reading plugin path {:?}, {:?}", path, e);
}
}
manifest_paths
}
fn load_manifest(path: &Path) -> Result<PluginDescription, PluginLoadError> {
let mut file = fs::File::open(&path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let mut manifest: PluginDescription = toml::from_str(&contents)?;
// normalize relative paths
if manifest.exec_path.starts_with("./") {
manifest.exec_path = path.parent().unwrap().join(manifest.exec_path).canonicalize()?;
}
for lang in &mut manifest.languages {
let lang_config_path =
path.parent().unwrap().join(&lang.name.as_ref()).with_extension("toml");
if !lang_config_path.exists() {
continue;
}
let lang_defaults = fs::read_to_string(&lang_config_path)?;
let lang_defaults = table_from_toml_str(&lang_defaults)?;
lang.default_config = Some(lang_defaults);
}
Ok(manifest)
}
impl From<io::Error> for PluginLoadError {
fn from(err: io::Error) -> PluginLoadError {
PluginLoadError::Io(err)
}
}
impl From<toml::de::Error> for PluginLoadError {
fn from(err: toml::de::Error) -> PluginLoadError {
PluginLoadError::Parse(err)
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/plugins/manifest.rs | rust/core-lib/src/plugins/manifest.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Structured representation of a plugin's features and capabilities.
use std::path::PathBuf;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{self, Value};
use crate::syntax::{LanguageDefinition, LanguageId};
/// Describes attributes and capabilities of a plugin.
///
/// Note: - these will eventually be loaded from manifest files.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct PluginDescription {
pub name: String,
pub version: String,
#[serde(default)]
pub scope: PluginScope,
// more metadata ...
/// path to plugin executable
#[serde(deserialize_with = "platform_exec_path")]
pub exec_path: PathBuf,
/// Events that cause this plugin to run
#[serde(default)]
pub activations: Vec<PluginActivation>,
#[serde(default)]
pub commands: Vec<Command>,
#[serde(default)]
pub languages: Vec<LanguageDefinition>,
}
fn platform_exec_path<'de, D: Deserializer<'de>>(deserializer: D) -> Result<PathBuf, D::Error> {
let exec_path = PathBuf::deserialize(deserializer)?;
if cfg!(windows) {
Ok(exec_path.with_extension("exe"))
} else {
Ok(exec_path)
}
}
/// `PluginActivation`s represent events that trigger running a plugin.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginActivation {
/// Always run this plugin, when available.
Autorun,
/// Run this plugin if the provided SyntaxDefinition is active.
#[allow(dead_code)]
OnSyntax(LanguageId),
/// Run this plugin in response to a given command.
#[allow(dead_code)]
OnCommand,
}
/// Describes the scope of events a plugin receives.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PluginScope {
/// The plugin receives events from multiple buffers.
Global,
/// The plugin receives events for a single buffer.
BufferLocal,
/// The plugin is launched in response to a command, and receives no
/// further updates.
SingleInvocation,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Represents a custom command provided by a plugin.
pub struct Command {
/// Human readable title, for display in (for example) a menu.
pub title: String,
/// A short description of the command.
pub description: String,
/// Template of the command RPC as it should be sent to the plugin.
pub rpc_cmd: PlaceholderRpc,
/// A list of `CommandArgument`s, which the client should use to build the RPC.
pub args: Vec<CommandArgument>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// A user provided argument to a plugin command.
pub struct CommandArgument {
/// A human readable name for this argument, for use as placeholder
/// text or equivelant.
pub title: String,
/// A short (single sentence) description of this argument's use.
pub description: String,
pub key: String,
pub arg_type: ArgumentType,
#[serde(skip_serializing_if = "Option::is_none")]
/// If `arg_type` is `Choice`, `options` must contain a list of options.
pub options: Option<Vec<ArgumentOption>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ArgumentType {
Number,
Int,
PosInt,
Bool,
String,
Choice,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
/// Represents an option for a user-selectable argument.
pub struct ArgumentOption {
pub title: String,
pub value: Value,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
/// A placeholder type which can represent a generic RPC.
///
/// This is the type used for custom plugin commands, which may have arbitrary
/// method names and parameters.
pub struct PlaceholderRpc {
pub method: String,
pub params: Value,
pub rpc_type: RpcType,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum RpcType {
Notification,
Request,
}
impl Command {
pub fn new<S, V>(title: S, description: S, rpc_cmd: PlaceholderRpc, args: V) -> Self
where
S: AsRef<str>,
V: Into<Option<Vec<CommandArgument>>>,
{
let title = title.as_ref().to_owned();
let description = description.as_ref().to_owned();
let args = args.into().unwrap_or_default();
Command { title, description, rpc_cmd, args }
}
}
impl CommandArgument {
pub fn new<S: AsRef<str>>(
title: S,
description: S,
key: S,
arg_type: ArgumentType,
options: Option<Vec<ArgumentOption>>,
) -> Self {
let key = key.as_ref().to_owned();
let title = title.as_ref().to_owned();
let description = description.as_ref().to_owned();
if arg_type == ArgumentType::Choice {
assert!(options.is_some())
}
CommandArgument { title, description, key, arg_type, options }
}
}
impl ArgumentOption {
pub fn new<S: AsRef<str>, V: Serialize>(title: S, value: V) -> Self {
let title = title.as_ref().to_owned();
let value = serde_json::to_value(value).unwrap();
ArgumentOption { title, value }
}
}
impl PlaceholderRpc {
pub fn new<S, V>(method: S, params: V, request: bool) -> Self
where
S: AsRef<str>,
V: Into<Option<Value>>,
{
let method = method.as_ref().to_owned();
let params = params.into().unwrap_or(json!({}));
let rpc_type = if request { RpcType::Request } else { RpcType::Notification };
PlaceholderRpc { method, params, rpc_type }
}
pub fn is_request(&self) -> bool {
self.rpc_type == RpcType::Request
}
/// Returns a reference to the placeholder's params.
pub fn params_ref(&self) -> &Value {
&self.params
}
/// Returns a mutable reference to the placeholder's params.
pub fn params_ref_mut(&mut self) -> &mut Value {
&mut self.params
}
/// Returns a reference to the placeholder's method.
pub fn method_ref(&self) -> &str {
&self.method
}
}
impl PluginDescription {
/// Returns `true` if this plugin is globally scoped, else `false`.
pub fn is_global(&self) -> bool {
matches!(self.scope, PluginScope::Global)
}
}
impl Default for PluginScope {
fn default() -> Self {
PluginScope::BufferLocal
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn platform_exec_path() {
let json = r#"
{
"name": "test_plugin",
"version": "0.0.0",
"scope": "global",
"exec_path": "path/to/binary",
"activations": [],
"commands": [],
"languages": []
}
"#;
let plugin_desc: PluginDescription = serde_json::from_str(json).unwrap();
if cfg!(windows) {
assert!(plugin_desc.exec_path.ends_with("binary.exe"));
} else {
assert!(plugin_desc.exec_path.ends_with("binary"));
}
}
#[test]
fn test_serde_command() {
let json = r#"
{
"title": "Test Command",
"description": "Passes the current test",
"rpc_cmd": {
"rpc_type": "notification",
"method": "test.cmd",
"params": {
"view": "",
"non_arg": "plugin supplied value",
"arg_one": "",
"arg_two": ""
}
},
"args": [
{
"title": "First argument",
"description": "Indicates something",
"key": "arg_one",
"arg_type": "Bool"
},
{
"title": "Favourite Number",
"description": "A number used in a test.",
"key": "arg_two",
"arg_type": "Choice",
"options": [
{"title": "Five", "value": 5},
{"title": "Ten", "value": 10}
]
}
]
}
"#;
let command: Command = serde_json::from_str(json).unwrap();
assert_eq!(command.title, "Test Command");
assert_eq!(command.args[0].arg_type, ArgumentType::Bool);
assert_eq!(command.rpc_cmd.params_ref()["non_arg"], "plugin supplied value");
assert_eq!(command.args[1].options.clone().unwrap()[1].value, json!(10));
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/plugins/mod.rs | rust/core-lib/src/plugins/mod.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Plugins and related functionality.
mod catalog;
pub mod manifest;
pub mod rpc;
use std::fmt;
use std::io::BufReader;
use std::path::Path;
use std::process::{Child, Command as ProcCommand, Stdio};
use std::sync::Arc;
use std::thread;
use serde_json::Value;
use xi_rpc::{self, RpcLoop, RpcPeer};
use crate::config::Table;
use crate::syntax::LanguageId;
use crate::tabs::ViewId;
use crate::WeakXiCore;
use self::rpc::{PluginBufferInfo, PluginUpdate};
pub(crate) use self::catalog::PluginCatalog;
pub use self::manifest::{Command, PlaceholderRpc, PluginDescription};
pub type PluginName = String;
/// A process-unique identifier for a running plugin.
///
/// Note: two instances of the same executable will have different identifiers.
/// Note: this identifier is distinct from the OS's process id.
#[derive(
Serialize, Deserialize, Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord,
)]
pub struct PluginPid(pub(crate) usize);
pub type PluginId = PluginPid;
impl fmt::Display for PluginPid {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "plugin-{}", self.0)
}
}
pub struct Plugin {
peer: RpcPeer,
pub(crate) id: PluginId,
pub(crate) name: String,
#[allow(dead_code)]
process: Child,
}
impl Plugin {
//TODO: initialize should be sent automatically during launch,
//and should only send the plugin_id. We can just use the existing 'new_buffer'
// RPC for adding views
pub fn initialize(&self, info: Vec<PluginBufferInfo>) {
self.peer.send_rpc_notification(
"initialize",
&json!({
"plugin_id": self.id,
"buffer_info": info,
}),
)
}
pub fn shutdown(&self) {
self.peer.send_rpc_notification("shutdown", &json!({}));
}
// TODO: rethink naming, does this need to be a vec?
pub fn new_buffer(&self, info: &PluginBufferInfo) {
self.peer.send_rpc_notification("new_buffer", &json!({ "buffer_info": [info] }))
}
pub fn close_view(&self, view_id: ViewId) {
self.peer.send_rpc_notification("did_close", &json!({ "view_id": view_id }))
}
pub fn did_save(&self, view_id: ViewId, path: &Path) {
self.peer.send_rpc_notification(
"did_save",
&json!({
"view_id": view_id,
"path": path,
}),
)
}
pub fn update<F>(&self, update: &PluginUpdate, callback: F)
where
F: FnOnce(Result<Value, xi_rpc::Error>) + Send + 'static,
{
self.peer.send_rpc_request_async("update", &json!(update), Box::new(callback))
}
pub fn toggle_tracing(&self, enabled: bool) {
self.peer.send_rpc_notification("tracing_config", &json!({ "enabled": enabled }))
}
pub fn collect_trace(&self) -> Result<Value, xi_rpc::Error> {
self.peer.send_rpc_request("collect_trace", &json!({}))
}
pub fn config_changed(&self, view_id: ViewId, changes: &Table) {
self.peer.send_rpc_notification(
"config_changed",
&json!({
"view_id": view_id,
"changes": changes,
}),
)
}
pub fn language_changed(&self, view_id: ViewId, new_lang: &LanguageId) {
self.peer.send_rpc_notification(
"language_changed",
&json!({
"view_id": view_id,
"new_lang": new_lang,
}),
)
}
pub fn get_hover(&self, view_id: ViewId, request_id: usize, position: usize) {
self.peer.send_rpc_notification(
"get_hover",
&json!({
"view_id": view_id,
"request_id": request_id,
"position": position,
}),
)
}
pub fn dispatch_command(&self, view_id: ViewId, method: &str, params: &Value) {
self.peer.send_rpc_notification(
"custom_command",
&json!({
"view_id": view_id,
"method": method,
"params": params,
}),
)
}
}
pub(crate) fn start_plugin_process(
plugin_desc: Arc<PluginDescription>,
id: PluginId,
core: WeakXiCore,
) {
let spawn_result = thread::Builder::new()
.name(format!("<{}> core host thread", &plugin_desc.name))
.spawn(move || {
info!("starting plugin {}", &plugin_desc.name);
let child = ProcCommand::new(&plugin_desc.exec_path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn();
match child {
Ok(mut child) => {
let child_stdin = child.stdin.take().unwrap();
let child_stdout = child.stdout.take().unwrap();
let mut looper = RpcLoop::new(child_stdin);
let peer: RpcPeer = Box::new(looper.get_raw_peer());
let name = plugin_desc.name.clone();
peer.send_rpc_notification("ping", &Value::Array(Vec::new()));
let plugin = Plugin { peer, process: child, name, id };
// set tracing immediately
if xi_trace::is_enabled() {
plugin.toggle_tracing(true);
}
core.plugin_connect(Ok(plugin));
let mut core = core;
let err = looper.mainloop(|| BufReader::new(child_stdout), &mut core);
core.plugin_exit(id, err);
}
Err(err) => core.plugin_connect(Err(err)),
}
});
if let Err(err) = spawn_result {
error!("thread spawn failed for {}, {:?}", id, err);
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/src/plugins/rpc.rs | rust/core-lib/src/plugins/rpc.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! RPC types, corresponding to protocol requests, notifications & responses.
use std::borrow::Borrow;
use std::path::PathBuf;
use serde::de::{self, Deserialize, Deserializer};
use serde::ser::{self, Serialize, Serializer};
use serde_json::{self, Value};
use super::PluginPid;
use crate::annotations::AnnotationType;
use crate::config::Table;
use crate::syntax::LanguageId;
use crate::tabs::{BufferIdentifier, ViewId};
use xi_rope::{LinesMetric, Rope, RopeDelta};
use xi_rpc::RemoteError;
//TODO: At the moment (May 08, 2017) this is all very much in flux.
// At some point, it will be stabalized and then perhaps will live in another crate,
// shared with the plugin lib.
// ====================================================================
// core -> plugin RPC method types + responses
// ====================================================================
/// Buffer information sent on plugin init.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginBufferInfo {
/// The buffer's unique identifier.
pub buffer_id: BufferIdentifier,
/// The buffer's current views.
pub views: Vec<ViewId>,
pub rev: u64,
pub buf_size: usize,
pub nb_lines: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
pub syntax: LanguageId,
pub config: Table,
}
//TODO: very likely this should be merged with PluginDescription
//TODO: also this does not belong here.
/// Describes an available plugin to the client.
#[derive(Serialize, Deserialize, Debug)]
pub struct ClientPluginInfo {
pub name: String,
pub running: bool,
}
/// A simple update, sent to a plugin.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginUpdate {
pub view_id: ViewId,
/// The delta representing changes to the document.
///
/// Note: Is `Some` in the general case; only if the delta involves
/// inserting more than some maximum number of bytes, will this be `None`,
/// indicating the plugin should flush cache and fetch manually.
pub delta: Option<RopeDelta>,
/// The size of the document after applying this delta.
pub new_len: usize,
/// The total number of lines in the document after applying this delta.
pub new_line_count: usize,
pub rev: u64,
/// The undo_group associated with this update. The plugin may pass
/// this value back to core when making an edit, to associate the
/// plugin's edit with this undo group. Core uses undo_group
// to undo actions occurred due to plugins after a user action
// in a single step.
pub undo_group: Option<usize>,
pub edit_type: String,
pub author: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmptyStruct {}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC requests sent from the host
pub enum HostRequest {
Update(PluginUpdate),
CollectTrace(EmptyStruct),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC Notifications sent from the host
pub enum HostNotification {
Ping(EmptyStruct),
Initialize { plugin_id: PluginPid, buffer_info: Vec<PluginBufferInfo> },
DidSave { view_id: ViewId, path: PathBuf },
ConfigChanged { view_id: ViewId, changes: Table },
NewBuffer { buffer_info: Vec<PluginBufferInfo> },
DidClose { view_id: ViewId },
GetHover { view_id: ViewId, request_id: usize, position: usize },
Shutdown(EmptyStruct),
TracingConfig { enabled: bool },
LanguageChanged { view_id: ViewId, new_lang: LanguageId },
CustomCommand { view_id: ViewId, method: String, params: Value },
}
// ====================================================================
// plugin -> core RPC method types
// ====================================================================
/// A simple edit, received from a plugin.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PluginEdit {
pub rev: u64,
pub delta: RopeDelta,
/// the edit priority determines the resolution strategy when merging
/// concurrent edits. The highest priority edit will be applied last.
pub priority: u64,
/// whether the inserted text prefers to be to the right of the cursor.
pub after_cursor: bool,
/// the originator of this edit: some identifier (plugin name, 'core', etc)
/// undo_group associated with this edit
pub undo_group: Option<usize>,
pub author: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct ScopeSpan {
pub start: usize,
pub end: usize,
pub scope_id: u32,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DataSpan {
pub start: usize,
pub end: usize,
pub data: Value,
}
/// The object returned by the `get_data` RPC.
#[derive(Debug, Serialize, Deserialize)]
pub struct GetDataResponse {
pub chunk: String,
pub offset: usize,
pub first_line: usize,
pub first_line_offset: usize,
}
/// The unit of measure when requesting data.
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
#[serde(rename_all = "snake_case")]
pub enum TextUnit {
/// The requested offset is in bytes. The returned chunk will be valid
/// UTF8, and is guaranteed to include the byte specified the offset.
Utf8,
/// The requested offset is a line number. The returned chunk will begin
/// at the offset of the requested line.
Line,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC requests sent from plugins.
pub enum PluginRequest {
GetData { start: usize, unit: TextUnit, max_size: usize, rev: u64 },
LineCount,
GetSelections,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "method", content = "params")]
/// RPC commands sent from plugins.
pub enum PluginNotification {
AddScopes {
scopes: Vec<Vec<String>>,
},
UpdateSpans {
start: usize,
len: usize,
spans: Vec<ScopeSpan>,
rev: u64,
},
Edit {
edit: PluginEdit,
},
Alert {
msg: String,
},
AddStatusItem {
key: String,
value: String,
alignment: String,
},
UpdateStatusItem {
key: String,
value: String,
},
RemoveStatusItem {
key: String,
},
ShowHover {
request_id: usize,
result: Result<Hover, RemoteError>,
},
UpdateAnnotations {
start: usize,
len: usize,
spans: Vec<DataSpan>,
annotation_type: AnnotationType,
rev: u64,
},
}
/// Range expressed in terms of PluginPosition. Meant to be sent from
/// plugin to core.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub struct Range {
pub start: usize,
pub end: usize,
}
/// Hover Item sent from Plugin to Core
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub struct Hover {
pub content: String,
pub range: Option<Range>,
}
/// Common wrapper for plugin-originating RPCs.
pub struct PluginCommand<T> {
pub view_id: ViewId,
pub plugin_id: PluginPid,
pub cmd: T,
}
impl<T: Serialize> Serialize for PluginCommand<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut v = serde_json::to_value(&self.cmd).map_err(ser::Error::custom)?;
v["params"]["view_id"] = json!(self.view_id);
v["params"]["plugin_id"] = json!(self.plugin_id);
v.serialize(serializer)
}
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for PluginCommand<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct InnerIds {
view_id: ViewId,
plugin_id: PluginPid,
}
#[derive(Deserialize)]
struct IdsWrapper {
params: InnerIds,
}
let v = Value::deserialize(deserializer)?;
let helper = IdsWrapper::deserialize(&v).map_err(de::Error::custom)?;
let InnerIds { view_id, plugin_id } = helper.params;
let cmd = T::deserialize(v).map_err(de::Error::custom)?;
Ok(PluginCommand { view_id, plugin_id, cmd })
}
}
impl PluginBufferInfo {
pub fn new(
buffer_id: BufferIdentifier,
views: &[ViewId],
rev: u64,
buf_size: usize,
nb_lines: usize,
path: Option<PathBuf>,
syntax: LanguageId,
config: Table,
) -> Self {
//TODO: do make any current assertions about paths being valid utf-8? do we want to?
let path = path.map(|p| p.to_str().unwrap().to_owned());
let views = views.to_owned();
PluginBufferInfo { buffer_id, views, rev, buf_size, nb_lines, path, syntax, config }
}
}
impl PluginUpdate {
pub fn new<D>(
view_id: ViewId,
rev: u64,
delta: D,
new_len: usize,
new_line_count: usize,
undo_group: Option<usize>,
edit_type: String,
author: String,
) -> Self
where
D: Into<Option<RopeDelta>>,
{
let delta = delta.into();
PluginUpdate { view_id, delta, new_len, new_line_count, rev, undo_group, edit_type, author }
}
}
// maybe this should be in xi_rope? has a strong resemblance to the various
// concrete `Metric` types.
impl TextUnit {
/// Converts an offset in some unit to a concrete byte offset. Returns
/// `None` if the input offset is out of bounds in its unit space.
pub fn resolve_offset<T: Borrow<Rope>>(self, text: T, offset: usize) -> Option<usize> {
let text = text.borrow();
match self {
TextUnit::Utf8 => {
if offset > text.len() {
None
} else {
text.at_or_prev_codepoint_boundary(offset)
}
}
TextUnit::Line => {
let max_line_number = text.measure::<LinesMetric>() + 1;
if offset > max_line_number {
None
} else {
text.offset_of_line(offset).into()
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn test_plugin_update() {
let json = r#"{
"view_id": "view-id-42",
"delta": {"base_len": 6, "els": [{"copy": [0,5]}, {"insert":"rofls"}, {"copy": [5,6]}]},
"new_len": 11,
"new_line_count": 1,
"rev": 5,
"undo_group": 6,
"edit_type": "something",
"author": "me"
}"#;
let val: PluginUpdate = match serde_json::from_str(json) {
Ok(val) => val,
Err(err) => panic!("{:?}", err),
};
assert!(val.delta.is_some());
assert!(val.delta.unwrap().as_simple_insert().is_some());
}
#[test]
fn test_deserde_init() {
let json = r#"
{"buffer_id": 42,
"views": ["view-id-4"],
"rev": 1,
"buf_size": 20,
"nb_lines": 5,
"path": "some_path",
"syntax": "toml",
"config": {"some_key": 420}}"#;
let val: PluginBufferInfo = match serde_json::from_str(json) {
Ok(val) => val,
Err(err) => panic!("{:?}", err),
};
assert_eq!(val.rev, 1);
assert_eq!(val.path, Some("some_path".to_owned()));
assert_eq!(val.syntax, "toml".into());
}
#[test]
fn test_de_plugin_rpc() {
let json = r#"{"method": "alert", "params": {"view_id": "view-id-1", "plugin_id": 42, "msg": "ahhh!"}}"#;
let de: PluginCommand<PluginNotification> = serde_json::from_str(json).unwrap();
assert_eq!(de.view_id, ViewId(1));
assert_eq!(de.plugin_id, PluginPid(42));
match de.cmd {
PluginNotification::Alert { ref msg } if msg == "ahhh!" => (),
_ => panic!("{:?}", de.cmd),
}
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/tests/rpc.rs | rust/core-lib/tests/rpc.rs | // Copyright 2017 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[macro_use]
extern crate serde_json;
extern crate xi_core_lib;
extern crate xi_rpc;
use std::io;
use xi_core_lib::test_helpers;
use xi_core_lib::XiCore;
use xi_rpc::test_utils::{make_reader, test_channel};
use xi_rpc::{ReadError, RpcLoop};
#[test]
/// Tests that the handler responds to a standard startup sequence as expected.
fn test_startup() {
let mut state = XiCore::new();
let (tx, mut rx) = test_channel();
let mut rpc_looper = RpcLoop::new(tx);
let json = make_reader(
r#"{"method":"client_started","params":{}}
{"method":"set_theme","params":{"theme_name":"InspiredGitHub"}}"#,
);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
rx.expect_rpc("available_languages");
rx.expect_rpc("available_themes");
rx.expect_rpc("theme_changed");
let json = make_reader(r#"{"id":0,"method":"new_view","params":{}}"#);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
assert_eq!(rx.expect_response(), Ok(json!("view-id-1")));
rx.expect_rpc("available_plugins");
rx.expect_rpc("config_changed");
rx.expect_rpc("language_changed");
rx.expect_rpc("update");
rx.expect_rpc("scroll_to");
rx.expect_nothing();
}
#[test]
/// Tests that the handler creates and destroys views and buffers
fn test_state() {
let mut state = XiCore::new();
let write = io::sink();
let json = make_reader(
r#"{"method":"client_started","params":{}}
{"id":0,"method":"new_view","params":{"file_path":"../Cargo.toml"}}
{"method":"set_theme","params":{"theme_name":"InspiredGitHub"}}"#,
);
let mut rpc_looper = RpcLoop::new(write);
rpc_looper.mainloop(|| json, &mut state).unwrap();
{
let state = state.inner();
assert_eq!(state._test_open_editors(), vec![test_helpers::new_buffer_id(2)]);
assert_eq!(state._test_open_views(), vec![test_helpers::new_view_id(1)]);
}
let json = make_reader(r#"{"method":"close_view","params":{"view_id":"view-id-1"}}"#);
rpc_looper.mainloop(|| json, &mut state).unwrap();
{
let state = state.inner();
assert_eq!(state._test_open_views(), Vec::new());
assert_eq!(state._test_open_editors(), Vec::new());
}
let json = make_reader(
r#"{"id":1,"method":"new_view","params":{}}
{"id":2,"method":"new_view","params":{}}
{"id":3,"method":"new_view","params":{}}"#,
);
rpc_looper.mainloop(|| json, &mut state).unwrap();
{
let state = state.inner();
assert_eq!(state._test_open_editors().len(), 3);
}
}
/// Test whether xi-core invalidates cache lines upon a cursor motion.
#[test]
fn test_invalidate() {
let mut state = XiCore::new();
let (tx, mut rx) = test_channel();
let mut rpc_looper = RpcLoop::new(tx);
let json = make_reader(
r#"{"method":"client_started","params":{}}
{"id":0,"method":"new_view","params":{}}
"#,
);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
let mut edit_cmds = String::new();
for i in 1..20 {
// add lines "line 1", "line 2",...
edit_cmds.push_str(r#"{"method":"edit","params":{"view_id":"view-id-1","method":"insert","params":{"chars":"line "#);
edit_cmds.push_str(&i.to_string());
edit_cmds.push_str(
r#""}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"insert_newline","params":[]}}
"#,
);
}
let json = make_reader(edit_cmds);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
// jump to line 1, then jump to line 18
const MOVEMENTS: &str = r#"{"method":"edit","params":{"view_id":"view-id-1","method":"goto_line","params":{"line":1}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"goto_line","params":{"line":18}}}"#;
let json = make_reader(MOVEMENTS);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
let mut last_ops = Vec::new();
while let Some(Ok(resp)) = rx.next_timeout(std::time::Duration::from_millis(1000)) {
if !resp.is_response() && resp.get_method().unwrap() == "update" {
let ops = resp.0.as_object().unwrap()["params"].as_object().unwrap()["update"]
.as_object()
.unwrap()["ops"]
.as_array()
.unwrap();
last_ops = ops.clone();
// Verify that the "invalidate" ops can only go first or last.
if ops.len() > 2 {
debug_assert!(
ops.iter()
// step over leading "invalidate" and "skip"
.skip_while(|op| op["op"].as_str().unwrap() == "invalidate"
|| op["op"].as_str().unwrap() == "skip")
// current op (ins/copy/update) adds lines;
// wait for another invalidate/skip
.skip_while(|op| op["op"].as_str().unwrap() != "invalidate")
// step over trailing "invalidate" and "skip"
.skip_while(|op| op["op"].as_str().unwrap() == "invalidate"
|| op["op"].as_str().unwrap() == "skip")
.next()
.is_none(),
"bad update: {}",
&ops.iter()
.map(|op| format!(
"{} {}",
op["op"].as_str().unwrap(),
op["n"].as_u64().unwrap()
))
.collect::<Vec<_>>()
.join(", ")
);
}
}
}
// Dump the last vector of ops.
// Verify that there is an "update" op in case of a cursor motion.
assert_eq!(
last_ops
.iter()
.map(|op| {
let op_in = op.as_object().unwrap();
(op_in["op"].as_str().unwrap(), op_in["n"].as_u64().unwrap())
})
.collect::<Vec<_>>(),
[("copy", 1), ("update", 1), ("copy", 5), ("copy", 11), ("update", 2)]
);
}
#[test]
/// Tests that the runloop exits with the correct error when receiving
/// malformed json.
fn test_malformed_json() {
let mut state = XiCore::new();
let write = io::sink();
let mut rpc_looper = RpcLoop::new(write);
// malformed json: method should be in quotes.
let read = make_reader(
r#"{"method":"client_started","params":{}}
{"id":0,method:"new_view","params":{}}"#,
);
match rpc_looper.mainloop(|| read, &mut state).err().expect("malformed json exits with error") {
ReadError::Json(_) => (), // expected
err => panic!("Unexpected error: {:?}", err),
}
// read should have ended after first item
{
let state = state.inner();
assert_eq!(state._test_open_editors().len(), 0);
}
}
#[test]
/// Sends all of the cursor movement-related commands, and verifies that
/// they are handled.
///
///
/// Note: this is a test of message parsing, not of editor behaviour.
fn test_movement_cmds() {
let mut state = XiCore::new();
let write = io::sink();
let mut rpc_looper = RpcLoop::new(write);
// init a new view
let json = make_reader(
r#"{"method":"client_started","params":{}}
{"method":"set_theme","params":{"theme_name":"InspiredGitHub"}}
{"id":0,"method":"new_view","params":{}}"#,
);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
let json = make_reader(MOVEMENT_RPCS);
rpc_looper.mainloop(|| json, &mut state).unwrap();
}
#[test]
/// Sends all the commands which modify the buffer, and verifies that they
/// are handled.
fn test_text_commands() {
let mut state = XiCore::new();
let write = io::sink();
let mut rpc_looper = RpcLoop::new(write);
// init a new view
let json = make_reader(
r#"{"method":"client_started","params":{}}
{"method":"set_theme","params":{"theme_name":"InspiredGitHub"}}
{"id":0,"method":"new_view","params":{}}"#,
);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
let json = make_reader(TEXT_EDIT_RPCS);
rpc_looper.mainloop(|| json, &mut state).unwrap();
}
#[test]
fn test_other_edit_commands() {
let mut state = XiCore::new();
let write = io::sink();
let mut rpc_looper = RpcLoop::new(write);
// init a new view
let json = make_reader(
r#"{"method":"client_started","params":{}}
{"method":"set_theme","params":{"theme_name":"InspiredGitHub"}}
{"id":0,"method":"new_view","params":{}}"#,
);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
let json = make_reader(OTHER_EDIT_RPCS);
rpc_looper.mainloop(|| json, &mut state).unwrap();
}
#[test]
fn test_settings_commands() {
let mut state = XiCore::new();
let (tx, mut rx) = test_channel();
let mut rpc_looper = RpcLoop::new(tx);
// init a new view
let json = make_reader(
r#"{"method":"client_started","params":{}}
{"method":"set_theme","params":{"theme_name":"InspiredGitHub"}}
{"id":0,"method":"new_view","params":{}}"#,
);
assert!(rpc_looper.mainloop(|| json, &mut state).is_ok());
rx.expect_rpc("available_languages");
rx.expect_rpc("available_themes");
rx.expect_rpc("theme_changed");
rx.expect_response().unwrap();
rx.expect_rpc("available_plugins");
rx.expect_rpc("config_changed");
rx.expect_rpc("language_changed");
rx.expect_rpc("update");
rx.expect_rpc("scroll_to");
let json = make_reader(r#"{"method":"get_config","id":1,"params":{"view_id":"view-id-1"}}"#);
rpc_looper.mainloop(|| json, &mut state).unwrap();
let resp = rx.expect_response().unwrap();
assert_eq!(resp["tab_size"], json!(4));
let json = make_reader(
r#"{"method":"modify_user_config","params":{"domain":{"user_override":"view-id-1"},"changes":{"font_face": "Comic Sans"}}}
{"method":"modify_user_config","params":{"domain":{"syntax":"rust"},"changes":{"font_size":42}}}
{"method":"modify_user_config","params":{"domain":"general","changes":{"tab_size":13,"font_face":"Papyrus"}}}"#,
);
rpc_looper.mainloop(|| json, &mut state).unwrap();
// discard config_changed
rx.expect_rpc("config_changed");
rx.expect_rpc("update");
rx.expect_rpc("config_changed");
rx.expect_rpc("update");
let json = make_reader(r#"{"method":"get_config","id":2,"params":{"view_id":"view-id-1"}}"#);
rpc_looper.mainloop(|| json, &mut state).unwrap();
let resp = rx.expect_response().unwrap();
assert_eq!(resp["tab_size"], json!(13));
assert_eq!(resp["font_face"], json!("Comic Sans"));
// null value should clear entry from this config
let json = make_reader(
r#"{"method":"modify_user_config","params":{"domain":{"user_override":"view-id-1"},"changes":{"font_face": null}}}"#,
);
rpc_looper.mainloop(|| json, &mut state).unwrap();
let resp = rx.expect_rpc("config_changed");
assert_eq!(resp.0["params"]["changes"]["font_face"], json!("Papyrus"));
}
//TODO: test saving rpc
//TODO: test plugin rpc
const MOVEMENT_RPCS: &str = r#"{"method":"edit","params":{"view_id":"view-id-1","method":"move_up","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_down","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_up_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_down_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_left","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_backward","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_right","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_forward","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_left_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_right_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_word_left","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_word_right","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_word_left_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_word_right_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_beginning_of_paragraph","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_end_of_paragraph","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_left_end_of_line","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_left_end_of_line_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_right_end_of_line","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_right_end_of_line_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_beginning_of_document","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_beginning_of_document_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_end_of_document","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"move_to_end_of_document_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"scroll_page_up","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"scroll_page_down","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"page_up_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"page_down_and_modify_selection","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"select_all","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"add_selection_above","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"add_selection_below","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"collapse_selections","params":[]}}"#;
const TEXT_EDIT_RPCS: &str = r#"{"method":"edit","params":{"view_id":"view-id-1","method":"insert","params":{"chars":"a"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"delete_backward","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"delete_forward","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"delete_word_forward","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"delete_word_backward","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"delete_to_end_of_paragraph","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"insert_newline","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"insert_tab","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"yank","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"undo","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"redo","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"transpose","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"uppercase","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"lowercase","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"indent","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"outdent","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"duplicate_line","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"replace_next","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"replace_all","params":[]}}
{"id":2,"method":"edit","params":{"view_id":"view-id-1","method":"cut","params":[]}}"#;
const OTHER_EDIT_RPCS: &str = r#"{"method":"edit","params":{"view_id":"view-id-1","method":"scroll","params":[0,1]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"goto_line","params":{"line":1}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"request_lines","params":[0,1]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"drag","params":[17,15,0]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"gesture","params":{"line": 1, "col": 2, "ty": "toggle_sel"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"gesture","params":{"line": 1, "col": 2, "ty": "point_select"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"gesture","params":{"line": 1, "col": 2, "ty": "range_select"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"gesture","params":{"line": 1, "col": 2, "ty": "line_select"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"gesture","params":{"line": 1, "col": 2, "ty": "word_select"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"gesture","params":{"line": 1, "col": 2, "ty": "multi_line_select"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"gesture","params":{"line": 1, "col": 2, "ty": "multi_word_select"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"find","params":{"case_sensitive":false,"chars":"m"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"multi_find","params":{"queries": [{"case_sensitive":false,"chars":"m"}]}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"find_next","params":{"wrap_around":true}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"find_previous","params":{"wrap_around":true}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"find_all","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"highlight_find","params":{"visible":true}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"selection_for_find","params":{"case_sensitive":true}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"replace","params":{"chars":"a"}}}
{"method":"edit","params":{"view_id":"view-id-1","method":"selection_for_replace","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"debug_rewrap","params":[]}}
{"method":"edit","params":{"view_id":"view-id-1","method":"debug_print_spans","params":[]}}
{"id":3,"method":"edit","params":{"view_id":"view-id-1","method":"copy","params":[]}}"#;
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/core-lib/benches/wrap.rs | rust/core-lib/benches/wrap.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![feature(test)]
extern crate test;
extern crate xi_core_lib as xi_core;
extern crate xi_rope;
use crate::xi_core::line_offset::LineOffset;
use crate::xi_core::tabs::BufferId;
use crate::xi_core::view::View;
use test::Bencher;
use xi_rope::Rope;
fn build_short_lines(n: usize) -> String {
let line =
"See it, the beautiful ball Poised in the toyshop window, Rounder than sun or moon.\n";
let mut s = String::new();
for _ in 0..n {
s += line;
}
s
}
#[bench]
fn line_of_offset_no_breaks(b: &mut Bencher) {
let text = Rope::from(build_short_lines(10_000));
let view = View::new(1.into(), BufferId::new(2));
let total_bytes = text.len();
b.iter(|| {
for i in 0..total_bytes {
let _line = view.line_of_offset(&text, i);
}
})
}
#[bench]
fn line_of_offset_col_breaks(b: &mut Bencher) {
let text = Rope::from(build_short_lines(10_000));
let mut view = View::new(1.into(), BufferId::new(2));
view.debug_force_rewrap_cols(&text, 20);
let total_bytes = text.len();
b.iter(|| {
for i in 0..total_bytes {
let _line = view.line_of_offset(&text, i);
}
})
}
#[bench]
fn offset_of_line_no_breaks(b: &mut Bencher) {
let text = Rope::from(build_short_lines(10_000));
let view = View::new(1.into(), BufferId::new(2));
b.iter(|| {
for i in 0..10_000 {
let _line = view.offset_of_line(&text, i);
}
})
}
#[bench]
fn offset_of_line_col_breaks(b: &mut Bencher) {
let text = Rope::from(build_short_lines(10_000));
let mut view = View::new(1.into(), BufferId::new(2));
view.debug_force_rewrap_cols(&text, 20);
b.iter(|| {
for i in 0..10_000 {
let _line = view.offset_of_line(&text, i);
}
})
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/unicode/src/lib.rs | rust/unicode/src/lib.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Unicode utilities useful for text editing, including a line breaking iterator.
#![no_std]
extern crate alloc;
mod emoji;
mod tables;
use core::cmp::Ordering;
use crate::emoji::*;
use crate::tables::*;
/// The Unicode line breaking property of the given code point.
///
/// This is given as a numeric value which matches the ULineBreak
/// enum value from ICU.
pub fn linebreak_property(cp: char) -> u8 {
let cp = cp as usize;
if cp < 0x800 {
LINEBREAK_1_2[cp]
} else if cp < 0x10000 {
let child = LINEBREAK_3_ROOT[cp >> 6];
LINEBREAK_3_CHILD[(child as usize) * 0x40 + (cp & 0x3f)]
} else {
let mid = LINEBREAK_4_ROOT[cp >> 12];
let leaf = LINEBREAK_4_MID[(mid as usize) * 0x40 + ((cp >> 6) & 0x3f)];
LINEBREAK_4_LEAVES[(leaf as usize) * 0x40 + (cp & 0x3f)]
}
}
/// The Unicode line breaking property of the given code point.
///
/// Look up the line breaking property for the first code point in the
/// string. Return the property as a numeric value, and also the utf-8
/// length of the codepoint, for convenience.
pub fn linebreak_property_str(s: &str, ix: usize) -> (u8, usize) {
let b = s.as_bytes()[ix];
if b < 0x80 {
(LINEBREAK_1_2[b as usize], 1)
} else if b < 0xe0 {
// 2 byte UTF-8 sequences
let cp = ((b as usize) << 6) + (s.as_bytes()[ix + 1] as usize) - 0x3080;
(LINEBREAK_1_2[cp], 2)
} else if b < 0xf0 {
// 3 byte UTF-8 sequences
let mid_ix = ((b as usize) << 6) + (s.as_bytes()[ix + 1] as usize) - 0x3880;
let mid = LINEBREAK_3_ROOT[mid_ix];
(LINEBREAK_3_CHILD[(mid as usize) * 0x40 + (s.as_bytes()[ix + 2] as usize) - 0x80], 3)
} else {
// 4 byte UTF-8 sequences
let mid_ix = ((b as usize) << 6) + (s.as_bytes()[ix + 1] as usize) - 0x3c80;
let mid = LINEBREAK_4_ROOT[mid_ix];
let leaf_ix = ((mid as usize) << 6) + (s.as_bytes()[ix + 2] as usize) - 0x80;
let leaf = LINEBREAK_4_MID[leaf_ix];
(LINEBREAK_4_LEAVES[(leaf as usize) * 0x40 + (s.as_bytes()[ix + 3] as usize) - 0x80], 4)
}
}
/// An iterator which produces line breaks according to the UAX 14 line
/// breaking algorithm. For each break, return a tuple consisting of the offset
/// within the source string and a bool indicating whether it's a hard break.
///
/// There is never a break at the beginning of the string (thus, the empty string
/// produces no breaks). For non-empty strings, there is always a break at the
/// end. It is indicated as a hard break when the string is terminated with a
/// newline or other Unicode explicit line-end character.
#[derive(Copy, Clone)]
pub struct LineBreakIterator<'a> {
s: &'a str,
ix: usize,
state: u8,
}
impl<'a> Iterator for LineBreakIterator<'a> {
type Item = (usize, bool);
// return break pos and whether it's a hard break
fn next(&mut self) -> Option<(usize, bool)> {
loop {
match self.ix.cmp(&self.s.len()) {
Ordering::Greater => {
return None;
}
Ordering::Equal => {
// LB3, break at EOT
self.ix += 1;
let i = (self.state as usize) * N_LINEBREAK_CATEGORIES;
let new = LINEBREAK_STATE_MACHINE[i];
return Some((self.s.len(), new >= 0xc0));
}
Ordering::Less => {
let (lb, len) = linebreak_property_str(self.s, self.ix);
let i = (self.state as usize) * N_LINEBREAK_CATEGORIES + (lb as usize);
let new = LINEBREAK_STATE_MACHINE[i];
//println!("{:?}[{}], state {} + lb {} -> {}", &self.s[self.ix..], self.ix, self.state, lb, new);
let result = self.ix;
self.ix += len;
if (new as i8) < 0 {
// break found
self.state = new & 0x3f;
return Some((result, new >= 0xc0));
} else {
self.state = new;
}
}
}
}
}
}
impl<'a> LineBreakIterator<'a> {
/// Create a new iterator for the given string slice.
pub fn new(s: &str) -> LineBreakIterator {
if s.is_empty() {
LineBreakIterator {
s,
ix: 1, // LB2, don't break; sot takes priority for empty string
state: 0,
}
} else {
let (lb, len) = linebreak_property_str(s, 0);
LineBreakIterator { s, ix: len, state: lb }
}
}
}
/// A struct useful for computing line breaks in a rope or other non-contiguous
/// string representation. This is a trickier problem than iterating in a string
/// for a few reasons, the trickiest of which is that in the general case,
/// line breaks require an indeterminate amount of look-behind.
///
/// This is something of an "expert-level" interface, and should only be used if
/// the caller is prepared to respect all the invariants. Otherwise, you might
/// get inconsistent breaks depending on start position and leaf boundaries.
#[derive(Copy, Clone)]
pub struct LineBreakLeafIter {
ix: usize,
state: u8,
}
#[allow(clippy::derivable_impls)]
impl Default for LineBreakLeafIter {
// A default value. No guarantees on what happens when next() is called
// on this. Intended to be useful for empty ropes.
fn default() -> LineBreakLeafIter {
LineBreakLeafIter { ix: 0, state: 0 }
}
}
impl LineBreakLeafIter {
/// Create a new line break iterator suitable for leaves in a rope.
/// Precondition: ix is at a code point boundary within s.
pub fn new(s: &str, ix: usize) -> LineBreakLeafIter {
let (lb, len) = if ix == s.len() { (0, 0) } else { linebreak_property_str(s, ix) };
LineBreakLeafIter { ix: ix + len, state: lb }
}
/// Return break pos and whether it's a hard break. Note: hard break
/// indication may go away, this may not be useful in actual application.
/// If end of leaf is found, return leaf's len. This does not indicate
/// a break, as that requires at least one more codepoint of context.
/// If it is a break, then subsequent next call will return an offset of 0.
/// EOT is always a break, so in the EOT case it's up to the caller
/// to figure that out.
///
/// For consistent results, always supply same `s` until end of leaf is
/// reached (and initially this should be the same as in the `new` call).
pub fn next(&mut self, s: &str) -> (usize, bool) {
loop {
if self.ix == s.len() {
self.ix = 0; // in preparation for next leaf
return (s.len(), false);
}
let (lb, len) = linebreak_property_str(s, self.ix);
let i = (self.state as usize) * N_LINEBREAK_CATEGORIES + (lb as usize);
let new = LINEBREAK_STATE_MACHINE[i];
//println!("\"{}\"[{}], state {} + lb {} -> {}", &s[self.ix..], self.ix, self.state, lb, new);
let result = self.ix;
self.ix += len;
if (new as i8) < 0 {
// break found
self.state = new & 0x3f;
return (result, new >= 0xc0);
} else {
self.state = new;
}
}
}
}
fn is_in_asc_list<T: core::cmp::PartialOrd>(c: T, list: &[T], start: usize, end: usize) -> bool {
if c == list[start] || c == list[end] {
return true;
}
if end - start <= 1 {
return false;
}
let mid = (start + end) / 2;
if c >= list[mid] {
is_in_asc_list(c, list, mid, end)
} else {
is_in_asc_list(c, list, start, mid)
}
}
pub fn is_variation_selector(c: char) -> bool {
('\u{FE00}'..='\u{FE0F}').contains(&c) || ('\u{E0100}'..='\u{E01EF}').contains(&c)
}
#[allow(clippy::wrong_self_convention)] // clippy wants &self for all of these
pub trait EmojiExt {
fn is_regional_indicator_symbol(self) -> bool;
fn is_emoji_modifier(self) -> bool;
fn is_emoji_combining_enclosing_keycap(self) -> bool;
fn is_emoji(self) -> bool;
fn is_emoji_modifier_base(self) -> bool;
fn is_tag_spec_char(self) -> bool;
fn is_emoji_cancel_tag(self) -> bool;
fn is_zwj(self) -> bool;
}
impl EmojiExt for char {
fn is_regional_indicator_symbol(self) -> bool {
('\u{1F1E6}'..='\u{1F1FF}').contains(&self)
}
fn is_emoji_modifier(self) -> bool {
('\u{1F3FB}'..='\u{1F3FF}').contains(&self)
}
fn is_emoji_combining_enclosing_keycap(self) -> bool {
self == '\u{20E3}'
}
fn is_emoji(self) -> bool {
is_in_asc_list(self, &EMOJI_TABLE, 0, EMOJI_TABLE.len() - 1)
}
fn is_emoji_modifier_base(self) -> bool {
is_in_asc_list(self, &EMOJI_MODIFIER_BASE_TABLE, 0, EMOJI_MODIFIER_BASE_TABLE.len() - 1)
}
fn is_tag_spec_char(self) -> bool {
('\u{E0020}'..='\u{E007E}').contains(&self)
}
fn is_emoji_cancel_tag(self) -> bool {
self == '\u{E007F}'
}
fn is_zwj(self) -> bool {
self == '\u{200D}'
}
}
pub fn is_keycap_base(c: char) -> bool {
('0'..='9').contains(&c) || c == '#' || c == '*'
}
#[cfg(test)]
mod tests {
use crate::linebreak_property;
use crate::linebreak_property_str;
use crate::LineBreakIterator;
use alloc::vec;
use alloc::vec::*;
#[test]
fn linebreak_prop() {
assert_eq!(9, linebreak_property('\u{0001}'));
assert_eq!(9, linebreak_property('\u{0003}'));
assert_eq!(9, linebreak_property('\u{0004}'));
assert_eq!(9, linebreak_property('\u{0008}'));
assert_eq!(10, linebreak_property('\u{000D}'));
assert_eq!(9, linebreak_property('\u{0010}'));
assert_eq!(9, linebreak_property('\u{0015}'));
assert_eq!(9, linebreak_property('\u{0018}'));
assert_eq!(22, linebreak_property('\u{002B}'));
assert_eq!(16, linebreak_property('\u{002C}'));
assert_eq!(13, linebreak_property('\u{002D}'));
assert_eq!(27, linebreak_property('\u{002F}'));
assert_eq!(19, linebreak_property('\u{0030}'));
assert_eq!(19, linebreak_property('\u{0038}'));
assert_eq!(19, linebreak_property('\u{0039}'));
assert_eq!(16, linebreak_property('\u{003B}'));
assert_eq!(2, linebreak_property('\u{003E}'));
assert_eq!(11, linebreak_property('\u{003F}'));
assert_eq!(2, linebreak_property('\u{0040}'));
assert_eq!(2, linebreak_property('\u{0055}'));
assert_eq!(2, linebreak_property('\u{0056}'));
assert_eq!(2, linebreak_property('\u{0058}'));
assert_eq!(2, linebreak_property('\u{0059}'));
assert_eq!(20, linebreak_property('\u{005B}'));
assert_eq!(22, linebreak_property('\u{005C}'));
assert_eq!(2, linebreak_property('\u{0062}'));
assert_eq!(2, linebreak_property('\u{006C}'));
assert_eq!(2, linebreak_property('\u{006D}'));
assert_eq!(2, linebreak_property('\u{0071}'));
assert_eq!(2, linebreak_property('\u{0074}'));
assert_eq!(2, linebreak_property('\u{0075}'));
assert_eq!(4, linebreak_property('\u{007C}'));
assert_eq!(9, linebreak_property('\u{009D}'));
assert_eq!(2, linebreak_property('\u{00D5}'));
assert_eq!(2, linebreak_property('\u{00D8}'));
assert_eq!(2, linebreak_property('\u{00E9}'));
assert_eq!(2, linebreak_property('\u{0120}'));
assert_eq!(2, linebreak_property('\u{0121}'));
assert_eq!(2, linebreak_property('\u{015C}'));
assert_eq!(2, linebreak_property('\u{016C}'));
assert_eq!(2, linebreak_property('\u{017E}'));
assert_eq!(2, linebreak_property('\u{01B0}'));
assert_eq!(2, linebreak_property('\u{0223}'));
assert_eq!(2, linebreak_property('\u{028D}'));
assert_eq!(2, linebreak_property('\u{02BE}'));
assert_eq!(1, linebreak_property('\u{02D0}'));
assert_eq!(9, linebreak_property('\u{0337}'));
assert_eq!(0, linebreak_property('\u{0380}'));
assert_eq!(2, linebreak_property('\u{04AA}'));
assert_eq!(2, linebreak_property('\u{04CE}'));
assert_eq!(2, linebreak_property('\u{04F1}'));
assert_eq!(2, linebreak_property('\u{0567}'));
assert_eq!(2, linebreak_property('\u{0580}'));
assert_eq!(9, linebreak_property('\u{05A1}'));
assert_eq!(9, linebreak_property('\u{05B0}'));
assert_eq!(38, linebreak_property('\u{05D4}'));
assert_eq!(2, linebreak_property('\u{0643}'));
assert_eq!(9, linebreak_property('\u{065D}'));
assert_eq!(19, linebreak_property('\u{066C}'));
assert_eq!(2, linebreak_property('\u{066E}'));
assert_eq!(2, linebreak_property('\u{068A}'));
assert_eq!(2, linebreak_property('\u{0776}'));
assert_eq!(2, linebreak_property('\u{07A2}'));
assert_eq!(0, linebreak_property('\u{07BB}'));
assert_eq!(19, linebreak_property('\u{1091}'));
assert_eq!(19, linebreak_property('\u{1B53}'));
assert_eq!(2, linebreak_property('\u{1EEA}'));
assert_eq!(42, linebreak_property('\u{200D}'));
assert_eq!(14, linebreak_property('\u{30C7}'));
assert_eq!(14, linebreak_property('\u{318B}'));
assert_eq!(14, linebreak_property('\u{3488}'));
assert_eq!(14, linebreak_property('\u{3B6E}'));
assert_eq!(14, linebreak_property('\u{475B}'));
assert_eq!(14, linebreak_property('\u{490B}'));
assert_eq!(14, linebreak_property('\u{5080}'));
assert_eq!(14, linebreak_property('\u{7846}'));
assert_eq!(14, linebreak_property('\u{7F3A}'));
assert_eq!(14, linebreak_property('\u{8B51}'));
assert_eq!(14, linebreak_property('\u{920F}'));
assert_eq!(14, linebreak_property('\u{9731}'));
assert_eq!(14, linebreak_property('\u{9F3A}'));
assert_eq!(2, linebreak_property('\u{ABD2}'));
assert_eq!(19, linebreak_property('\u{ABF6}'));
assert_eq!(32, linebreak_property('\u{B2EA}'));
assert_eq!(32, linebreak_property('\u{B3F5}'));
assert_eq!(32, linebreak_property('\u{B796}'));
assert_eq!(32, linebreak_property('\u{B9E8}'));
assert_eq!(32, linebreak_property('\u{BD42}'));
assert_eq!(32, linebreak_property('\u{C714}'));
assert_eq!(32, linebreak_property('\u{CC25}'));
assert_eq!(0, linebreak_property('\u{EA59}'));
assert_eq!(0, linebreak_property('\u{F6C8}'));
assert_eq!(0, linebreak_property('\u{F83C}'));
assert_eq!(2, linebreak_property('\u{FC6A}'));
assert_eq!(0, linebreak_property('\u{15199}'));
assert_eq!(0, linebreak_property('\u{163AC}'));
assert_eq!(0, linebreak_property('\u{1EF65}'));
assert_eq!(14, linebreak_property('\u{235A7}'));
assert_eq!(14, linebreak_property('\u{2E483}'));
assert_eq!(14, linebreak_property('\u{2FFFA}'));
assert_eq!(14, linebreak_property('\u{3613E}'));
assert_eq!(14, linebreak_property('\u{3799A}'));
assert_eq!(0, linebreak_property('\u{4DD35}'));
assert_eq!(0, linebreak_property('\u{5858D}'));
assert_eq!(0, linebreak_property('\u{585C2}'));
assert_eq!(0, linebreak_property('\u{6CF38}'));
assert_eq!(0, linebreak_property('\u{7573F}'));
assert_eq!(0, linebreak_property('\u{7AABF}'));
assert_eq!(0, linebreak_property('\u{87762}'));
assert_eq!(0, linebreak_property('\u{90297}'));
assert_eq!(0, linebreak_property('\u{9D037}'));
assert_eq!(0, linebreak_property('\u{A0E65}'));
assert_eq!(0, linebreak_property('\u{B8E7F}'));
assert_eq!(0, linebreak_property('\u{BBEA5}'));
assert_eq!(0, linebreak_property('\u{BE28C}'));
assert_eq!(0, linebreak_property('\u{C1B57}'));
assert_eq!(0, linebreak_property('\u{C2011}'));
assert_eq!(0, linebreak_property('\u{CBF32}'));
assert_eq!(0, linebreak_property('\u{DD9BD}'));
assert_eq!(0, linebreak_property('\u{DF4A6}'));
assert_eq!(0, linebreak_property('\u{E923D}'));
assert_eq!(0, linebreak_property('\u{E94DB}'));
assert_eq!(0, linebreak_property('\u{F90AB}'));
assert_eq!(0, linebreak_property('\u{100EF6}'));
assert_eq!(0, linebreak_property('\u{106487}'));
assert_eq!(0, linebreak_property('\u{1064B4}'));
}
#[test]
fn linebreak_prop_str() {
assert_eq!((9, 1), linebreak_property_str("\u{0004}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{0005}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{0008}", 0));
assert_eq!((4, 1), linebreak_property_str("\u{0009}", 0));
assert_eq!((17, 1), linebreak_property_str("\u{000A}", 0));
assert_eq!((6, 1), linebreak_property_str("\u{000C}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{000E}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{0010}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{0013}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{0017}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{001C}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{001D}", 0));
assert_eq!((9, 1), linebreak_property_str("\u{001F}", 0));
assert_eq!((11, 1), linebreak_property_str("\u{0021}", 0));
assert_eq!((23, 1), linebreak_property_str("\u{0027}", 0));
assert_eq!((22, 1), linebreak_property_str("\u{002B}", 0));
assert_eq!((13, 1), linebreak_property_str("\u{002D}", 0));
assert_eq!((27, 1), linebreak_property_str("\u{002F}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{003C}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0043}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{004B}", 0));
assert_eq!((36, 1), linebreak_property_str("\u{005D}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0060}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0065}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0066}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0068}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0069}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{006C}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{006D}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0077}", 0));
assert_eq!((2, 1), linebreak_property_str("\u{0079}", 0));
assert_eq!((4, 1), linebreak_property_str("\u{007C}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{008D}", 0));
assert_eq!((1, 2), linebreak_property_str("\u{00D7}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{015C}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{01B5}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{0216}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{0234}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{026E}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{027C}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{02BB}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{0313}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{0343}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{034A}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{0358}", 0));
assert_eq!((0, 2), linebreak_property_str("\u{0378}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{038C}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{03A4}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{03AC}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{041F}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{049A}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{04B4}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{04C6}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{0535}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{05B1}", 0));
assert_eq!((0, 2), linebreak_property_str("\u{05FF}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{065D}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{067E}", 0));
assert_eq!((19, 2), linebreak_property_str("\u{06F5}", 0));
assert_eq!((19, 2), linebreak_property_str("\u{06F6}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{0735}", 0));
assert_eq!((2, 2), linebreak_property_str("\u{074D}", 0));
assert_eq!((9, 2), linebreak_property_str("\u{07A6}", 0));
assert_eq!((0, 2), linebreak_property_str("\u{07B9}", 0));
assert_eq!((2, 3), linebreak_property_str("\u{131F}", 0));
assert_eq!((42, 3), linebreak_property_str("\u{200D}", 0));
assert_eq!((2, 3), linebreak_property_str("\u{25DA}", 0));
assert_eq!((2, 3), linebreak_property_str("\u{2C01}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{2EE5}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{4207}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{4824}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{491A}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{4C20}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{4D6A}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{50EB}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{521B}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{5979}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{5F9B}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{65AB}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{6B1F}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{7169}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{87CA}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{87FF}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{8A91}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{943A}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{9512}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{9D66}", 0));
assert_eq!((9, 3), linebreak_property_str("\u{A928}", 0));
assert_eq!((24, 3), linebreak_property_str("\u{AA7E}", 0));
assert_eq!((2, 3), linebreak_property_str("\u{AAEA}", 0));
assert_eq!((0, 3), linebreak_property_str("\u{AB66}", 0));
assert_eq!((32, 3), linebreak_property_str("\u{B9FC}", 0));
assert_eq!((32, 3), linebreak_property_str("\u{CD89}", 0));
assert_eq!((32, 3), linebreak_property_str("\u{CDB2}", 0));
assert_eq!((0, 3), linebreak_property_str("\u{F71D}", 0));
assert_eq!((14, 3), linebreak_property_str("\u{F9DF}", 0));
assert_eq!((2, 3), linebreak_property_str("\u{FEC3}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{13CC5}", 0));
assert_eq!((2, 4), linebreak_property_str("\u{1D945}", 0));
assert_eq!((40, 4), linebreak_property_str("\u{1F3C3}", 0));
assert_eq!((41, 4), linebreak_property_str("\u{1F3FB}", 0));
assert_eq!((14, 4), linebreak_property_str("\u{2BDCD}", 0));
assert_eq!((14, 4), linebreak_property_str("\u{3898E}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{45C35}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{4EC30}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{58EE2}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{5E3E8}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{5FB7D}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{6A564}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{6C591}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{6CA82}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{83839}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{88F47}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{91CA0}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{95644}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{AC335}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{AE8BF}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{B282B}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{B4CFC}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{BBED0}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{CCC89}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{D40EB}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{D65F5}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{D8E0B}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{DF93A}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{E4E2C}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{F7935}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{F9DFF}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{1094B7}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{10C782}", 0));
assert_eq!((0, 4), linebreak_property_str("\u{10E4D5}", 0));
}
#[test]
fn lb_iter_simple() {
assert_eq!(
vec![(6, false), (11, false)],
LineBreakIterator::new("hello world").collect::<Vec<_>>()
);
// LB7, LB18
assert_eq!(
vec![(3, false), (4, false)],
LineBreakIterator::new("a b").collect::<Vec<_>>()
);
// LB5
assert_eq!(vec![(2, true), (3, false)], LineBreakIterator::new("a\nb").collect::<Vec<_>>());
assert_eq!(
vec![(2, true), (4, true)],
LineBreakIterator::new("\r\n\r\n").collect::<Vec<_>>()
);
// LB8a
assert_eq!(
vec![(7, false)],
LineBreakIterator::new("\u{200D}\u{1F3FB}").collect::<Vec<_>>()
);
// LB10 combining mark after space
assert_eq!(
vec![(2, false), (4, false)],
LineBreakIterator::new("a \u{301}").collect::<Vec<_>>()
);
// LB15
assert_eq!(vec![(3, false)], LineBreakIterator::new("\" [").collect::<Vec<_>>());
// LB17
assert_eq!(
vec![(2, false), (10, false), (11, false)],
LineBreakIterator::new("a \u{2014} \u{2014} c").collect::<Vec<_>>()
);
// LB18
assert_eq!(
vec![(2, false), (6, false), (7, false)],
LineBreakIterator::new("a \"b\" c").collect::<Vec<_>>()
);
// LB21
assert_eq!(vec![(2, false), (3, false)], LineBreakIterator::new("a-b").collect::<Vec<_>>());
// LB21a
assert_eq!(
vec![(5, false)],
LineBreakIterator::new("\u{05D0}-\u{05D0}").collect::<Vec<_>>()
);
// LB23a
assert_eq!(vec![(6, false)], LineBreakIterator::new("$\u{1F3FB}%").collect::<Vec<_>>());
// LB30b
assert_eq!(
vec![(8, false)],
LineBreakIterator::new("\u{1F466}\u{1F3FB}").collect::<Vec<_>>()
);
// LB31
assert_eq!(
vec![(8, false), (16, false)],
LineBreakIterator::new("\u{1F1E6}\u{1F1E6}\u{1F1E6}\u{1F1E6}").collect::<Vec<_>>()
);
}
#[test]
// The final break is hard only when there is an explicit separator.
fn lb_iter_eot() {
assert_eq!(vec![(4, false)], LineBreakIterator::new("abc ").collect::<Vec<_>>());
assert_eq!(vec![(4, true)], LineBreakIterator::new("abc\r").collect::<Vec<_>>());
assert_eq!(vec![(5, true)], LineBreakIterator::new("abc\u{0085}").collect::<Vec<_>>());
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/unicode/src/emoji.rs | rust/unicode/src/emoji.rs | #[rustfmt::skip]
pub const EMOJI_TABLE: [char; 1250] = ['\u{23}', '\u{2A}', '\u{30}', '\u{31}', '\u{32}', '\u{33}', '\u{34}',
'\u{35}', '\u{36}', '\u{37}', '\u{38}', '\u{39}', '\u{A9}', '\u{AE}', '\u{203C}',
'\u{2049}', '\u{2122}', '\u{2139}', '\u{2194}', '\u{2195}', '\u{2196}', '\u{2197}', '\u{2198}',
'\u{2199}', '\u{21A9}', '\u{21AA}', '\u{231A}', '\u{231B}', '\u{2328}', '\u{23CF}', '\u{23E9}',
'\u{23EA}', '\u{23EB}', '\u{23EC}', '\u{23ED}', '\u{23EE}', '\u{23EF}', '\u{23F0}', '\u{23F1}',
'\u{23F2}', '\u{23F3}', '\u{23F8}', '\u{23F9}', '\u{23FA}', '\u{24C2}', '\u{25AA}', '\u{25AB}',
'\u{25B6}', '\u{25C0}', '\u{25FB}', '\u{25FC}', '\u{25FD}', '\u{25FE}', '\u{2600}', '\u{2601}',
'\u{2602}', '\u{2603}', '\u{2604}', '\u{260E}', '\u{2611}', '\u{2614}', '\u{2615}', '\u{2618}',
'\u{261D}', '\u{2620}', '\u{2622}', '\u{2623}', '\u{2626}', '\u{262A}', '\u{262E}', '\u{262F}',
'\u{2638}', '\u{2639}', '\u{263A}', '\u{2640}', '\u{2642}', '\u{2648}', '\u{2649}', '\u{264A}',
'\u{264B}', '\u{264C}', '\u{264D}', '\u{264E}', '\u{264F}', '\u{2650}', '\u{2651}', '\u{2652}',
'\u{2653}', '\u{265F}', '\u{2660}', '\u{2663}', '\u{2665}', '\u{2666}', '\u{2668}', '\u{267B}',
'\u{267E}', '\u{267F}', '\u{2692}', '\u{2693}', '\u{2694}', '\u{2695}', '\u{2696}', '\u{2697}',
'\u{2699}', '\u{269B}', '\u{269C}', '\u{26A0}', '\u{26A1}', '\u{26AA}', '\u{26AB}', '\u{26B0}',
'\u{26B1}', '\u{26BD}', '\u{26BE}', '\u{26C4}', '\u{26C5}', '\u{26C8}', '\u{26CE}', '\u{26CF}',
'\u{26D1}', '\u{26D3}', '\u{26D4}', '\u{26E9}', '\u{26EA}', '\u{26F0}', '\u{26F1}', '\u{26F2}',
'\u{26F3}', '\u{26F4}', '\u{26F5}', '\u{26F7}', '\u{26F8}', '\u{26F9}', '\u{26FA}', '\u{26FD}',
'\u{2702}', '\u{2705}', '\u{2708}', '\u{2709}', '\u{270A}', '\u{270B}', '\u{270C}', '\u{270D}',
'\u{270F}', '\u{2712}', '\u{2714}', '\u{2716}', '\u{271D}', '\u{2721}', '\u{2728}', '\u{2733}',
'\u{2734}', '\u{2744}', '\u{2747}', '\u{274C}', '\u{274E}', '\u{2753}', '\u{2754}', '\u{2755}',
'\u{2757}', '\u{2763}', '\u{2764}', '\u{2795}', '\u{2796}', '\u{2797}', '\u{27A1}', '\u{27B0}',
'\u{27BF}', '\u{2934}', '\u{2935}', '\u{2B05}', '\u{2B06}', '\u{2B07}', '\u{2B1B}', '\u{2B1C}',
'\u{2B50}', '\u{2B55}', '\u{3030}', '\u{303D}', '\u{3297}', '\u{3299}', '\u{1F004}', '\u{1F0CF}',
'\u{1F170}', '\u{1F171}', '\u{1F17E}', '\u{1F17F}', '\u{1F18E}', '\u{1F191}', '\u{1F192}', '\u{1F193}',
'\u{1F194}', '\u{1F195}', '\u{1F196}', '\u{1F197}', '\u{1F198}', '\u{1F199}', '\u{1F19A}', '\u{1F1E6}',
'\u{1F1E7}', '\u{1F1E8}', '\u{1F1E9}', '\u{1F1EA}', '\u{1F1EB}', '\u{1F1EC}', '\u{1F1ED}', '\u{1F1EE}',
'\u{1F1EF}', '\u{1F1F0}', '\u{1F1F1}', '\u{1F1F2}', '\u{1F1F3}', '\u{1F1F4}', '\u{1F1F5}', '\u{1F1F6}',
'\u{1F1F7}', '\u{1F1F8}', '\u{1F1F9}', '\u{1F1FA}', '\u{1F1FB}', '\u{1F1FC}', '\u{1F1FD}', '\u{1F1FE}',
'\u{1F1FF}', '\u{1F201}', '\u{1F202}', '\u{1F21A}', '\u{1F22F}', '\u{1F232}', '\u{1F233}', '\u{1F234}',
'\u{1F235}', '\u{1F236}', '\u{1F237}', '\u{1F238}', '\u{1F239}', '\u{1F23A}', '\u{1F250}', '\u{1F251}',
'\u{1F300}', '\u{1F301}', '\u{1F302}', '\u{1F303}', '\u{1F304}', '\u{1F305}', '\u{1F306}', '\u{1F307}',
'\u{1F308}', '\u{1F309}', '\u{1F30A}', '\u{1F30B}', '\u{1F30C}', '\u{1F30D}', '\u{1F30E}', '\u{1F30F}',
'\u{1F310}', '\u{1F311}', '\u{1F312}', '\u{1F313}', '\u{1F314}', '\u{1F315}', '\u{1F316}', '\u{1F317}',
'\u{1F318}', '\u{1F319}', '\u{1F31A}', '\u{1F31B}', '\u{1F31C}', '\u{1F31D}', '\u{1F31E}', '\u{1F31F}',
'\u{1F320}', '\u{1F321}', '\u{1F324}', '\u{1F325}', '\u{1F326}', '\u{1F327}', '\u{1F328}', '\u{1F329}',
'\u{1F32A}', '\u{1F32B}', '\u{1F32C}', '\u{1F32D}', '\u{1F32E}', '\u{1F32F}', '\u{1F330}', '\u{1F331}',
'\u{1F332}', '\u{1F333}', '\u{1F334}', '\u{1F335}', '\u{1F336}', '\u{1F337}', '\u{1F338}', '\u{1F339}',
'\u{1F33A}', '\u{1F33B}', '\u{1F33C}', '\u{1F33D}', '\u{1F33E}', '\u{1F33F}', '\u{1F340}', '\u{1F341}',
'\u{1F342}', '\u{1F343}', '\u{1F344}', '\u{1F345}', '\u{1F346}', '\u{1F347}', '\u{1F348}', '\u{1F349}',
'\u{1F34A}', '\u{1F34B}', '\u{1F34C}', '\u{1F34D}', '\u{1F34E}', '\u{1F34F}', '\u{1F350}', '\u{1F351}',
'\u{1F352}', '\u{1F353}', '\u{1F354}', '\u{1F355}', '\u{1F356}', '\u{1F357}', '\u{1F358}', '\u{1F359}',
'\u{1F35A}', '\u{1F35B}', '\u{1F35C}', '\u{1F35D}', '\u{1F35E}', '\u{1F35F}', '\u{1F360}', '\u{1F361}',
'\u{1F362}', '\u{1F363}', '\u{1F364}', '\u{1F365}', '\u{1F366}', '\u{1F367}', '\u{1F368}', '\u{1F369}',
'\u{1F36A}', '\u{1F36B}', '\u{1F36C}', '\u{1F36D}', '\u{1F36E}', '\u{1F36F}', '\u{1F370}', '\u{1F371}',
'\u{1F372}', '\u{1F373}', '\u{1F374}', '\u{1F375}', '\u{1F376}', '\u{1F377}', '\u{1F378}', '\u{1F379}',
'\u{1F37A}', '\u{1F37B}', '\u{1F37C}', '\u{1F37D}', '\u{1F37E}', '\u{1F37F}', '\u{1F380}', '\u{1F381}',
'\u{1F382}', '\u{1F383}', '\u{1F384}', '\u{1F385}', '\u{1F386}', '\u{1F387}', '\u{1F388}', '\u{1F389}',
'\u{1F38A}', '\u{1F38B}', '\u{1F38C}', '\u{1F38D}', '\u{1F38E}', '\u{1F38F}', '\u{1F390}', '\u{1F391}',
'\u{1F392}', '\u{1F393}', '\u{1F396}', '\u{1F397}', '\u{1F399}', '\u{1F39A}', '\u{1F39B}', '\u{1F39E}',
'\u{1F39F}', '\u{1F3A0}', '\u{1F3A1}', '\u{1F3A2}', '\u{1F3A3}', '\u{1F3A4}', '\u{1F3A5}', '\u{1F3A6}',
'\u{1F3A7}', '\u{1F3A8}', '\u{1F3A9}', '\u{1F3AA}', '\u{1F3AB}', '\u{1F3AC}', '\u{1F3AD}', '\u{1F3AE}',
'\u{1F3AF}', '\u{1F3B0}', '\u{1F3B1}', '\u{1F3B2}', '\u{1F3B3}', '\u{1F3B4}', '\u{1F3B5}', '\u{1F3B6}',
'\u{1F3B7}', '\u{1F3B8}', '\u{1F3B9}', '\u{1F3BA}', '\u{1F3BB}', '\u{1F3BC}', '\u{1F3BD}', '\u{1F3BE}',
'\u{1F3BF}', '\u{1F3C0}', '\u{1F3C1}', '\u{1F3C2}', '\u{1F3C3}', '\u{1F3C4}', '\u{1F3C5}', '\u{1F3C6}',
'\u{1F3C7}', '\u{1F3C8}', '\u{1F3C9}', '\u{1F3CA}', '\u{1F3CB}', '\u{1F3CC}', '\u{1F3CD}', '\u{1F3CE}',
'\u{1F3CF}', '\u{1F3D0}', '\u{1F3D1}', '\u{1F3D2}', '\u{1F3D3}', '\u{1F3D4}', '\u{1F3D5}', '\u{1F3D6}',
'\u{1F3D7}', '\u{1F3D8}', '\u{1F3D9}', '\u{1F3DA}', '\u{1F3DB}', '\u{1F3DC}', '\u{1F3DD}', '\u{1F3DE}',
'\u{1F3DF}', '\u{1F3E0}', '\u{1F3E1}', '\u{1F3E2}', '\u{1F3E3}', '\u{1F3E4}', '\u{1F3E5}', '\u{1F3E6}',
'\u{1F3E7}', '\u{1F3E8}', '\u{1F3E9}', '\u{1F3EA}', '\u{1F3EB}', '\u{1F3EC}', '\u{1F3ED}', '\u{1F3EE}',
'\u{1F3EF}', '\u{1F3F0}', '\u{1F3F3}', '\u{1F3F4}', '\u{1F3F5}', '\u{1F3F7}', '\u{1F3F8}', '\u{1F3F9}',
'\u{1F3FA}', '\u{1F3FB}', '\u{1F3FC}', '\u{1F3FD}', '\u{1F3FE}', '\u{1F3FF}', '\u{1F400}', '\u{1F401}',
'\u{1F402}', '\u{1F403}', '\u{1F404}', '\u{1F405}', '\u{1F406}', '\u{1F407}', '\u{1F408}', '\u{1F409}',
'\u{1F40A}', '\u{1F40B}', '\u{1F40C}', '\u{1F40D}', '\u{1F40E}', '\u{1F40F}', '\u{1F410}', '\u{1F411}',
'\u{1F412}', '\u{1F413}', '\u{1F414}', '\u{1F415}', '\u{1F416}', '\u{1F417}', '\u{1F418}', '\u{1F419}',
'\u{1F41A}', '\u{1F41B}', '\u{1F41C}', '\u{1F41D}', '\u{1F41E}', '\u{1F41F}', '\u{1F420}', '\u{1F421}',
'\u{1F422}', '\u{1F423}', '\u{1F424}', '\u{1F425}', '\u{1F426}', '\u{1F427}', '\u{1F428}', '\u{1F429}',
'\u{1F42A}', '\u{1F42B}', '\u{1F42C}', '\u{1F42D}', '\u{1F42E}', '\u{1F42F}', '\u{1F430}', '\u{1F431}',
'\u{1F432}', '\u{1F433}', '\u{1F434}', '\u{1F435}', '\u{1F436}', '\u{1F437}', '\u{1F438}', '\u{1F439}',
'\u{1F43A}', '\u{1F43B}', '\u{1F43C}', '\u{1F43D}', '\u{1F43E}', '\u{1F43F}', '\u{1F440}', '\u{1F441}',
'\u{1F442}', '\u{1F443}', '\u{1F444}', '\u{1F445}', '\u{1F446}', '\u{1F447}', '\u{1F448}', '\u{1F449}',
'\u{1F44A}', '\u{1F44B}', '\u{1F44C}', '\u{1F44D}', '\u{1F44E}', '\u{1F44F}', '\u{1F450}', '\u{1F451}',
'\u{1F452}', '\u{1F453}', '\u{1F454}', '\u{1F455}', '\u{1F456}', '\u{1F457}', '\u{1F458}', '\u{1F459}',
'\u{1F45A}', '\u{1F45B}', '\u{1F45C}', '\u{1F45D}', '\u{1F45E}', '\u{1F45F}', '\u{1F460}', '\u{1F461}',
'\u{1F462}', '\u{1F463}', '\u{1F464}', '\u{1F465}', '\u{1F466}', '\u{1F467}', '\u{1F468}', '\u{1F469}',
'\u{1F46A}', '\u{1F46B}', '\u{1F46C}', '\u{1F46D}', '\u{1F46E}', '\u{1F46F}', '\u{1F470}', '\u{1F471}',
'\u{1F472}', '\u{1F473}', '\u{1F474}', '\u{1F475}', '\u{1F476}', '\u{1F477}', '\u{1F478}', '\u{1F479}',
'\u{1F47A}', '\u{1F47B}', '\u{1F47C}', '\u{1F47D}', '\u{1F47E}', '\u{1F47F}', '\u{1F480}', '\u{1F481}',
'\u{1F482}', '\u{1F483}', '\u{1F484}', '\u{1F485}', '\u{1F486}', '\u{1F487}', '\u{1F488}', '\u{1F489}',
'\u{1F48A}', '\u{1F48B}', '\u{1F48C}', '\u{1F48D}', '\u{1F48E}', '\u{1F48F}', '\u{1F490}', '\u{1F491}',
'\u{1F492}', '\u{1F493}', '\u{1F494}', '\u{1F495}', '\u{1F496}', '\u{1F497}', '\u{1F498}', '\u{1F499}',
'\u{1F49A}', '\u{1F49B}', '\u{1F49C}', '\u{1F49D}', '\u{1F49E}', '\u{1F49F}', '\u{1F4A0}', '\u{1F4A1}',
'\u{1F4A2}', '\u{1F4A3}', '\u{1F4A4}', '\u{1F4A5}', '\u{1F4A6}', '\u{1F4A7}', '\u{1F4A8}', '\u{1F4A9}',
'\u{1F4AA}', '\u{1F4AB}', '\u{1F4AC}', '\u{1F4AD}', '\u{1F4AE}', '\u{1F4AF}', '\u{1F4B0}', '\u{1F4B1}',
'\u{1F4B2}', '\u{1F4B3}', '\u{1F4B4}', '\u{1F4B5}', '\u{1F4B6}', '\u{1F4B7}', '\u{1F4B8}', '\u{1F4B9}',
'\u{1F4BA}', '\u{1F4BB}', '\u{1F4BC}', '\u{1F4BD}', '\u{1F4BE}', '\u{1F4BF}', '\u{1F4C0}', '\u{1F4C1}',
'\u{1F4C2}', '\u{1F4C3}', '\u{1F4C4}', '\u{1F4C5}', '\u{1F4C6}', '\u{1F4C7}', '\u{1F4C8}', '\u{1F4C9}',
'\u{1F4CA}', '\u{1F4CB}', '\u{1F4CC}', '\u{1F4CD}', '\u{1F4CE}', '\u{1F4CF}', '\u{1F4D0}', '\u{1F4D1}',
'\u{1F4D2}', '\u{1F4D3}', '\u{1F4D4}', '\u{1F4D5}', '\u{1F4D6}', '\u{1F4D7}', '\u{1F4D8}', '\u{1F4D9}',
'\u{1F4DA}', '\u{1F4DB}', '\u{1F4DC}', '\u{1F4DD}', '\u{1F4DE}', '\u{1F4DF}', '\u{1F4E0}', '\u{1F4E1}',
'\u{1F4E2}', '\u{1F4E3}', '\u{1F4E4}', '\u{1F4E5}', '\u{1F4E6}', '\u{1F4E7}', '\u{1F4E8}', '\u{1F4E9}',
'\u{1F4EA}', '\u{1F4EB}', '\u{1F4EC}', '\u{1F4ED}', '\u{1F4EE}', '\u{1F4EF}', '\u{1F4F0}', '\u{1F4F1}',
'\u{1F4F2}', '\u{1F4F3}', '\u{1F4F4}', '\u{1F4F5}', '\u{1F4F6}', '\u{1F4F7}', '\u{1F4F8}', '\u{1F4F9}',
'\u{1F4FA}', '\u{1F4FB}', '\u{1F4FC}', '\u{1F4FD}', '\u{1F4FF}', '\u{1F500}', '\u{1F501}', '\u{1F502}',
'\u{1F503}', '\u{1F504}', '\u{1F505}', '\u{1F506}', '\u{1F507}', '\u{1F508}', '\u{1F509}', '\u{1F50A}',
'\u{1F50B}', '\u{1F50C}', '\u{1F50D}', '\u{1F50E}', '\u{1F50F}', '\u{1F510}', '\u{1F511}', '\u{1F512}',
'\u{1F513}', '\u{1F514}', '\u{1F515}', '\u{1F516}', '\u{1F517}', '\u{1F518}', '\u{1F519}', '\u{1F51A}',
'\u{1F51B}', '\u{1F51C}', '\u{1F51D}', '\u{1F51E}', '\u{1F51F}', '\u{1F520}', '\u{1F521}', '\u{1F522}',
'\u{1F523}', '\u{1F524}', '\u{1F525}', '\u{1F526}', '\u{1F527}', '\u{1F528}', '\u{1F529}', '\u{1F52A}',
'\u{1F52B}', '\u{1F52C}', '\u{1F52D}', '\u{1F52E}', '\u{1F52F}', '\u{1F530}', '\u{1F531}', '\u{1F532}',
'\u{1F533}', '\u{1F534}', '\u{1F535}', '\u{1F536}', '\u{1F537}', '\u{1F538}', '\u{1F539}', '\u{1F53A}',
'\u{1F53B}', '\u{1F53C}', '\u{1F53D}', '\u{1F549}', '\u{1F54A}', '\u{1F54B}', '\u{1F54C}', '\u{1F54D}',
'\u{1F54E}', '\u{1F550}', '\u{1F551}', '\u{1F552}', '\u{1F553}', '\u{1F554}', '\u{1F555}', '\u{1F556}',
'\u{1F557}', '\u{1F558}', '\u{1F559}', '\u{1F55A}', '\u{1F55B}', '\u{1F55C}', '\u{1F55D}', '\u{1F55E}',
'\u{1F55F}', '\u{1F560}', '\u{1F561}', '\u{1F562}', '\u{1F563}', '\u{1F564}', '\u{1F565}', '\u{1F566}',
'\u{1F567}', '\u{1F56F}', '\u{1F570}', '\u{1F573}', '\u{1F574}', '\u{1F575}', '\u{1F576}', '\u{1F577}',
'\u{1F578}', '\u{1F579}', '\u{1F57A}', '\u{1F587}', '\u{1F58A}', '\u{1F58B}', '\u{1F58C}', '\u{1F58D}',
'\u{1F590}', '\u{1F595}', '\u{1F596}', '\u{1F5A4}', '\u{1F5A5}', '\u{1F5A8}', '\u{1F5B1}', '\u{1F5B2}',
'\u{1F5BC}', '\u{1F5C2}', '\u{1F5C3}', '\u{1F5C4}', '\u{1F5D1}', '\u{1F5D2}', '\u{1F5D3}', '\u{1F5DC}',
'\u{1F5DD}', '\u{1F5DE}', '\u{1F5E1}', '\u{1F5E3}', '\u{1F5E8}', '\u{1F5EF}', '\u{1F5F3}', '\u{1F5FA}',
'\u{1F5FB}', '\u{1F5FC}', '\u{1F5FD}', '\u{1F5FE}', '\u{1F5FF}', '\u{1F600}', '\u{1F601}', '\u{1F602}',
'\u{1F603}', '\u{1F604}', '\u{1F605}', '\u{1F606}', '\u{1F607}', '\u{1F608}', '\u{1F609}', '\u{1F60A}',
'\u{1F60B}', '\u{1F60C}', '\u{1F60D}', '\u{1F60E}', '\u{1F60F}', '\u{1F610}', '\u{1F611}', '\u{1F612}',
'\u{1F613}', '\u{1F614}', '\u{1F615}', '\u{1F616}', '\u{1F617}', '\u{1F618}', '\u{1F619}', '\u{1F61A}',
'\u{1F61B}', '\u{1F61C}', '\u{1F61D}', '\u{1F61E}', '\u{1F61F}', '\u{1F620}', '\u{1F621}', '\u{1F622}',
'\u{1F623}', '\u{1F624}', '\u{1F625}', '\u{1F626}', '\u{1F627}', '\u{1F628}', '\u{1F629}', '\u{1F62A}',
'\u{1F62B}', '\u{1F62C}', '\u{1F62D}', '\u{1F62E}', '\u{1F62F}', '\u{1F630}', '\u{1F631}', '\u{1F632}',
'\u{1F633}', '\u{1F634}', '\u{1F635}', '\u{1F636}', '\u{1F637}', '\u{1F638}', '\u{1F639}', '\u{1F63A}',
'\u{1F63B}', '\u{1F63C}', '\u{1F63D}', '\u{1F63E}', '\u{1F63F}', '\u{1F640}', '\u{1F641}', '\u{1F642}',
'\u{1F643}', '\u{1F644}', '\u{1F645}', '\u{1F646}', '\u{1F647}', '\u{1F648}', '\u{1F649}', '\u{1F64A}',
'\u{1F64B}', '\u{1F64C}', '\u{1F64D}', '\u{1F64E}', '\u{1F64F}', '\u{1F680}', '\u{1F681}', '\u{1F682}',
'\u{1F683}', '\u{1F684}', '\u{1F685}', '\u{1F686}', '\u{1F687}', '\u{1F688}', '\u{1F689}', '\u{1F68A}',
'\u{1F68B}', '\u{1F68C}', '\u{1F68D}', '\u{1F68E}', '\u{1F68F}', '\u{1F690}', '\u{1F691}', '\u{1F692}',
'\u{1F693}', '\u{1F694}', '\u{1F695}', '\u{1F696}', '\u{1F697}', '\u{1F698}', '\u{1F699}', '\u{1F69A}',
'\u{1F69B}', '\u{1F69C}', '\u{1F69D}', '\u{1F69E}', '\u{1F69F}', '\u{1F6A0}', '\u{1F6A1}', '\u{1F6A2}',
'\u{1F6A3}', '\u{1F6A4}', '\u{1F6A5}', '\u{1F6A6}', '\u{1F6A7}', '\u{1F6A8}', '\u{1F6A9}', '\u{1F6AA}',
'\u{1F6AB}', '\u{1F6AC}', '\u{1F6AD}', '\u{1F6AE}', '\u{1F6AF}', '\u{1F6B0}', '\u{1F6B1}', '\u{1F6B2}',
'\u{1F6B3}', '\u{1F6B4}', '\u{1F6B5}', '\u{1F6B6}', '\u{1F6B7}', '\u{1F6B8}', '\u{1F6B9}', '\u{1F6BA}',
'\u{1F6BB}', '\u{1F6BC}', '\u{1F6BD}', '\u{1F6BE}', '\u{1F6BF}', '\u{1F6C0}', '\u{1F6C1}', '\u{1F6C2}',
'\u{1F6C3}', '\u{1F6C4}', '\u{1F6C5}', '\u{1F6CB}', '\u{1F6CC}', '\u{1F6CD}', '\u{1F6CE}', '\u{1F6CF}',
'\u{1F6D0}', '\u{1F6D1}', '\u{1F6D2}', '\u{1F6E0}', '\u{1F6E1}', '\u{1F6E2}', '\u{1F6E3}', '\u{1F6E4}',
'\u{1F6E5}', '\u{1F6E9}', '\u{1F6EB}', '\u{1F6EC}', '\u{1F6F0}', '\u{1F6F3}', '\u{1F6F4}', '\u{1F6F5}',
'\u{1F6F6}', '\u{1F6F7}', '\u{1F6F8}', '\u{1F6F9}', '\u{1F910}', '\u{1F911}', '\u{1F912}', '\u{1F913}',
'\u{1F914}', '\u{1F915}', '\u{1F916}', '\u{1F917}', '\u{1F918}', '\u{1F919}', '\u{1F91A}', '\u{1F91B}',
'\u{1F91C}', '\u{1F91D}', '\u{1F91E}', '\u{1F91F}', '\u{1F920}', '\u{1F921}', '\u{1F922}', '\u{1F923}',
'\u{1F924}', '\u{1F925}', '\u{1F926}', '\u{1F927}', '\u{1F928}', '\u{1F929}', '\u{1F92A}', '\u{1F92B}',
'\u{1F92C}', '\u{1F92D}', '\u{1F92E}', '\u{1F92F}', '\u{1F930}', '\u{1F931}', '\u{1F932}', '\u{1F933}',
'\u{1F934}', '\u{1F935}', '\u{1F936}', '\u{1F937}', '\u{1F938}', '\u{1F939}', '\u{1F93A}', '\u{1F93C}',
'\u{1F93D}', '\u{1F93E}', '\u{1F940}', '\u{1F941}', '\u{1F942}', '\u{1F943}', '\u{1F944}', '\u{1F945}',
'\u{1F947}', '\u{1F948}', '\u{1F949}', '\u{1F94A}', '\u{1F94B}', '\u{1F94C}', '\u{1F94D}', '\u{1F94E}',
'\u{1F94F}', '\u{1F950}', '\u{1F951}', '\u{1F952}', '\u{1F953}', '\u{1F954}', '\u{1F955}', '\u{1F956}',
'\u{1F957}', '\u{1F958}', '\u{1F959}', '\u{1F95A}', '\u{1F95B}', '\u{1F95C}', '\u{1F95D}', '\u{1F95E}',
'\u{1F95F}', '\u{1F960}', '\u{1F961}', '\u{1F962}', '\u{1F963}', '\u{1F964}', '\u{1F965}', '\u{1F966}',
'\u{1F967}', '\u{1F968}', '\u{1F969}', '\u{1F96A}', '\u{1F96B}', '\u{1F96C}', '\u{1F96D}', '\u{1F96E}',
'\u{1F96F}', '\u{1F970}', '\u{1F973}', '\u{1F974}', '\u{1F975}', '\u{1F976}', '\u{1F97A}', '\u{1F97C}',
'\u{1F97D}', '\u{1F97E}', '\u{1F97F}', '\u{1F980}', '\u{1F981}', '\u{1F982}', '\u{1F983}', '\u{1F984}',
'\u{1F985}', '\u{1F986}', '\u{1F987}', '\u{1F988}', '\u{1F989}', '\u{1F98A}', '\u{1F98B}', '\u{1F98C}',
'\u{1F98D}', '\u{1F98E}', '\u{1F98F}', '\u{1F990}', '\u{1F991}', '\u{1F992}', '\u{1F993}', '\u{1F994}',
'\u{1F995}', '\u{1F996}', '\u{1F997}', '\u{1F998}', '\u{1F999}', '\u{1F99A}', '\u{1F99B}', '\u{1F99C}',
'\u{1F99D}', '\u{1F99E}', '\u{1F99F}', '\u{1F9A0}', '\u{1F9A1}', '\u{1F9A2}', '\u{1F9B0}', '\u{1F9B1}',
'\u{1F9B2}', '\u{1F9B3}', '\u{1F9B4}', '\u{1F9B5}', '\u{1F9B6}', '\u{1F9B7}', '\u{1F9B8}', '\u{1F9B9}',
'\u{1F9C0}', '\u{1F9C1}', '\u{1F9C2}', '\u{1F9D0}', '\u{1F9D1}', '\u{1F9D2}', '\u{1F9D3}', '\u{1F9D4}',
'\u{1F9D5}', '\u{1F9D6}', '\u{1F9D7}', '\u{1F9D8}', '\u{1F9D9}', '\u{1F9DA}', '\u{1F9DB}', '\u{1F9DC}',
'\u{1F9DD}', '\u{1F9DE}', '\u{1F9DF}', '\u{1F9E0}', '\u{1F9E1}', '\u{1F9E2}', '\u{1F9E3}', '\u{1F9E4}',
'\u{1F9E5}', '\u{1F9E6}', '\u{1F9E7}', '\u{1F9E8}', '\u{1F9E9}', '\u{1F9EA}', '\u{1F9EB}', '\u{1F9EC}',
'\u{1F9ED}', '\u{1F9EE}', '\u{1F9EF}', '\u{1F9F0}', '\u{1F9F1}', '\u{1F9F2}', '\u{1F9F3}', '\u{1F9F4}',
'\u{1F9F5}', '\u{1F9F6}', '\u{1F9F7}', '\u{1F9F8}', '\u{1F9F9}', '\u{1F9FA}', '\u{1F9FB}', '\u{1F9FC}',
'\u{1F9FD}', '\u{1F9FE}', '\u{1F9FF}'];
#[rustfmt::skip]
pub const EMOJI_MODIFIER_BASE_TABLE: [char; 106] = ['\u{261D}', '\u{26F9}', '\u{270A}', '\u{270B}',
'\u{270C}', '\u{270D}', '\u{1F385}', '\u{1F3C2}', '\u{1F3C3}', '\u{1F3C4}', '\u{1F3C7}', '\u{1F3CA}',
'\u{1F3CB}', '\u{1F3CC}', '\u{1F442}', '\u{1F443}', '\u{1F446}', '\u{1F447}', '\u{1F448}', '\u{1F449}',
'\u{1F44A}', '\u{1F44B}', '\u{1F44C}', '\u{1F44D}', '\u{1F44E}', '\u{1F44F}', '\u{1F450}', '\u{1F466}',
'\u{1F467}', '\u{1F468}', '\u{1F469}', '\u{1F46E}', '\u{1F470}', '\u{1F471}', '\u{1F472}', '\u{1F473}',
'\u{1F474}', '\u{1F475}', '\u{1F476}', '\u{1F477}', '\u{1F478}', '\u{1F47C}', '\u{1F481}', '\u{1F482}',
'\u{1F483}', '\u{1F485}', '\u{1F486}', '\u{1F487}', '\u{1F4AA}', '\u{1F574}', '\u{1F575}', '\u{1F57A}',
'\u{1F590}', '\u{1F595}', '\u{1F596}', '\u{1F645}', '\u{1F646}', '\u{1F647}', '\u{1F64B}', '\u{1F64C}',
'\u{1F64D}', '\u{1F64E}', '\u{1F64F}', '\u{1F6A3}', '\u{1F6B4}', '\u{1F6B5}', '\u{1F6B6}', '\u{1F6C0}',
'\u{1F6CC}', '\u{1F918}', '\u{1F919}', '\u{1F91A}', '\u{1F91B}', '\u{1F91C}', '\u{1F91E}', '\u{1F91F}',
'\u{1F926}', '\u{1F930}', '\u{1F931}', '\u{1F932}', '\u{1F933}', '\u{1F934}', '\u{1F935}', '\u{1F936}',
'\u{1F937}', '\u{1F938}', '\u{1F939}', '\u{1F93D}', '\u{1F93E}', '\u{1F9B5}', '\u{1F9B6}', '\u{1F9B8}',
'\u{1F9B9}', '\u{1F9D1}', '\u{1F9D2}', '\u{1F9D3}', '\u{1F9D4}', '\u{1F9D5}', '\u{1F9D6}', '\u{1F9D7}',
'\u{1F9D8}', '\u{1F9D9}', '\u{1F9DA}', '\u{1F9DB}', '\u{1F9DC}', '\u{1F9DD}'];
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/unicode/src/tables.rs | rust/unicode/src/tables.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Raw trie data for linebreak property lookup.
// This file autogenerated from LineBreak-10.0.0.txt by mk_tables.py
#[rustfmt::skip]
pub const LINEBREAK_1_2: [u8; 2048] = [
9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 17, 6, 6, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 26, 11, 23, 2, 22, 21, 2, 23, 20, 36, 2, 22, 16, 13,
16, 27, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 16, 16, 2, 2, 2, 11, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
20, 22, 36, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 20, 4, 8, 2, 9, 9, 9, 9, 9, 9, 29, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 12, 20, 21, 22,
22, 22, 2, 1, 1, 2, 1, 23, 2, 4, 2, 2, 21, 22, 1, 1, 5, 2, 1, 1, 1, 1, 1,
23, 1, 1, 1, 20, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
5, 1, 1, 1, 5, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 2, 1, 2, 5, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 12, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 12,
12, 12, 12, 12, 12, 12, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2,
2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 16, 2, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 9,
9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 0, 16, 4, 0, 0, 2, 2, 22, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 9, 2, 9, 9, 2, 9, 9, 11, 9, 0, 0, 0, 0,
0, 0, 0, 0, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38,
38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 0, 0, 0, 0, 0, 38, 38, 38, 2, 2,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 21, 21, 21, 16,
16, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, 9, 0, 11, 11, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 21, 19,
19, 2, 2, 2, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 11, 2, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9,
2, 9, 9, 9, 9, 2, 2, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 9, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2,
2, 2, 16, 11, 2, 0, 0, 0, 0, 0,
];
#[rustfmt::skip]
pub const LINEBREAK_3_ROOT: [u8; 1024] = [
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 40, 40, 40, 40, 40, 40, 40, 40,
40, 49, 50, 51, 52, 32, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,
66, 67, 68, 69, 70, 71, 72, 73, 40, 40, 40, 74, 40, 40, 40, 40, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 40, 40, 92, 93, 94,
95, 96, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 40, 40, 40,
40, 40, 40, 108, 109, 40, 40, 40, 40, 40, 110, 111, 112, 113, 114, 40, 115,
116, 117, 118, 119, 120, 121, 122, 123, 124, 124, 124, 125, 126, 127, 128,
129, 130, 124, 131, 132, 133, 134, 124, 135, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 40, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 136, 124, 124, 124, 124,
124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 137, 138,
40, 40, 40, 40, 139, 140, 141, 142, 40, 40, 143, 144, 145, 146, 147, 148,
149, 150, 151, 152, 153, 154, 32, 155, 156, 157, 40, 158, 159, 160, 161,
162, 163, 164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162,
163, 164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163,
164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163, 164,
165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163, 164, 165,
159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163, 164, 165, 159,
160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160,
161, 162, 163, 164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161,
162, 163, 164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162,
163, 164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163,
164, 165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163, 164,
165, 159, 160, 161, 162, 163, 164, 165, 159, 160, 161, 162, 163, 164, 165,
159, 160, 161, 162, 163, 164, 166, 167, 168, 168, 168, 168, 168, 168, 168,
168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 168,
168, 168, 168, 168, 168, 168, 168, 168, 168, 168, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 124,
124, 124, 124, 124, 124, 124, 124, 169, 170, 40, 171, 40, 40, 40, 40, 172,
173, 174, 175, 176, 177, 40, 178, 179, 180, 181, 182,
];
#[rustfmt::skip]
pub const LINEBREAK_3_CHILD: [u8; 11712] = [
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9,
9, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 9, 9, 9, 2, 9, 9, 9, 9, 9, 0, 0, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 0, 0, 2, 0, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 2, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 9, 9, 4, 4, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 0, 2, 2, 2, 2, 2, 2, 2, 2,
0, 0, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 0, 0, 2, 2, 2, 2, 0, 0, 9, 2, 9,
9, 9, 9, 9, 9, 9, 0, 0, 9, 9, 0, 0, 9, 9, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 9,
0, 0, 0, 0, 2, 2, 0, 2, 2, 2, 9, 9, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 2, 2, 21, 21, 2, 2, 2, 2, 2, 21, 2, 22, 2, 2, 0, 0, 0, 9, 9, 9, 0,
2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2,
0, 2, 2, 0, 0, 9, 0, 9, 9, 9, 9, 9, 0, 0, 0, 0, 9, 9, 0, 0, 9, 9, 9, 0, 0,
0, 9, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19, 9, 9, 2, 2, 2, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 9, 9, 9, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 9, 2, 9, 9, 9, 9, 9, 9, 9, 9, 0, 9, 9, 9,
0, 9, 9, 9, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 9,
9, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 2, 22, 0, 0, 0, 0, 0, 0, 0,
2, 9, 9, 9, 9, 9, 9, 0, 9, 9, 9, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 0,
0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2,
2, 2, 2, 2, 2, 2, 0, 2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 9, 2, 9, 9, 9, 9, 9, 9,
9, 0, 0, 9, 9, 0, 0, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 2,
2, 0, 2, 2, 2, 9, 9, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 2, 2, 2,
2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2, 0, 2, 2, 2, 2, 2, 2, 0,
0, 0, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2,
0, 0, 0, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0,
9, 9, 9, 9, 9, 0, 0, 0, 9, 9, 9, 0, 9, 9, 9, 9, 0, 0, 2, 0, 0, 0, 0, 0, 0,
9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 2, 2, 2, 2, 2, 2, 2, 2, 2, 22, 2, 0, 0, 0, 0, 0, 9, 9, 9, 9, 0, 2,
2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 0, 0, 0, 2, 9, 9, 9, 9, 9, 9, 9, 0, 9, 9, 9, 0, 9, 9, 9, 9, 0, 0, 0,
0, 0, 0, 0, 9, 9, 0, 2, 2, 2, 0, 0, 0, 0, 0, 2, 2, 9, 9, 0, 0, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2,
2, 9, 9, 9, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 0, 2, 2, 2, 2, 2, 0, 0, 9, 2, 9, 9, 9, 9, 9, 9, 9, 0, 9, 9, 9, 0, 9,
9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 9, 9,
0, 0, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 2, 9, 9, 9, 9, 9, 9, 9,
0, 9, 9, 9, 0, 9, 9, 9, 9, 2, 2, 0, 0, 0, 0, 2, 2, 2, 9, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 9, 9, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 2, 2, 2, 2,
2, 2, 2, 2, 2, 21, 2, 2, 2, 2, 2, 2, 0, 0, 9, 9, 0, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0,
0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 9, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 0, 9, 0,
9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19,
19, 19, 0, 0, 9, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0,
22, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 2, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24,
24, 0, 24, 0, 0, 24, 24, 0, 24, 0, 0, 24, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24,
0, 24, 24, 24, 24, 24, 24, 24, 0, 24, 24, 24, 0, 24, 0, 24, 0, 0, 24, 24, 0,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 24, 24, 24, 0, 0, 24,
24, 24, 24, 24, 0, 24, 0, 24, 24, 24, 24, 24, 24, 0, 0, 19, 19, 19, 19, 19,
19, 19, 19, 19, 19, 0, 0, 24, 24, 24, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 5, 5, 5,
5, 2, 5, 5, 12, 5, 5, 4, 12, 11, 11, 11, 11, 11, 12, 2, 11, 2, 2, 2, 9, 9,
2, 2, 2, 2, 2, 2, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 4, 9, 2, 9, 2, 9, 20, 8, 20, 8, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 4, 9, 9, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 4, 4, 2, 2, 2, 2, 2, 2,
9, 2, 2, 2, 2, 2, 2, 0, 2, 2, 5, 5, 4, 5, 2, 2, 2, 2, 2, 12, 12, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 4, 4, 2, 2, 2, 2, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 24, 24, 24, 24, 24, 24, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 33, 33, 33, 33, 33, 33, 33, 33, 33,
33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33,
33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33,
33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33,
33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33,
33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 35, 35, 35, 35, 35, 35, 35, 35,
35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
35, 35, 35, 35, 35, 35, 35, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34,
34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2,
2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 0, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2,
2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 9,
9, 9, 2, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 20, 8, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0,
0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 9, 9, 9,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 9, 9, 9, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 0, 9, 9, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 4, 4, 18, 24, 4, 2, 4, 22, 24, 24, 0, 0, 19, 19, 19,
19, 19, 19, 19, 19, 19, 19, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
0, 0, 0, 0, 0, 0, 2, 2, 11, 11, 4, 4, 5, 2, 11, 11, 2, 9, 9, 9, 12, 0, 19,
19, 19, 19, 19, 19, 19, 19, 19, 19, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 9, 9, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 9, 2, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 0, 0, 0, 0, 2, 0, 0, 0, 11, 11, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 24, 24, 24, 24, 24, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 0, 0, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 0, 0, 0, 0, 0, 0, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19, 24, 0, 0, 0, 24, 24, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 0, 0, 2, 2, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 0, 0, 9, 19, 19,
19, 19, 19, 19, 19, 19, 19, 19, 0, 0, 0, 0, 0, 0, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 0, 0, 0, 0, 0, 0, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 19, 19, 19, 19, 19, 19,
19, 19, 19, 19, 4, 4, 2, 4, 4, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9,
9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 9, 9, 9, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 19, 19, 19, 19, 19, 19, 19,
19, 19, 19, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 0, 0, 0, 4, 4, 4, 4, 4, 19, 19, 19, 19, 19, 19, 19, 19, 19,
19, 0, 0, 0, 2, 2, 2, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 4, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2,
2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 2, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 2, 2, 9, 2, 2, 2, 2, 9, 9, 9,
2, 2, 9, 9, 9, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 9, 9, 9, 9, 9,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2,
2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2,
2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 0, 2, 0, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 2, 2, 2, 0, 2, 2, 2, 2,
2, 2, 2, 5, 2, 0, 4, 4, 4, 4, 4, 4, 4, 12, 4, 4, 4, 28, 9, 42, 9, 9, 4, 12,
4, 4, 3, 1, 1, 2, 23, 23, 20, 23, 23, 23, 20, 23, 1, 1, 2, 2, 15, 15, 15, 4,
6, 6, 9, 9, 9, 9, 9, 12, 21, 21, 21, 21, 21, 21, 21, 21, 2, 23, 23, 1, 18,
18, 2, 2, 2, 2, 2, 2, 16, 20, 8, 18, 18, 18, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 4, 2, 4, 4, 4, 4, 2, 4, 4, 4, 30, 2, 2, 2, 2, 0, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 2, 2, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 20, 8, 1, 2, 1, 1, 1, 1, 2,
2, 2, 2, 2, 2, 2, 2, 20, 8, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0,
0, 22, 22, 22, 22, 22, 22, 22, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 21, 22, 22, 22, 22, 21, 22, 22, 21, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 21, 2, 1, 2, 2, 2, 21, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 2, 22, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 2,
2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2,
2, 2, 2, 1, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
2, 2, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 1, 1, 2, 2, 2,
1, 1, 2, 2, 1, 2, 2, 2, 1, 2, 1, 22, 22, 2, 1, 2, 2, 2, 2, 1, 2, 2, 1, 1, 1,
1, 2, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 2,
2, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1,
1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1,
2, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 15, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 20, 8, 20, 8, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2,
14, 14, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 20, 8, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 14, 14, 14, 14, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/unicode/tests/linebreaktest.rs | rust/unicode/tests/linebreaktest.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate xi_unicode;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
use xi_unicode::LineBreakIterator;
const TEST_FILE: &str = "tests/LineBreakTest.txt";
#[test]
fn line_break_test() {
let file = File::open(TEST_FILE).expect("unable to open test file.");
let mut reader = BufReader::new(file);
let mut buffer = String::new();
reader.read_to_string(&mut buffer).expect("failed to read test file.");
let mut failed_tests = Vec::new();
for full_test in buffer.lines().filter(|s| !s.starts_with('#')) {
let test = full_test.split('#').next().unwrap().trim();
let (string, breaks) = parse_test(test);
let xi_lb = LineBreakIterator::new(&string).map(|(idx, _)| idx).collect::<Vec<_>>();
if xi_lb != breaks {
failed_tests.push((full_test.to_string(), breaks, xi_lb));
}
}
if !failed_tests.is_empty() {
println!("\nFailed {} line break tests.", failed_tests.len());
for fail in failed_tests {
println!("Failed Test: {}", fail.0);
println!("Unicode Breaks: {:?}", fail.1);
println!("Xi Breaks: {:?}\n", fail.2);
}
panic!("failed line break test.");
}
}
// A typical test looks like: "× 0023 × 0308 × 0020 ÷ 0023 ÷"
fn parse_test(test: &str) -> (String, Vec<usize>) {
use std::char;
let mut parts = test.split(' ');
let mut idx = 0usize;
let mut string = String::new();
let mut breaks = Vec::new();
loop {
let next = parts.next();
if next.is_none() {
break;
}
if next != Some("×") && next != Some("÷") {
panic!("syntax error");
}
if next == Some("÷") {
breaks.push(idx);
}
if let Some(hex) = parts.next() {
let num = u32::from_str_radix(hex, 16).expect("syntax error");
let ch = char::from_u32(num).expect("invalid codepoint");
string.push(ch);
idx += ch.len_utf8();
} else {
break;
}
}
(string, breaks)
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/unicode/benches/bench.rs | rust/unicode/benches/bench.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![feature(test)]
extern crate test;
#[cfg(test)]
mod bench {
use std::cmp::max;
use test::{black_box, Bencher};
use xi_unicode::linebreak_property;
use xi_unicode::linebreak_property_str;
use xi_unicode::LineBreakIterator;
fn linebreak_property_chars(s: &str) -> u8 {
linebreak_property(black_box(s).chars().next().unwrap())
}
// compute the maximum numeric value of the lb, a model for iterating a string
fn max_lb_chars(s: &str) -> u8 {
let mut result = 0;
for c in s.chars() {
result = max(result, linebreak_property(c))
}
result
}
fn max_lb(s: &str) -> u8 {
let mut result = 0;
let mut ix = 0;
while ix < s.len() {
let (lb, len) = linebreak_property_str(s, ix);
result = max(result, lb);
ix += len;
}
result
}
#[bench]
fn linebreak_lo(b: &mut Bencher) {
b.iter(|| linebreak_property(black_box('\u{0042}')));
}
#[bench]
fn linebreak_lo2(b: &mut Bencher) {
b.iter(|| linebreak_property(black_box('\u{0644}')));
}
#[bench]
fn linebreak_med(b: &mut Bencher) {
b.iter(|| linebreak_property(black_box('\u{200D}')));
}
#[bench]
fn linebreak_hi(b: &mut Bencher) {
b.iter(|| linebreak_property(black_box('\u{1F680}')));
}
#[bench]
fn linebreak_str_lo(b: &mut Bencher) {
b.iter(|| linebreak_property_str("\\u{0042}", 0));
}
#[bench]
fn linebreak_str_lo2(b: &mut Bencher) {
b.iter(|| linebreak_property_str("\\u{0644}", 0));
}
#[bench]
fn linebreak_str_med(b: &mut Bencher) {
b.iter(|| linebreak_property_str("\\u{200D}", 0));
}
#[bench]
fn linebreak_str_hi(b: &mut Bencher) {
b.iter(|| linebreak_property_str("\u{1F680}", 0));
}
#[bench]
fn linebreak_chars_lo2(b: &mut Bencher) {
b.iter(|| linebreak_property_chars("\\u{0644}"));
}
#[bench]
fn linebreak_chars_hi(b: &mut Bencher) {
b.iter(|| linebreak_property_chars("\\u{1F680}"));
}
#[bench]
fn max_lb_chars_hi(b: &mut Bencher) {
b.iter(|| max_lb_chars("\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}"));
}
#[bench]
fn max_lb_hi(b: &mut Bencher) {
b.iter(|| max_lb("\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}\\u{1F680}"));
}
#[bench]
fn max_lb_lo(b: &mut Bencher) {
b.iter(|| max_lb("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
}
#[bench]
fn max_lb_chars_lo(b: &mut Bencher) {
b.iter(|| max_lb_chars("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
}
#[bench]
fn lb_iter(b: &mut Bencher) {
// 73 ASCII characters
let s = "Now is the time for all good persons to come to the aid of their country.";
b.iter(|| LineBreakIterator::new(s).count())
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/unicode/examples/runtestdata.rs | rust/unicode/examples/runtestdata.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Run line break test data.
// Run on:
// http://www.unicode.org/Public/UCD/latest/ucd/auxiliary/LineBreakTest.txt
// or use randomized data from tools/gen_rand_icu.cc (same format)
extern crate xi_unicode;
use xi_unicode::{LineBreakIterator, LineBreakLeafIter};
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
fn quote_str(s: &str) -> String {
let mut result = String::new();
for c in s.chars() {
if c == '"' || c == '\\' {
result.push('\\');
}
if (' '..='~').contains(&c) {
result.push(c);
} else {
result.push_str(&format!("\\u{{{:04x}}}", c as u32));
}
}
result
}
fn check_breaks(s: &str, breaks: &[usize]) -> bool {
let my_breaks = LineBreakIterator::new(s).map(|(bk, _hard)| bk).collect::<Vec<_>>();
if my_breaks != breaks {
println!("failed case: \"{}\"", quote_str(s));
println!("expected {:?} actual {:?}", breaks, my_breaks);
return false;
}
true
}
// Verify that starting iteration at a break is insensitive to look-behind.
fn check_lb(s: &str) -> bool {
let breaks = LineBreakIterator::new(s).collect::<Vec<_>>();
for i in 0..breaks.len() - 1 {
let mut cursor = LineBreakLeafIter::new(s, breaks[i].0);
for &bk in &breaks[i + 1..] {
let mut next = cursor.next(s);
if next.0 == s.len() {
next = (s.len(), true);
}
if next != bk {
println!("failed case: \"{}\"", quote_str(s));
println!("expected {:?} actual {:?}", bk, next);
return false;
}
}
}
true
}
fn run_test(filename: &str, lb: bool) -> std::io::Result<()> {
let f = File::open(filename)?;
let mut reader = BufReader::new(f);
let mut pass = 0;
let mut total = 0;
loop {
let mut line = String::new();
if reader.read_line(&mut line)? == 0 {
break;
};
let mut s = String::new();
let mut breaks = Vec::new();
for token in line.split_whitespace() {
if token == "÷" {
breaks.push(s.len());
} else if token == "×" {
} else if token == "#" {
break;
} else if let Ok(cp) = u32::from_str_radix(token, 16) {
s.push(std::char::from_u32(cp).unwrap());
}
}
total += 1;
if lb {
if check_lb(&s) {
pass += 1;
}
} else if check_breaks(&s, &breaks) {
pass += 1;
}
}
println!("{}/{} pass", pass, total);
Ok(())
}
fn main() {
let mut args = std::env::args();
let _ = args.next();
let filename = args.next().unwrap();
match args.next() {
None => {
let _ = run_test(&filename, false);
}
Some(ref s) if s == "--lookbehind" => {
let _ = run_test(&filename, true);
}
_ => {
println!("unknown argument");
}
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/rope.rs | rust/rope/src/rope.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A rope data structure with a line count metric and (soon) other useful
//! info.
#![allow(clippy::needless_return)]
use std::borrow::Cow;
use std::cmp::{max, min, Ordering};
use std::fmt;
use std::ops::Add;
use std::str::{self, FromStr};
use std::string::ParseError;
use crate::delta::{Delta, DeltaElement};
use crate::interval::{Interval, IntervalBounds};
use crate::tree::{Cursor, DefaultMetric, Leaf, Metric, Node, NodeInfo, TreeBuilder};
use memchr::{memchr, memrchr};
use unicode_segmentation::{GraphemeCursor, GraphemeIncomplete};
const MIN_LEAF: usize = 511;
const MAX_LEAF: usize = 1024;
/// A rope data structure.
///
/// A [rope](https://en.wikipedia.org/wiki/Rope_(data_structure)) is a data structure
/// for strings, specialized for incremental editing operations. Most operations
/// (such as insert, delete, substring) are O(log n). This module provides an immutable
/// (also known as [persistent](https://en.wikipedia.org/wiki/Persistent_data_structure))
/// version of Ropes, and if there are many copies of similar strings, the common parts
/// are shared.
///
/// Internally, the implementation uses thread safe reference counting.
/// Mutations are generally copy-on-write, though in-place edits are
/// supported as an optimization when only one reference exists, making the
/// implementation as efficient as a mutable version.
///
/// Also note: in addition to the `From` traits described below, this module
/// implements `From<Rope> for String` and `From<&Rope> for String`, for easy
/// conversions in both directions.
///
/// # Examples
///
/// Create a `Rope` from a `String`:
///
/// ```rust
/// # use xi_rope::Rope;
/// let a = Rope::from("hello ");
/// let b = Rope::from("world");
/// assert_eq!("hello world", String::from(a.clone() + b.clone()));
/// assert!("hello world" == String::from(a + b));
/// ```
///
/// Get a slice of a `Rope`:
///
/// ```rust
/// # use xi_rope::Rope;
/// let a = Rope::from("hello world");
/// let b = a.slice(1..9);
/// assert_eq!("ello wor", String::from(&b));
/// let c = b.slice(1..7);
/// assert_eq!("llo wo", String::from(c));
/// ```
///
/// Replace part of a `Rope`:
///
/// ```rust
/// # use xi_rope::Rope;
/// let mut a = Rope::from("hello world");
/// a.edit(1..9, "era");
/// assert_eq!("herald", String::from(a));
/// ```
pub type Rope = Node<RopeInfo>;
/// Represents a transform from one rope to another.
pub type RopeDelta = Delta<RopeInfo>;
/// An element in a `RopeDelta`.
pub type RopeDeltaElement = DeltaElement<RopeInfo>;
impl Leaf for String {
fn len(&self) -> usize {
self.len()
}
fn is_ok_child(&self) -> bool {
self.len() >= MIN_LEAF
}
fn push_maybe_split(&mut self, other: &String, iv: Interval) -> Option<String> {
//println!("push_maybe_split [{}] [{}] {:?}", self, other, iv);
let (start, end) = iv.start_end();
self.push_str(&other[start..end]);
if self.len() <= MAX_LEAF {
None
} else {
let splitpoint = find_leaf_split_for_merge(self);
let right_str = self[splitpoint..].to_owned();
self.truncate(splitpoint);
self.shrink_to_fit();
Some(right_str)
}
}
}
#[derive(Clone, Copy)]
pub struct RopeInfo {
lines: usize,
utf16_size: usize,
}
impl NodeInfo for RopeInfo {
type L = String;
fn accumulate(&mut self, other: &Self) {
self.lines += other.lines;
self.utf16_size += other.utf16_size;
}
fn compute_info(s: &String) -> Self {
RopeInfo { lines: count_newlines(s), utf16_size: count_utf16_code_units(s) }
}
fn identity() -> Self {
RopeInfo { lines: 0, utf16_size: 0 }
}
}
impl DefaultMetric for RopeInfo {
type DefaultMetric = BaseMetric;
}
//TODO: document metrics, based on https://github.com/google/xi-editor/issues/456
//See ../docs/MetricsAndBoundaries.md for more information.
/// This metric let us walk utf8 text by code point.
///
/// `BaseMetric` implements the trait [Metric]. Both its _measured unit_ and
/// its _base unit_ are utf8 code unit.
///
/// Offsets that do not correspond to codepoint boundaries are _invalid_, and
/// calling functions that assume valid offsets with invalid offets will panic
/// in debug mode.
///
/// Boundary is atomic and determined by codepoint boundary. Atomicity is
/// implicit, because offsets between two utf8 code units that form a code
/// point is considered invalid. For example, if a string starts with a
/// 0xC2 byte, then `offset=1` is invalid.
#[derive(Clone, Copy)]
pub struct BaseMetric(());
impl Metric<RopeInfo> for BaseMetric {
fn measure(_: &RopeInfo, len: usize) -> usize {
len
}
fn to_base_units(s: &String, in_measured_units: usize) -> usize {
debug_assert!(s.is_char_boundary(in_measured_units));
in_measured_units
}
fn from_base_units(s: &String, in_base_units: usize) -> usize {
debug_assert!(s.is_char_boundary(in_base_units));
in_base_units
}
fn is_boundary(s: &String, offset: usize) -> bool {
s.is_char_boundary(offset)
}
fn prev(s: &String, offset: usize) -> Option<usize> {
if offset == 0 {
// I think it's a precondition that this will never be called
// with offset == 0, but be defensive.
None
} else {
let mut len = 1;
while !s.is_char_boundary(offset - len) {
len += 1;
}
Some(offset - len)
}
}
fn next(s: &String, offset: usize) -> Option<usize> {
if offset == s.len() {
// I think it's a precondition that this will never be called
// with offset == s.len(), but be defensive.
None
} else {
let b = s.as_bytes()[offset];
Some(offset + len_utf8_from_first_byte(b))
}
}
fn can_fragment() -> bool {
false
}
}
/// Given the inital byte of a UTF-8 codepoint, returns the number of
/// bytes required to represent the codepoint.
/// RFC reference : https://tools.ietf.org/html/rfc3629#section-4
pub fn len_utf8_from_first_byte(b: u8) -> usize {
match b {
b if b < 0x80 => 1,
b if b < 0xe0 => 2,
b if b < 0xf0 => 3,
_ => 4,
}
}
#[derive(Clone, Copy)]
pub struct LinesMetric(usize); // number of lines
/// Measured unit is newline amount.
/// Base unit is utf8 code unit.
/// Boundary is trailing and determined by a newline char.
impl Metric<RopeInfo> for LinesMetric {
fn measure(info: &RopeInfo, _: usize) -> usize {
info.lines
}
fn is_boundary(s: &String, offset: usize) -> bool {
if offset == 0 {
// shouldn't be called with this, but be defensive
false
} else {
s.as_bytes()[offset - 1] == b'\n'
}
}
fn to_base_units(s: &String, in_measured_units: usize) -> usize {
let mut offset = 0;
for _ in 0..in_measured_units {
match memchr(b'\n', &s.as_bytes()[offset..]) {
Some(pos) => offset += pos + 1,
_ => panic!("to_base_units called with arg too large"),
}
}
offset
}
fn from_base_units(s: &String, in_base_units: usize) -> usize {
count_newlines(&s[..in_base_units])
}
fn prev(s: &String, offset: usize) -> Option<usize> {
debug_assert!(offset > 0, "caller is responsible for validating input");
memrchr(b'\n', &s.as_bytes()[..offset - 1]).map(|pos| pos + 1)
}
fn next(s: &String, offset: usize) -> Option<usize> {
memchr(b'\n', &s.as_bytes()[offset..]).map(|pos| offset + pos + 1)
}
fn can_fragment() -> bool {
true
}
}
#[derive(Clone, Copy)]
pub struct Utf16CodeUnitsMetric(usize);
impl Metric<RopeInfo> for Utf16CodeUnitsMetric {
fn measure(info: &RopeInfo, _: usize) -> usize {
info.utf16_size
}
fn is_boundary(s: &String, offset: usize) -> bool {
s.is_char_boundary(offset)
}
fn to_base_units(s: &String, in_measured_units: usize) -> usize {
let mut cur_len_utf16 = 0;
let mut cur_len_utf8 = 0;
for u in s.chars() {
if cur_len_utf16 >= in_measured_units {
break;
}
cur_len_utf16 += u.len_utf16();
cur_len_utf8 += u.len_utf8();
}
cur_len_utf8
}
fn from_base_units(s: &String, in_base_units: usize) -> usize {
count_utf16_code_units(&s[..in_base_units])
}
fn prev(s: &String, offset: usize) -> Option<usize> {
if offset == 0 {
// I think it's a precondition that this will never be called
// with offset == 0, but be defensive.
None
} else {
let mut len = 1;
while !s.is_char_boundary(offset - len) {
len += 1;
}
Some(offset - len)
}
}
fn next(s: &String, offset: usize) -> Option<usize> {
if offset == s.len() {
// I think it's a precondition that this will never be called
// with offset == s.len(), but be defensive.
None
} else {
let b = s.as_bytes()[offset];
Some(offset + len_utf8_from_first_byte(b))
}
}
fn can_fragment() -> bool {
false
}
}
// Low level functions
pub fn count_newlines(s: &str) -> usize {
bytecount::count(s.as_bytes(), b'\n')
}
fn count_utf16_code_units(s: &str) -> usize {
let mut utf16_count = 0;
for &b in s.as_bytes() {
if (b as i8) >= -0x40 {
utf16_count += 1;
}
if b >= 0xf0 {
utf16_count += 1;
}
}
utf16_count
}
fn find_leaf_split_for_bulk(s: &str) -> usize {
find_leaf_split(s, MIN_LEAF)
}
fn find_leaf_split_for_merge(s: &str) -> usize {
find_leaf_split(s, max(MIN_LEAF, s.len() - MAX_LEAF))
}
// Try to split at newline boundary (leaning left), if not, then split at codepoint
fn find_leaf_split(s: &str, minsplit: usize) -> usize {
let mut splitpoint = min(MAX_LEAF, s.len() - MIN_LEAF);
match memrchr(b'\n', &s.as_bytes()[minsplit - 1..splitpoint]) {
Some(pos) => minsplit + pos,
None => {
while !s.is_char_boundary(splitpoint) {
splitpoint -= 1;
}
splitpoint
}
}
}
// Additional APIs custom to strings
impl FromStr for Rope {
type Err = ParseError;
fn from_str(s: &str) -> Result<Rope, Self::Err> {
let mut b = TreeBuilder::new();
b.push_str(s);
Ok(b.build())
}
}
impl Rope {
/// Edit the string, replacing the byte range [`start`..`end`] with `new`.
///
/// Time complexity: O(log n)
#[deprecated(since = "0.3.0", note = "Use Rope::edit instead")]
pub fn edit_str<T: IntervalBounds>(&mut self, iv: T, new: &str) {
self.edit(iv, new)
}
/// Returns a new Rope with the contents of the provided range.
pub fn slice<T: IntervalBounds>(&self, iv: T) -> Rope {
self.subseq(iv)
}
// encourage callers to use Cursor instead?
/// Determine whether `offset` lies on a codepoint boundary.
pub fn is_codepoint_boundary(&self, offset: usize) -> bool {
let mut cursor = Cursor::new(self, offset);
cursor.is_boundary::<BaseMetric>()
}
/// Return the offset of the codepoint before `offset`.
pub fn prev_codepoint_offset(&self, offset: usize) -> Option<usize> {
let mut cursor = Cursor::new(self, offset);
cursor.prev::<BaseMetric>()
}
/// Return the offset of the codepoint after `offset`.
pub fn next_codepoint_offset(&self, offset: usize) -> Option<usize> {
let mut cursor = Cursor::new(self, offset);
cursor.next::<BaseMetric>()
}
/// Returns `offset` if it lies on a codepoint boundary. Otherwise returns
/// the codepoint after `offset`.
pub fn at_or_next_codepoint_boundary(&self, offset: usize) -> Option<usize> {
if self.is_codepoint_boundary(offset) {
Some(offset)
} else {
self.next_codepoint_offset(offset)
}
}
/// Returns `offset` if it lies on a codepoint boundary. Otherwise returns
/// the codepoint before `offset`.
pub fn at_or_prev_codepoint_boundary(&self, offset: usize) -> Option<usize> {
if self.is_codepoint_boundary(offset) {
Some(offset)
} else {
self.prev_codepoint_offset(offset)
}
}
pub fn prev_grapheme_offset(&self, offset: usize) -> Option<usize> {
let mut cursor = Cursor::new(self, offset);
cursor.prev_grapheme()
}
pub fn next_grapheme_offset(&self, offset: usize) -> Option<usize> {
let mut cursor = Cursor::new(self, offset);
cursor.next_grapheme()
}
/// Return the line number corresponding to the byte index `offset`.
///
/// The line number is 0-based, thus this is equivalent to the count of newlines
/// in the slice up to `offset`.
///
/// Time complexity: O(log n)
///
/// # Panics
///
/// This function will panic if `offset > self.len()`. Callers are expected to
/// validate their input.
pub fn line_of_offset(&self, offset: usize) -> usize {
self.count::<LinesMetric>(offset)
}
/// Return the byte offset corresponding to the line number `line`.
/// If `line` is equal to one plus the current number of lines,
/// this returns the offset of the end of the rope. Arguments higher
/// than this will panic.
///
/// The line number is 0-based.
///
/// Time complexity: O(log n)
///
/// # Panics
///
/// This function will panic if `line > self.measure::<LinesMetric>() + 1`.
/// Callers are expected to validate their input.
pub fn offset_of_line(&self, line: usize) -> usize {
let max_line = self.measure::<LinesMetric>() + 1;
match line.cmp(&max_line) {
Ordering::Greater => {
panic!("line number {} beyond last line {}", line, max_line);
}
Ordering::Equal => {
return self.len();
}
Ordering::Less => self.count_base_units::<LinesMetric>(line),
}
}
/// Returns an iterator over chunks of the rope.
///
/// Each chunk is a `&str` slice borrowed from the rope's storage. The size
/// of the chunks is indeterminate but for large strings will generally be
/// in the range of 511-1024 bytes.
///
/// The empty string will yield a single empty slice. In all other cases, the
/// slices will be nonempty.
///
/// Time complexity: technically O(n log n), but the constant factor is so
/// tiny it is effectively O(n). This iterator does not allocate.
pub fn iter_chunks<T: IntervalBounds>(&self, range: T) -> ChunkIter {
let Interval { start, end } = range.into_interval(self.len());
ChunkIter { cursor: Cursor::new(self, start), end }
}
/// An iterator over the raw lines. The lines, except the last, include the
/// terminating newline.
///
/// The return type is a `Cow<str>`, and in most cases the lines are slices
/// borrowed from the rope.
pub fn lines_raw<T: IntervalBounds>(&self, range: T) -> LinesRaw {
LinesRaw { inner: self.iter_chunks(range), fragment: "" }
}
/// An iterator over the lines of a rope.
///
/// Lines are ended with either Unix (`\n`) or MS-DOS (`\r\n`) style line endings.
/// The line ending is stripped from the resulting string. The final line ending
/// is optional.
///
/// The return type is a `Cow<str>`, and in most cases the lines are slices borrowed
/// from the rope.
///
/// The semantics are intended to match `str::lines()`.
pub fn lines<T: IntervalBounds>(&self, range: T) -> Lines {
Lines { inner: self.lines_raw(range) }
}
// callers should be encouraged to use cursor instead
pub fn byte_at(&self, offset: usize) -> u8 {
let cursor = Cursor::new(self, offset);
let (leaf, pos) = cursor.get_leaf().unwrap();
leaf.as_bytes()[pos]
}
pub fn slice_to_cow<T: IntervalBounds>(&self, range: T) -> Cow<str> {
let mut iter = self.iter_chunks(range);
let first = iter.next();
let second = iter.next();
match (first, second) {
(None, None) => Cow::from(""),
(Some(s), None) => Cow::from(s),
(Some(one), Some(two)) => {
let mut result = [one, two].concat();
for chunk in iter {
result.push_str(chunk);
}
Cow::from(result)
}
(None, Some(_)) => unreachable!(),
}
}
}
// should make this generic, but most leaf types aren't going to be sliceable
pub struct ChunkIter<'a> {
cursor: Cursor<'a, RopeInfo>,
end: usize,
}
impl<'a> Iterator for ChunkIter<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
if self.cursor.pos() >= self.end {
return None;
}
let (leaf, start_pos) = self.cursor.get_leaf().unwrap();
let len = min(self.end - self.cursor.pos(), leaf.len() - start_pos);
self.cursor.next_leaf();
Some(&leaf[start_pos..start_pos + len])
}
}
impl TreeBuilder<RopeInfo> {
/// Push a string on the accumulating tree in the naive way.
///
/// Splits the provided string in chunks that fit in a leaf
/// and pushes the leaves one by one onto the tree by calling
/// `push_leaf` on the builder.
pub fn push_str(&mut self, mut s: &str) {
if s.len() <= MAX_LEAF {
if !s.is_empty() {
self.push_leaf(s.to_owned());
}
return;
}
while !s.is_empty() {
let splitpoint = if s.len() > MAX_LEAF { find_leaf_split_for_bulk(s) } else { s.len() };
self.push_leaf(s[..splitpoint].to_owned());
s = &s[splitpoint..];
}
}
}
impl<T: AsRef<str>> From<T> for Rope {
fn from(s: T) -> Rope {
Rope::from_str(s.as_ref()).unwrap()
}
}
impl From<Rope> for String {
// maybe explore grabbing leaf? would require api in tree
fn from(r: Rope) -> String {
String::from(&r)
}
}
impl<'a> From<&'a Rope> for String {
fn from(r: &Rope) -> String {
r.slice_to_cow(..).into_owned()
}
}
impl fmt::Display for Rope {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for s in self.iter_chunks(..) {
write!(f, "{}", s)?;
}
Ok(())
}
}
impl fmt::Debug for Rope {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
write!(f, "{}", String::from(self))
} else {
write!(f, "Rope({:?})", String::from(self))
}
}
}
impl Add for Rope {
type Output = Rope;
fn add(self, rhs: Rope) -> Rope {
let mut b = TreeBuilder::new();
b.push(self);
b.push(rhs);
b.build()
}
}
//additional cursor features
impl<'a> Cursor<'a, RopeInfo> {
/// Get previous codepoint before cursor position, and advance cursor backwards.
pub fn prev_codepoint(&mut self) -> Option<char> {
self.prev::<BaseMetric>();
if let Some((l, offset)) = self.get_leaf() {
l[offset..].chars().next()
} else {
None
}
}
/// Get next codepoint after cursor position, and advance cursor.
pub fn next_codepoint(&mut self) -> Option<char> {
if let Some((l, offset)) = self.get_leaf() {
self.next::<BaseMetric>();
l[offset..].chars().next()
} else {
None
}
}
/// Get the next codepoint after the cursor position, without advancing
/// the cursor.
pub fn peek_next_codepoint(&self) -> Option<char> {
self.get_leaf().and_then(|(l, off)| l[off..].chars().next())
}
pub fn next_grapheme(&mut self) -> Option<usize> {
let (mut l, mut offset) = self.get_leaf()?;
let mut pos = self.pos();
while offset < l.len() && !l.is_char_boundary(offset) {
pos -= 1;
offset -= 1;
}
let mut leaf_offset = pos - offset;
let mut c = GraphemeCursor::new(pos, self.total_len(), true);
let mut next_boundary = c.next_boundary(l, leaf_offset);
while let Err(incomp) = next_boundary {
if let GraphemeIncomplete::PreContext(_) = incomp {
let (pl, poffset) = self.prev_leaf()?;
c.provide_context(pl, self.pos() - poffset);
} else if incomp == GraphemeIncomplete::NextChunk {
self.set(pos);
let (nl, noffset) = self.next_leaf()?;
l = nl;
leaf_offset = self.pos() - noffset;
pos = leaf_offset + nl.len();
} else {
return None;
}
next_boundary = c.next_boundary(l, leaf_offset);
}
next_boundary.unwrap_or(None)
}
pub fn prev_grapheme(&mut self) -> Option<usize> {
let (mut l, mut offset) = self.get_leaf()?;
let mut pos = self.pos();
while offset < l.len() && !l.is_char_boundary(offset) {
pos += 1;
offset += 1;
}
let mut leaf_offset = pos - offset;
let mut c = GraphemeCursor::new(pos, l.len() + leaf_offset, true);
let mut prev_boundary = c.prev_boundary(l, leaf_offset);
while let Err(incomp) = prev_boundary {
if let GraphemeIncomplete::PreContext(_) = incomp {
let (pl, poffset) = self.prev_leaf()?;
c.provide_context(pl, self.pos() - poffset);
} else if incomp == GraphemeIncomplete::PrevChunk {
self.set(pos);
let (pl, poffset) = self.prev_leaf()?;
l = pl;
leaf_offset = self.pos() - poffset;
pos = leaf_offset + pl.len();
} else {
return None;
}
prev_boundary = c.prev_boundary(l, leaf_offset);
}
prev_boundary.unwrap_or(None)
}
}
// line iterators
pub struct LinesRaw<'a> {
inner: ChunkIter<'a>,
fragment: &'a str,
}
fn cow_append<'a>(a: Cow<'a, str>, b: &'a str) -> Cow<'a, str> {
if a.is_empty() {
Cow::from(b)
} else {
Cow::from(a.into_owned() + b)
}
}
impl<'a> Iterator for LinesRaw<'a> {
type Item = Cow<'a, str>;
fn next(&mut self) -> Option<Cow<'a, str>> {
let mut result = Cow::from("");
loop {
if self.fragment.is_empty() {
match self.inner.next() {
Some(chunk) => self.fragment = chunk,
None => return if result.is_empty() { None } else { Some(result) },
}
if self.fragment.is_empty() {
// can only happen on empty input
return None;
}
}
match memchr(b'\n', self.fragment.as_bytes()) {
Some(i) => {
result = cow_append(result, &self.fragment[..=i]);
self.fragment = &self.fragment[i + 1..];
return Some(result);
}
None => {
result = cow_append(result, self.fragment);
self.fragment = "";
}
}
}
}
}
pub struct Lines<'a> {
inner: LinesRaw<'a>,
}
impl<'a> Iterator for Lines<'a> {
type Item = Cow<'a, str>;
fn next(&mut self) -> Option<Cow<'a, str>> {
match self.inner.next() {
Some(Cow::Borrowed(mut s)) => {
if s.ends_with('\n') {
s = &s[..s.len() - 1];
if s.ends_with('\r') {
s = &s[..s.len() - 1];
}
}
Some(Cow::from(s))
}
Some(Cow::Owned(mut s)) => {
if s.ends_with('\n') {
let _ = s.pop();
if s.ends_with('\r') {
let _ = s.pop();
}
}
Some(Cow::from(s))
}
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn replace_small() {
let mut a = Rope::from("hello world");
a.edit(1..9, "era");
assert_eq!("herald", String::from(a));
}
#[test]
fn lines_raw_small() {
let a = Rope::from("a\nb\nc");
assert_eq!(vec!["a\n", "b\n", "c"], a.lines_raw(..).collect::<Vec<_>>());
assert_eq!(vec!["a\n", "b\n", "c"], a.lines_raw(..).collect::<Vec<_>>());
let a = Rope::from("a\nb\n");
assert_eq!(vec!["a\n", "b\n"], a.lines_raw(..).collect::<Vec<_>>());
let a = Rope::from("\n");
assert_eq!(vec!["\n"], a.lines_raw(..).collect::<Vec<_>>());
let a = Rope::from("");
assert_eq!(0, a.lines_raw(..).count());
}
#[test]
fn lines_small() {
let a = Rope::from("a\nb\nc");
assert_eq!(vec!["a", "b", "c"], a.lines(..).collect::<Vec<_>>());
assert_eq!(String::from(&a).lines().collect::<Vec<_>>(), a.lines(..).collect::<Vec<_>>());
let a = Rope::from("a\nb\n");
assert_eq!(vec!["a", "b"], a.lines(..).collect::<Vec<_>>());
assert_eq!(String::from(&a).lines().collect::<Vec<_>>(), a.lines(..).collect::<Vec<_>>());
let a = Rope::from("\n");
assert_eq!(vec![""], a.lines(..).collect::<Vec<_>>());
assert_eq!(String::from(&a).lines().collect::<Vec<_>>(), a.lines(..).collect::<Vec<_>>());
let a = Rope::from("");
assert_eq!(0, a.lines(..).count());
assert_eq!(String::from(&a).lines().collect::<Vec<_>>(), a.lines(..).collect::<Vec<_>>());
let a = Rope::from("a\r\nb\r\nc");
assert_eq!(vec!["a", "b", "c"], a.lines(..).collect::<Vec<_>>());
assert_eq!(String::from(&a).lines().collect::<Vec<_>>(), a.lines(..).collect::<Vec<_>>());
let a = Rope::from("a\rb\rc");
assert_eq!(vec!["a\rb\rc"], a.lines(..).collect::<Vec<_>>());
assert_eq!(String::from(&a).lines().collect::<Vec<_>>(), a.lines(..).collect::<Vec<_>>());
}
#[test]
fn lines_med() {
let mut a = String::new();
let mut b = String::new();
let line_len = MAX_LEAF + MIN_LEAF - 1;
for _ in 0..line_len {
a.push('a');
b.push('b');
}
a.push('\n');
b.push('\n');
let r = Rope::from(&a[..MAX_LEAF]);
let r = r + Rope::from(String::from(&a[MAX_LEAF..]) + &b[..MIN_LEAF]);
let r = r + Rope::from(&b[MIN_LEAF..]);
//println!("{:?}", r.iter_chunks().collect::<Vec<_>>());
assert_eq!(vec![a.as_str(), b.as_str()], r.lines_raw(..).collect::<Vec<_>>());
assert_eq!(vec![&a[..line_len], &b[..line_len]], r.lines(..).collect::<Vec<_>>());
assert_eq!(String::from(&r).lines().collect::<Vec<_>>(), r.lines(..).collect::<Vec<_>>());
// additional tests for line indexing
assert_eq!(a.len(), r.offset_of_line(1));
assert_eq!(r.len(), r.offset_of_line(2));
assert_eq!(0, r.line_of_offset(a.len() - 1));
assert_eq!(1, r.line_of_offset(a.len()));
assert_eq!(1, r.line_of_offset(r.len() - 1));
assert_eq!(2, r.line_of_offset(r.len()));
}
#[test]
fn append_large() {
let mut a = Rope::from("");
let mut b = String::new();
for i in 0..5_000 {
let c = i.to_string() + "\n";
b.push_str(&c);
a = a + Rope::from(&c);
}
assert_eq!(b, String::from(a));
}
#[test]
fn prev_codepoint_offset_small() {
let a = Rope::from("a\u{00A1}\u{4E00}\u{1F4A9}");
assert_eq!(Some(6), a.prev_codepoint_offset(10));
assert_eq!(Some(3), a.prev_codepoint_offset(6));
assert_eq!(Some(1), a.prev_codepoint_offset(3));
assert_eq!(Some(0), a.prev_codepoint_offset(1));
assert_eq!(None, a.prev_codepoint_offset(0));
let b = a.slice(1..10);
assert_eq!(Some(5), b.prev_codepoint_offset(9));
assert_eq!(Some(2), b.prev_codepoint_offset(5));
assert_eq!(Some(0), b.prev_codepoint_offset(2));
assert_eq!(None, b.prev_codepoint_offset(0));
}
#[test]
fn next_codepoint_offset_small() {
let a = Rope::from("a\u{00A1}\u{4E00}\u{1F4A9}");
assert_eq!(Some(10), a.next_codepoint_offset(6));
assert_eq!(Some(6), a.next_codepoint_offset(3));
assert_eq!(Some(3), a.next_codepoint_offset(1));
assert_eq!(Some(1), a.next_codepoint_offset(0));
assert_eq!(None, a.next_codepoint_offset(10));
let b = a.slice(1..10);
assert_eq!(Some(9), b.next_codepoint_offset(5));
assert_eq!(Some(5), b.next_codepoint_offset(2));
assert_eq!(Some(2), b.next_codepoint_offset(0));
assert_eq!(None, b.next_codepoint_offset(9));
}
#[test]
fn peek_next_codepoint() {
let inp = Rope::from("$¢€£💶");
let mut cursor = Cursor::new(&inp, 0);
assert_eq!(cursor.peek_next_codepoint(), Some('$'));
assert_eq!(cursor.peek_next_codepoint(), Some('$'));
assert_eq!(cursor.next_codepoint(), Some('$'));
assert_eq!(cursor.peek_next_codepoint(), Some('¢'));
assert_eq!(cursor.prev_codepoint(), Some('$'));
assert_eq!(cursor.peek_next_codepoint(), Some('$'));
assert_eq!(cursor.next_codepoint(), Some('$'));
assert_eq!(cursor.next_codepoint(), Some('¢'));
assert_eq!(cursor.peek_next_codepoint(), Some('€'));
assert_eq!(cursor.next_codepoint(), Some('€'));
assert_eq!(cursor.peek_next_codepoint(), Some('£'));
assert_eq!(cursor.next_codepoint(), Some('£'));
assert_eq!(cursor.peek_next_codepoint(), Some('💶'));
assert_eq!(cursor.next_codepoint(), Some('💶'));
assert_eq!(cursor.peek_next_codepoint(), None);
assert_eq!(cursor.next_codepoint(), None);
assert_eq!(cursor.peek_next_codepoint(), None);
}
#[test]
fn prev_grapheme_offset() {
// A with ring, hangul, regional indicator "US"
let a = Rope::from("A\u{030a}\u{110b}\u{1161}\u{1f1fa}\u{1f1f8}");
assert_eq!(Some(9), a.prev_grapheme_offset(17));
assert_eq!(Some(3), a.prev_grapheme_offset(9));
assert_eq!(Some(0), a.prev_grapheme_offset(3));
assert_eq!(None, a.prev_grapheme_offset(0));
}
#[test]
fn next_grapheme_offset() {
// A with ring, hangul, regional indicator "US"
let a = Rope::from("A\u{030a}\u{110b}\u{1161}\u{1f1fa}\u{1f1f8}");
assert_eq!(Some(3), a.next_grapheme_offset(0));
assert_eq!(Some(9), a.next_grapheme_offset(3));
assert_eq!(Some(17), a.next_grapheme_offset(9));
assert_eq!(None, a.next_grapheme_offset(17));
}
#[test]
fn next_grapheme_offset_with_ris_of_leaf_boundaries() {
let s1 = "\u{1f1fa}\u{1f1f8}".repeat(100);
let a = Rope::concat(
Rope::from(s1.clone()),
Rope::concat(Rope::from(s1.clone() + "\u{1f1fa}"), Rope::from(s1.clone())),
);
for i in 1..(s1.len() * 3) {
assert_eq!(Some((i - 1) / 8 * 8), a.prev_grapheme_offset(i));
assert_eq!(Some(i / 8 * 8 + 8), a.next_grapheme_offset(i));
}
for i in (s1.len() * 3 + 1)..(s1.len() * 3 + 4) {
assert_eq!(Some(s1.len() * 3), a.prev_grapheme_offset(i));
assert_eq!(Some(s1.len() * 3 + 4), a.next_grapheme_offset(i));
}
assert_eq!(None, a.prev_grapheme_offset(0));
assert_eq!(Some(8), a.next_grapheme_offset(0));
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/test_helpers.rs | rust/rope/src/test_helpers.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::delta::{self, Delta};
use crate::interval::Interval;
use crate::multiset::{Subset, SubsetBuilder};
use crate::rope::{Rope, RopeInfo};
/// Creates a `Subset` of `s` by scanning through `substr` and finding which
/// characters of `s` are missing from it in order. Returns a `Subset` which
/// when deleted from `s` yields `substr`.
pub fn find_deletions(substr: &str, s: &str) -> Subset {
let mut sb = SubsetBuilder::new();
let mut j = 0;
for i in 0..s.len() {
if j < substr.len() && substr.as_bytes()[j] == s.as_bytes()[i] {
j += 1;
} else {
sb.add_range(i, i + 1, 1);
}
}
sb.pad_to_len(s.len());
sb.build()
}
impl Delta<RopeInfo> {
pub fn apply_to_string(&self, s: &str) -> String {
String::from(self.apply(&Rope::from(s)))
}
}
impl PartialEq for Rope {
fn eq(&self, other: &Rope) -> bool {
String::from(self) == String::from(other)
}
}
pub fn parse_subset(s: &str) -> Subset {
let mut sb = SubsetBuilder::new();
for c in s.chars() {
if c == '#' {
sb.push_segment(1, 1);
} else if c == 'e' {
// do nothing, used for empty subsets
} else {
sb.push_segment(1, 0);
}
}
sb.build()
}
pub fn parse_subset_list(s: &str) -> Vec<Subset> {
s.lines().map(|s| s.trim()).filter(|s| !s.is_empty()).map(parse_subset).collect()
}
pub fn debug_subsets(subsets: &[Subset]) {
for s in subsets {
println!("{:#?}", s);
}
}
pub fn parse_delta(s: &str) -> Delta<RopeInfo> {
let base_len = s.chars().filter(|c| *c == '-' || *c == '!').count();
let mut b = delta::Builder::new(base_len);
let mut i = 0;
for c in s.chars() {
if c == '-' {
i += 1;
} else if c == '!' {
b.delete(Interval::new(i, i + 1));
i += 1;
} else {
let inserted = format!("{}", c);
b.replace(Interval::new(i, i), Rope::from(inserted));
}
}
b.build()
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/engine.rs | rust/rope/src/engine.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! An engine for handling edits (possibly from async sources) and undo. It
//! conceptually represents the current text and all edit history for that
//! text.
//!
//! This module actually implements a mini Conflict-free Replicated Data Type
//! under `Engine::edit_rev`, which is considerably simpler than the usual
//! CRDT implementation techniques, because all operations are serialized in
//! this central engine. It provides the ability to apply edits that depend on
//! a previously committed version of the text rather than the current text,
//! which is sufficient for asynchronous plugins that can only have one
//! pending edit in flight each.
//!
//! There is also a full CRDT merge operation implemented under
//! `Engine::merge`, which is more powerful but considerably more complex.
//! It enables support for full asynchronous and even peer-to-peer editing.
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeSet;
use crate::delta::{Delta, InsertDelta};
use crate::interval::Interval;
use crate::multiset::{CountMatcher, Subset};
use crate::rope::{Rope, RopeInfo};
/// Represents the current state of a document and all of its history
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Engine {
/// The session ID used to create new `RevId`s for edits made on this device
#[cfg_attr(feature = "serde", serde(default = "default_session", skip_serializing))]
session: SessionId,
/// The incrementing revision number counter for this session used for `RevId`s
#[cfg_attr(feature = "serde", serde(default = "initial_revision_counter", skip_serializing))]
rev_id_counter: u32,
/// The current contents of the document as would be displayed on screen
text: Rope,
/// Storage for all the characters that have been deleted but could
/// return if a delete is un-done or an insert is re- done.
tombstones: Rope,
/// Imagine a "union string" that contained all the characters ever
/// inserted, including the ones that were later deleted, in the locations
/// they would be if they hadn't been deleted.
///
/// This is a `Subset` of the "union string" representing the characters
/// that are currently deleted, and thus in `tombstones` rather than
/// `text`. The count of a character in `deletes_from_union` represents
/// how many times it has been deleted, so if a character is deleted twice
/// concurrently it will have count `2` so that undoing one delete but not
/// the other doesn't make it re-appear.
///
/// You could construct the "union string" from `text`, `tombstones` and
/// `deletes_from_union` by splicing a segment of `tombstones` into `text`
/// wherever there's a non-zero-count segment in `deletes_from_union`.
deletes_from_union: Subset,
// TODO: switch to a persistent Set representation to avoid O(n) copying
undone_groups: BTreeSet<usize>, // set of undo_group id's
/// The revision history of the document
revs: Vec<Revision>,
}
// The advantage of using a session ID over random numbers is that it can be
// easily delta-compressed later.
#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct RevId {
// 96 bits has a 10^(-12) chance of collision with 400 million sessions and 10^(-6) with 100 billion.
// `session1==session2==0` is reserved for initialization which is the same on all sessions.
// A colliding session will break merge invariants and the document will start crashing Xi.
session1: u64,
// if this was a tuple field instead of two fields, alignment padding would add 8 more bytes.
session2: u32,
// There will probably never be a document with more than 4 billion edits
// in a single session.
num: u32,
}
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
struct Revision {
/// This uniquely represents the identity of this revision and it stays
/// the same even if it is rebased or merged between devices.
rev_id: RevId,
/// The largest undo group number of any edit in the history up to this
/// point. Used to optimize undo to not look further back.
max_undo_so_far: usize,
edit: Contents,
}
/// Valid within a session. If there's a collision the most recent matching
/// Revision will be used, which means only the (small) set of concurrent edits
/// could trigger incorrect behavior if they collide, so u64 is safe.
pub type RevToken = u64;
/// the session ID component of a `RevId`
pub type SessionId = (u64, u32);
/// Type for errors that occur during CRDT operations.
#[derive(Clone)]
pub enum Error {
/// An edit specified a revision that did not exist. The revision may
/// have been GC'd, or it may have specified incorrectly.
MissingRevision(RevToken),
/// A delta was applied which had a `base_len` that did not match the length
/// of the revision it was applied to.
MalformedDelta { rev_len: usize, delta_len: usize },
}
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
struct FullPriority {
priority: usize,
session_id: SessionId,
}
use self::Contents::*;
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
enum Contents {
Edit {
/// Used to order concurrent inserts, for example auto-indentation
/// should go before typed text.
priority: usize,
/// Groups related edits together so that they are undone and re-done
/// together. For example, an auto-indent insertion would be un-done
/// along with the newline that triggered it.
undo_group: usize,
/// The subset of the characters of the union string from after this
/// revision that were added by this revision.
inserts: Subset,
/// The subset of the characters of the union string from after this
/// revision that were deleted by this revision.
deletes: Subset,
},
Undo {
/// The set of groups toggled between undone and done.
/// Just the `symmetric_difference` (XOR) of the two sets.
toggled_groups: BTreeSet<usize>, // set of undo_group id's
/// Used to store a reversible difference between the old
/// and new deletes_from_union
deletes_bitxor: Subset,
},
}
/// for single user cases, used by serde and ::empty
fn default_session() -> (u64, u32) {
(1, 0)
}
/// Revision 0 is always an Undo of the empty set of groups
#[cfg(feature = "serde")]
fn initial_revision_counter() -> u32 {
1
}
impl RevId {
/// Returns a u64 that will be equal for equivalent revision IDs and
/// should be as unlikely to collide as two random u64s.
pub fn token(&self) -> RevToken {
use std::hash::{Hash, Hasher};
// Rust is unlikely to break the property that this hash is strongly collision-resistant
// and it only needs to be consistent over one execution.
let mut hasher = DefaultHasher::new();
self.hash(&mut hasher);
hasher.finish()
}
pub fn session_id(&self) -> SessionId {
(self.session1, self.session2)
}
}
impl Engine {
/// Create a new Engine with a single edit that inserts `initial_contents`
/// if it is non-empty. It needs to be a separate commit rather than just
/// part of the initial contents since any two `Engine`s need a common
/// ancestor in order to be mergeable.
pub fn new(initial_contents: Rope) -> Engine {
let mut engine = Engine::empty();
if !initial_contents.is_empty() {
let first_rev = engine.get_head_rev_id().token();
let delta = Delta::simple_edit(Interval::new(0, 0), initial_contents, 0);
engine.edit_rev(0, 0, first_rev, delta);
}
engine
}
pub fn empty() -> Engine {
let deletes_from_union = Subset::new(0);
let rev = Revision {
rev_id: RevId { session1: 0, session2: 0, num: 0 },
edit: Undo {
toggled_groups: BTreeSet::new(),
deletes_bitxor: deletes_from_union.clone(),
},
max_undo_so_far: 0,
};
Engine {
session: default_session(),
rev_id_counter: 1,
text: Rope::default(),
tombstones: Rope::default(),
deletes_from_union,
undone_groups: BTreeSet::new(),
revs: vec![rev],
}
}
fn next_rev_id(&self) -> RevId {
RevId { session1: self.session.0, session2: self.session.1, num: self.rev_id_counter }
}
fn find_rev(&self, rev_id: RevId) -> Option<usize> {
self.revs.iter().enumerate().rev().find(|&(_, rev)| rev.rev_id == rev_id).map(|(i, _)| i)
}
fn find_rev_token(&self, rev_token: RevToken) -> Option<usize> {
self.revs
.iter()
.enumerate()
.rev()
.find(|&(_, rev)| rev.rev_id.token() == rev_token)
.map(|(i, _)| i)
}
// TODO: does Cow really help much here? It certainly won't after making Subsets a rope.
/// Find what the `deletes_from_union` field in Engine would have been at the time
/// of a certain `rev_index`. In other words, the deletes from the union string at that time.
fn deletes_from_union_for_index(&self, rev_index: usize) -> Cow<Subset> {
self.deletes_from_union_before_index(rev_index + 1, true)
}
/// Garbage collection means undo can sometimes need to replay the very first
/// revision, and so needs a way to get the deletion set before then.
fn deletes_from_union_before_index(&self, rev_index: usize, invert_undos: bool) -> Cow<Subset> {
let mut deletes_from_union = Cow::Borrowed(&self.deletes_from_union);
let mut undone_groups = Cow::Borrowed(&self.undone_groups);
// invert the changes to deletes_from_union starting in the present and working backwards
for rev in self.revs[rev_index..].iter().rev() {
deletes_from_union = match rev.edit {
Edit { ref inserts, ref deletes, ref undo_group, .. } => {
if undone_groups.contains(undo_group) {
// no need to un-delete undone inserts since we'll just shrink them out
Cow::Owned(deletes_from_union.transform_shrink(inserts))
} else {
let un_deleted = deletes_from_union.subtract(deletes);
Cow::Owned(un_deleted.transform_shrink(inserts))
}
}
Undo { ref toggled_groups, ref deletes_bitxor } => {
if invert_undos {
let new_undone =
undone_groups.symmetric_difference(toggled_groups).cloned().collect();
undone_groups = Cow::Owned(new_undone);
Cow::Owned(deletes_from_union.bitxor(deletes_bitxor))
} else {
deletes_from_union
}
}
}
}
deletes_from_union
}
/// Get the contents of the document at a given revision number
fn rev_content_for_index(&self, rev_index: usize) -> Rope {
let old_deletes_from_union = self.deletes_from_cur_union_for_index(rev_index);
let delta =
Delta::synthesize(&self.tombstones, &self.deletes_from_union, &old_deletes_from_union);
delta.apply(&self.text)
}
/// Get the Subset to delete from the current union string in order to obtain a revision's content
fn deletes_from_cur_union_for_index(&self, rev_index: usize) -> Cow<Subset> {
let mut deletes_from_union = self.deletes_from_union_for_index(rev_index);
for rev in &self.revs[rev_index + 1..] {
if let Edit { ref inserts, .. } = rev.edit {
if !inserts.is_empty() {
deletes_from_union = Cow::Owned(deletes_from_union.transform_union(inserts));
}
}
}
deletes_from_union
}
/// Returns the largest undo group ID used so far
pub fn max_undo_group_id(&self) -> usize {
self.revs.last().unwrap().max_undo_so_far
}
/// Get revision id of head revision.
pub fn get_head_rev_id(&self) -> RevId {
self.revs.last().unwrap().rev_id
}
/// Get text of head revision.
pub fn get_head(&self) -> &Rope {
&self.text
}
/// Get text of a given revision, if it can be found.
pub fn get_rev(&self, rev: RevToken) -> Option<Rope> {
self.find_rev_token(rev).map(|rev_index| self.rev_content_for_index(rev_index))
}
/// A delta that, when applied to `base_rev`, results in the current head. Returns
/// an error if there is not at least one edit.
pub fn try_delta_rev_head(&self, base_rev: RevToken) -> Result<Delta<RopeInfo>, Error> {
let ix = self.find_rev_token(base_rev).ok_or(Error::MissingRevision(base_rev))?;
let prev_from_union = self.deletes_from_cur_union_for_index(ix);
// TODO: this does 2 calls to Delta::synthesize and 1 to apply, this probably could be better.
let old_tombstones = shuffle_tombstones(
&self.text,
&self.tombstones,
&self.deletes_from_union,
&prev_from_union,
);
Ok(Delta::synthesize(&old_tombstones, &prev_from_union, &self.deletes_from_union))
}
// TODO: don't construct transform if subsets are empty
// TODO: maybe switch to using a revision index for `base_rev` once we disable GC
/// Returns a tuple of a new `Revision` representing the edit based on the
/// current head, a new text `Rope`, a new tombstones `Rope` and a new `deletes_from_union`.
/// Returns an [`Error`] if `base_rev` cannot be found, or `delta.base_len`
/// does not equal the length of the text at `base_rev`.
fn mk_new_rev(
&self,
new_priority: usize,
undo_group: usize,
base_rev: RevToken,
delta: Delta<RopeInfo>,
) -> Result<(Revision, Rope, Rope, Subset), Error> {
let ix = self.find_rev_token(base_rev).ok_or(Error::MissingRevision(base_rev))?;
let (ins_delta, deletes) = delta.factor();
// rebase delta to be on the base_rev union instead of the text
let deletes_at_rev = self.deletes_from_union_for_index(ix);
// validate delta
if ins_delta.base_len != deletes_at_rev.len_after_delete() {
return Err(Error::MalformedDelta {
delta_len: ins_delta.base_len,
rev_len: deletes_at_rev.len_after_delete(),
});
}
let mut union_ins_delta = ins_delta.transform_expand(&deletes_at_rev, true);
let mut new_deletes = deletes.transform_expand(&deletes_at_rev);
// rebase the delta to be on the head union instead of the base_rev union
let new_full_priority = FullPriority { priority: new_priority, session_id: self.session };
for r in &self.revs[ix + 1..] {
if let Edit { priority, ref inserts, .. } = r.edit {
if !inserts.is_empty() {
let full_priority =
FullPriority { priority, session_id: r.rev_id.session_id() };
let after = new_full_priority >= full_priority; // should never be ==
union_ins_delta = union_ins_delta.transform_expand(inserts, after);
new_deletes = new_deletes.transform_expand(inserts);
}
}
}
// rebase the deletion to be after the inserts instead of directly on the head union
let new_inserts = union_ins_delta.inserted_subset();
if !new_inserts.is_empty() {
new_deletes = new_deletes.transform_expand(&new_inserts);
}
// rebase insertions on text and apply
let cur_deletes_from_union = &self.deletes_from_union;
let text_ins_delta = union_ins_delta.transform_shrink(cur_deletes_from_union);
let text_with_inserts = text_ins_delta.apply(&self.text);
let rebased_deletes_from_union = cur_deletes_from_union.transform_expand(&new_inserts);
// is the new edit in an undo group that was already undone due to concurrency?
let undone = self.undone_groups.contains(&undo_group);
let new_deletes_from_union = {
let to_delete = if undone { &new_inserts } else { &new_deletes };
rebased_deletes_from_union.union(to_delete)
};
// move deleted or undone-inserted things from text to tombstones
let (new_text, new_tombstones) = shuffle(
&text_with_inserts,
&self.tombstones,
&rebased_deletes_from_union,
&new_deletes_from_union,
);
let head_rev = &self.revs.last().unwrap();
Ok((
Revision {
rev_id: self.next_rev_id(),
max_undo_so_far: std::cmp::max(undo_group, head_rev.max_undo_so_far),
edit: Edit {
priority: new_priority,
undo_group,
inserts: new_inserts,
deletes: new_deletes,
},
},
new_text,
new_tombstones,
new_deletes_from_union,
))
}
// NOTE: maybe just deprecate this? we can panic on the other side of
// the call if/when that makes sense.
/// Create a new edit based on `base_rev`.
///
/// # Panics
///
/// Panics if `base_rev` does not exist, or if `delta` is poorly formed.
pub fn edit_rev(
&mut self,
priority: usize,
undo_group: usize,
base_rev: RevToken,
delta: Delta<RopeInfo>,
) {
self.try_edit_rev(priority, undo_group, base_rev, delta).unwrap();
}
// TODO: have `base_rev` be an index so that it can be used maximally
// efficiently with the head revision, a token or a revision ID.
// Efficiency loss of token is negligible but unfortunate.
/// Attempts to apply a new edit based on the [`Revision`] specified by `base_rev`,
/// Returning an [`Error`] if the `Revision` cannot be found.
pub fn try_edit_rev(
&mut self,
priority: usize,
undo_group: usize,
base_rev: RevToken,
delta: Delta<RopeInfo>,
) -> Result<(), Error> {
let (new_rev, new_text, new_tombstones, new_deletes_from_union) =
self.mk_new_rev(priority, undo_group, base_rev, delta)?;
self.rev_id_counter += 1;
self.revs.push(new_rev);
self.text = new_text;
self.tombstones = new_tombstones;
self.deletes_from_union = new_deletes_from_union;
Ok(())
}
// since undo and gc replay history with transforms, we need an empty set
// of the union string length *before* the first revision.
fn empty_subset_before_first_rev(&self) -> Subset {
let first_rev = &self.revs.first().unwrap();
// it will be immediately transform_expanded by inserts if it is an Edit, so length must be before
let len = match first_rev.edit {
Edit { ref inserts, .. } => inserts.count(CountMatcher::Zero),
Undo { ref deletes_bitxor, .. } => deletes_bitxor.count(CountMatcher::All),
};
Subset::new(len)
}
/// Find the first revision that could be affected by toggling a set of undo groups
fn find_first_undo_candidate_index(&self, toggled_groups: &BTreeSet<usize>) -> usize {
// find the lowest toggled undo group number
if let Some(lowest_group) = toggled_groups.iter().cloned().next() {
for (i, rev) in self.revs.iter().enumerate().rev() {
if rev.max_undo_so_far < lowest_group {
return i + 1; // +1 since we know the one we just found doesn't have it
}
}
0
} else {
// no toggled groups, return past end
self.revs.len()
}
}
// This computes undo all the way from the beginning. An optimization would be to not
// recompute the prefix up to where the history diverges, but it's not clear that's
// even worth the code complexity.
fn compute_undo(&self, groups: &BTreeSet<usize>) -> (Revision, Subset) {
let toggled_groups = self.undone_groups.symmetric_difference(groups).cloned().collect();
let first_candidate = self.find_first_undo_candidate_index(&toggled_groups);
// the `false` below: don't invert undos since our first_candidate is based on the current undo set, not past
let mut deletes_from_union =
self.deletes_from_union_before_index(first_candidate, false).into_owned();
for rev in &self.revs[first_candidate..] {
if let Edit { ref undo_group, ref inserts, ref deletes, .. } = rev.edit {
if groups.contains(undo_group) {
if !inserts.is_empty() {
deletes_from_union = deletes_from_union.transform_union(inserts);
}
} else {
if !inserts.is_empty() {
deletes_from_union = deletes_from_union.transform_expand(inserts);
}
if !deletes.is_empty() {
deletes_from_union = deletes_from_union.union(deletes);
}
}
}
}
let deletes_bitxor = self.deletes_from_union.bitxor(&deletes_from_union);
let max_undo_so_far = self.revs.last().unwrap().max_undo_so_far;
(
Revision {
rev_id: self.next_rev_id(),
max_undo_so_far,
edit: Undo { toggled_groups, deletes_bitxor },
},
deletes_from_union,
)
}
// TODO: maybe refactor this API to take a toggle set
pub fn undo(&mut self, groups: BTreeSet<usize>) {
let (new_rev, new_deletes_from_union) = self.compute_undo(&groups);
let (new_text, new_tombstones) = shuffle(
&self.text,
&self.tombstones,
&self.deletes_from_union,
&new_deletes_from_union,
);
self.text = new_text;
self.tombstones = new_tombstones;
self.deletes_from_union = new_deletes_from_union;
self.undone_groups = groups;
self.revs.push(new_rev);
self.rev_id_counter += 1;
}
pub fn is_equivalent_revision(&self, base_rev: RevId, other_rev: RevId) -> bool {
let base_subset = self
.find_rev(base_rev)
.map(|rev_index| self.deletes_from_cur_union_for_index(rev_index));
let other_subset = self
.find_rev(other_rev)
.map(|rev_index| self.deletes_from_cur_union_for_index(rev_index));
base_subset.is_some() && base_subset == other_subset
}
// Note: this function would need some work to handle retaining arbitrary revisions,
// partly because the reachability calculation would become more complicated (a
// revision might hold content from an undo group that would otherwise be gc'ed),
// and partly because you need to retain more undo history, to supply input to the
// reachability calculation.
//
// Thus, it's easiest to defer gc to when all plugins quiesce, but it's certainly
// possible to fix it so that's not necessary.
pub fn gc(&mut self, gc_groups: &BTreeSet<usize>) {
let mut gc_dels = self.empty_subset_before_first_rev();
// TODO: want to let caller retain more rev_id's.
let mut retain_revs = BTreeSet::new();
if let Some(last) = self.revs.last() {
retain_revs.insert(last.rev_id);
}
{
for rev in &self.revs {
if let Edit { ref undo_group, ref inserts, ref deletes, .. } = rev.edit {
if !retain_revs.contains(&rev.rev_id) && gc_groups.contains(undo_group) {
if self.undone_groups.contains(undo_group) {
if !inserts.is_empty() {
gc_dels = gc_dels.transform_union(inserts);
}
} else {
if !inserts.is_empty() {
gc_dels = gc_dels.transform_expand(inserts);
}
if !deletes.is_empty() {
gc_dels = gc_dels.union(deletes);
}
}
} else if !inserts.is_empty() {
gc_dels = gc_dels.transform_expand(inserts);
}
}
}
}
if !gc_dels.is_empty() {
let not_in_tombstones = self.deletes_from_union.complement();
let dels_from_tombstones = gc_dels.transform_shrink(¬_in_tombstones);
self.tombstones = dels_from_tombstones.delete_from(&self.tombstones);
self.deletes_from_union = self.deletes_from_union.transform_shrink(&gc_dels);
}
let old_revs = std::mem::take(&mut self.revs);
for rev in old_revs.into_iter().rev() {
match rev.edit {
Edit { priority, undo_group, inserts, deletes } => {
let new_gc_dels = if inserts.is_empty() {
None
} else {
Some(gc_dels.transform_shrink(&inserts))
};
if retain_revs.contains(&rev.rev_id) || !gc_groups.contains(&undo_group) {
let (inserts, deletes) = if gc_dels.is_empty() {
(inserts, deletes)
} else {
(inserts.transform_shrink(&gc_dels), deletes.transform_shrink(&gc_dels))
};
self.revs.push(Revision {
rev_id: rev.rev_id,
max_undo_so_far: rev.max_undo_so_far,
edit: Edit { priority, undo_group, inserts, deletes },
});
}
if let Some(new_gc_dels) = new_gc_dels {
gc_dels = new_gc_dels;
}
}
Undo { toggled_groups, deletes_bitxor } => {
// We're super-aggressive about dropping these; after gc, the history
// of which undos were used to compute deletes_from_union in edits may be lost.
if retain_revs.contains(&rev.rev_id) {
let new_deletes_bitxor = if gc_dels.is_empty() {
deletes_bitxor
} else {
deletes_bitxor.transform_shrink(&gc_dels)
};
self.revs.push(Revision {
rev_id: rev.rev_id,
max_undo_so_far: rev.max_undo_so_far,
edit: Undo {
toggled_groups: &toggled_groups - gc_groups,
deletes_bitxor: new_deletes_bitxor,
},
})
}
}
}
}
self.revs.reverse();
}
/// Merge the new content from another Engine into this one with a CRDT merge
pub fn merge(&mut self, other: &Engine) {
let (mut new_revs, text, tombstones, deletes_from_union) = {
let base_index = find_base_index(&self.revs, &other.revs);
let a_to_merge = &self.revs[base_index..];
let b_to_merge = &other.revs[base_index..];
let common = find_common(a_to_merge, b_to_merge);
let a_new = rearrange(a_to_merge, &common, self.deletes_from_union.len());
let b_new = rearrange(b_to_merge, &common, other.deletes_from_union.len());
let b_deltas =
compute_deltas(&b_new, &other.text, &other.tombstones, &other.deletes_from_union);
let expand_by = compute_transforms(a_new);
let max_undo = self.max_undo_group_id();
rebase(
expand_by,
b_deltas,
self.text.clone(),
self.tombstones.clone(),
self.deletes_from_union.clone(),
max_undo,
)
};
self.text = text;
self.tombstones = tombstones;
self.deletes_from_union = deletes_from_union;
self.revs.append(&mut new_revs);
}
/// When merging between multiple concurrently-editing sessions, each session should have a unique ID
/// set with this function, which will make the revisions they create not have colliding IDs.
/// For safety, this will panic if any revisions have already been added to the Engine.
///
/// Merge may panic or return incorrect results if session IDs collide, which is why they can be
/// 96 bits which is more than sufficient for this to never happen.
pub fn set_session_id(&mut self, session: SessionId) {
assert_eq!(
1,
self.revs.len(),
"Revisions were added to an Engine before set_session_id, these may collide."
);
self.session = session;
}
}
// ======== Generic helpers
/// Move sections from text to tombstones and out of tombstones based on a new and old set of deletions
fn shuffle_tombstones(
text: &Rope,
tombstones: &Rope,
old_deletes_from_union: &Subset,
new_deletes_from_union: &Subset,
) -> Rope {
// Taking the complement of deletes_from_union leads to an interleaving valid for swapped text and tombstones,
// allowing us to use the same method to insert the text into the tombstones.
let inverse_tombstones_map = old_deletes_from_union.complement();
let move_delta =
Delta::synthesize(text, &inverse_tombstones_map, &new_deletes_from_union.complement());
move_delta.apply(tombstones)
}
/// Move sections from text to tombstones and vice versa based on a new and old set of deletions.
/// Returns a tuple of a new text `Rope` and a new `Tombstones` rope described by `new_deletes_from_union`.
fn shuffle(
text: &Rope,
tombstones: &Rope,
old_deletes_from_union: &Subset,
new_deletes_from_union: &Subset,
) -> (Rope, Rope) {
// Delta that deletes the right bits from the text
let del_delta = Delta::synthesize(tombstones, old_deletes_from_union, new_deletes_from_union);
let new_text = del_delta.apply(text);
// println!("shuffle: old={:?} new={:?} old_text={:?} new_text={:?} old_tombstones={:?}",
// old_deletes_from_union, new_deletes_from_union, text, new_text, tombstones);
(new_text, shuffle_tombstones(text, tombstones, old_deletes_from_union, new_deletes_from_union))
}
// ======== Merge helpers
/// Find an index before which everything is the same
fn find_base_index(a: &[Revision], b: &[Revision]) -> usize {
assert!(!a.is_empty() && !b.is_empty());
assert!(a[0].rev_id == b[0].rev_id);
// TODO find the maximum base revision.
// this should have the same behavior, but worse performance
1
}
/// Find a set of revisions common to both lists
fn find_common(a: &[Revision], b: &[Revision]) -> BTreeSet<RevId> {
// TODO make this faster somehow?
let a_ids: BTreeSet<RevId> = a.iter().map(|r| r.rev_id).collect();
let b_ids: BTreeSet<RevId> = b.iter().map(|r| r.rev_id).collect();
a_ids.intersection(&b_ids).cloned().collect()
}
/// Returns the operations in `revs` that don't have their `rev_id` in
/// `base_revs`, but modified so that they are in the same order but based on
/// the `base_revs`. This allows the rest of the merge to operate on only
/// revisions not shared by both sides.
///
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/lib.rs | rust/rope/src/lib.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Trees for text.
#![allow(
clippy::collapsible_if,
clippy::len_without_is_empty,
clippy::many_single_char_names,
clippy::needless_range_loop,
clippy::new_without_default,
clippy::should_implement_trait,
clippy::wrong_self_convention
)]
extern crate bytecount;
extern crate memchr;
extern crate regex;
extern crate unicode_segmentation;
#[cfg(feature = "serde")]
#[macro_use]
extern crate serde;
#[cfg(test)]
extern crate serde_json;
#[cfg(test)]
extern crate serde_test;
pub mod breaks;
pub mod compare;
pub mod delta;
pub mod diff;
pub mod engine;
pub mod find;
pub mod interval;
pub mod multiset;
pub mod rope;
#[cfg(feature = "serde")]
mod serde_impls;
pub mod spans;
#[cfg(test)]
mod test_helpers;
pub mod tree;
pub use crate::delta::{Builder as DeltaBuilder, Delta, DeltaElement, Transformer};
pub use crate::interval::Interval;
pub use crate::rope::{LinesMetric, Rope, RopeDelta, RopeInfo};
pub use crate::tree::{Cursor, Metric};
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/delta.rs | rust/rope/src/delta.rs | // Copyright 2016 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! A data structure for representing editing operations on ropes.
//! It's useful to explicitly represent these operations so they can be
//! shared across multiple subsystems.
use crate::interval::{Interval, IntervalBounds};
use crate::multiset::{CountMatcher, Subset, SubsetBuilder};
use crate::tree::{Node, NodeInfo, TreeBuilder};
use std::cmp::min;
use std::fmt;
use std::ops::Deref;
use std::slice;
#[derive(Clone)]
pub enum DeltaElement<N: NodeInfo> {
/// Represents a range of text in the base document. Includes beginning, excludes end.
Copy(usize, usize), // note: for now, we lose open/closed info at interval endpoints
Insert(Node<N>),
}
/// Represents changes to a document by describing the new document as a
/// sequence of sections copied from the old document and of new inserted
/// text. Deletions are represented by gaps in the ranges copied from the old
/// document.
///
/// For example, Editing "abcd" into "acde" could be represented as:
/// `[Copy(0,1),Copy(2,4),Insert("e")]`
#[derive(Clone)]
pub struct Delta<N: NodeInfo> {
pub els: Vec<DeltaElement<N>>,
pub base_len: usize,
}
/// A struct marking that a Delta contains only insertions. That is, it copies
/// all of the old document in the same order. It has a `Deref` impl so all
/// normal `Delta` methods can also be used on it.
#[derive(Clone)]
pub struct InsertDelta<N: NodeInfo>(Delta<N>);
impl<N: NodeInfo> Delta<N> {
pub fn simple_edit<T: IntervalBounds>(interval: T, rope: Node<N>, base_len: usize) -> Delta<N> {
let mut builder = Builder::new(base_len);
if rope.is_empty() {
builder.delete(interval);
} else {
builder.replace(interval, rope);
}
builder.build()
}
/// If this delta represents a simple insertion, returns the inserted node.
pub fn as_simple_insert(&self) -> Option<&Node<N>> {
let mut iter = self.els.iter();
let mut el = iter.next();
let mut i = 0;
if let Some(&DeltaElement::Copy(beg, end)) = el {
if beg != 0 {
return None;
}
i = end;
el = iter.next();
}
if let Some(&DeltaElement::Insert(ref n)) = el {
el = iter.next();
if el.is_none() {
if i == self.base_len {
return Some(n);
}
} else if let Some(&DeltaElement::Copy(beg, end)) = el {
if i == beg && end == self.base_len && iter.next().is_none() {
return Some(n);
}
}
}
None
}
/// Returns `true` if this delta represents a single deletion without
/// any insertions.
///
/// Note that this is `false` for the trivial delta, as well as for a deletion
/// from an empty `Rope`.
pub fn is_simple_delete(&self) -> bool {
if self.els.is_empty() {
return self.base_len > 0;
}
if let DeltaElement::Copy(beg, end) = self.els[0] {
if beg == 0 {
if self.els.len() == 1 {
// Deletion at end
end < self.base_len
} else if let DeltaElement::Copy(b1, e1) = self.els[1] {
// Deletion in middle
self.els.len() == 2 && end < b1 && e1 == self.base_len
} else {
false
}
} else {
// Deletion at beginning
end == self.base_len && self.els.len() == 1
}
} else {
false
}
}
/// Returns `true` if applying the delta will cause no change.
pub fn is_identity(&self) -> bool {
let len = self.els.len();
// Case 1: Everything from beginning to end is getting copied.
if len == 1 {
if let DeltaElement::Copy(beg, end) = self.els[0] {
return beg == 0 && end == self.base_len;
}
}
// Case 2: The rope is empty and the entire rope is getting deleted.
len == 0 && self.base_len == 0
}
/// Apply the delta to the given rope. May not work well if the length of the rope
/// is not compatible with the construction of the delta.
pub fn apply(&self, base: &Node<N>) -> Node<N> {
debug_assert_eq!(base.len(), self.base_len, "must apply Delta to Node of correct length");
let mut b = TreeBuilder::new();
for elem in &self.els {
match *elem {
DeltaElement::Copy(beg, end) => b.push_slice(base, Interval::new(beg, end)),
DeltaElement::Insert(ref n) => b.push(n.clone()),
}
}
b.build()
}
/// Factor the delta into an insert-only delta and a subset representing deletions.
/// Applying the insert then the delete yields the same result as the original delta:
///
/// ```no_run
/// # use xi_rope::rope::{Rope, RopeInfo};
/// # use xi_rope::delta::Delta;
/// # use std::str::FromStr;
/// fn test_factor(d : &Delta<RopeInfo>, r : &Rope) {
/// let (ins, del) = d.clone().factor();
/// let del2 = del.transform_expand(&ins.inserted_subset());
/// assert_eq!(String::from(del2.delete_from(&ins.apply(r))), String::from(d.apply(r)));
/// }
/// ```
pub fn factor(self) -> (InsertDelta<N>, Subset) {
let mut ins = Vec::new();
let mut sb = SubsetBuilder::new();
let mut b1 = 0;
let mut e1 = 0;
for elem in self.els {
match elem {
DeltaElement::Copy(b, e) => {
sb.add_range(e1, b, 1);
e1 = e;
}
DeltaElement::Insert(n) => {
if e1 > b1 {
ins.push(DeltaElement::Copy(b1, e1));
}
b1 = e1;
ins.push(DeltaElement::Insert(n));
}
}
}
if b1 < self.base_len {
ins.push(DeltaElement::Copy(b1, self.base_len));
}
sb.add_range(e1, self.base_len, 1);
sb.pad_to_len(self.base_len);
(InsertDelta(Delta { els: ins, base_len: self.base_len }), sb.build())
}
/// Synthesize a delta from a "union string" and two subsets: an old set
/// of deletions and a new set of deletions from the union. The Delta is
/// from text to text, not union to union; anything in both subsets will
/// be assumed to be missing from the Delta base and the new text. You can
/// also think of these as a set of insertions and one of deletions, with
/// overlap doing nothing. This is basically the inverse of `factor`.
///
/// Since only the deleted portions of the union string are necessary,
/// instead of requiring a union string the function takes a `tombstones`
/// rope which contains the deleted portions of the union string. The
/// `from_dels` subset must be the interleaving of `tombstones` into the
/// union string.
///
/// ```no_run
/// # use xi_rope::rope::{Rope, RopeInfo};
/// # use xi_rope::delta::Delta;
/// # use std::str::FromStr;
/// fn test_synthesize(d : &Delta<RopeInfo>, r : &Rope) {
/// let (ins_d, del) = d.clone().factor();
/// let ins = ins_d.inserted_subset();
/// let del2 = del.transform_expand(&ins);
/// let r2 = ins_d.apply(&r);
/// let tombstones = ins.complement().delete_from(&r2);
/// let d2 = Delta::synthesize(&tombstones, &ins, &del);
/// assert_eq!(String::from(d2.apply(r)), String::from(d.apply(r)));
/// }
/// ```
// For if last_old.is_some() && last_old.unwrap().0 <= beg {. Clippy complaints
// about not using if-let, but that'd change the meaning of the conditional.
#[allow(clippy::unnecessary_unwrap)]
pub fn synthesize(tombstones: &Node<N>, from_dels: &Subset, to_dels: &Subset) -> Delta<N> {
let base_len = from_dels.len_after_delete();
let mut els = Vec::new();
let mut x = 0;
let mut old_ranges = from_dels.complement_iter();
let mut last_old = old_ranges.next();
let mut m = from_dels.mapper(CountMatcher::NonZero);
// For each segment of the new text
for (b, e) in to_dels.complement_iter() {
// Fill the whole segment
let mut beg = b;
while beg < e {
// Skip over ranges in old text until one overlaps where we want to fill
while let Some((ib, ie)) = last_old {
if ie > beg {
break;
}
x += ie - ib;
last_old = old_ranges.next();
}
// If we have a range in the old text with the character at beg, then we Copy
if last_old.is_some() && last_old.unwrap().0 <= beg {
let (ib, ie) = last_old.unwrap();
let end = min(e, ie);
// Try to merge contiguous Copys in the output
let xbeg = beg + x - ib; // "beg - ib + x" better for overflow?
let xend = end + x - ib; // ditto
let merged =
if let Some(&mut DeltaElement::Copy(_, ref mut le)) = els.last_mut() {
if *le == xbeg {
*le = xend;
true
} else {
false
}
} else {
false
};
if !merged {
els.push(DeltaElement::Copy(xbeg, xend));
}
beg = end;
} else {
// if the character at beg isn't in the old text, then we Insert
// Insert up until the next old range we could Copy from, or the end of this segment
let mut end = e;
if let Some((ib, _)) = last_old {
end = min(end, ib)
}
// Note: could try to aggregate insertions, but not sure of the win.
// Use the mapper to insert the corresponding section of the tombstones rope
let interval =
Interval::new(m.doc_index_to_subset(beg), m.doc_index_to_subset(end));
els.push(DeltaElement::Insert(tombstones.subseq(interval)));
beg = end;
}
}
}
Delta { els, base_len }
}
/// Produce a summary of the delta. Everything outside the returned interval
/// is unchanged, and the old contents of the interval are replaced by new
/// contents of the returned length. Equations:
///
/// `(iv, new_len) = self.summary()`
///
/// `new_s = self.apply(s)`
///
/// `new_s = simple_edit(iv, new_s.subseq(iv.start(), iv.start() + new_len), s.len()).apply(s)`
pub fn summary(&self) -> (Interval, usize) {
let mut els = self.els.as_slice();
let mut iv_start = 0;
if let Some((&DeltaElement::Copy(0, end), rest)) = els.split_first() {
iv_start = end;
els = rest;
}
let mut iv_end = self.base_len;
if let Some((&DeltaElement::Copy(beg, end), init)) = els.split_last() {
if end == iv_end {
iv_end = beg;
els = init;
}
}
(Interval::new(iv_start, iv_end), Delta::total_element_len(els))
}
/// Returns the length of the new document. In other words, the length of
/// the transformed string after this Delta is applied.
///
/// `d.apply(r).len() == d.new_document_len()`
pub fn new_document_len(&self) -> usize {
Delta::total_element_len(self.els.as_slice())
}
fn total_element_len(els: &[DeltaElement<N>]) -> usize {
els.iter().fold(0, |sum, el| {
sum + match *el {
DeltaElement::Copy(beg, end) => end - beg,
DeltaElement::Insert(ref n) => n.len(),
}
})
}
/// Returns the sum length of the inserts of the delta.
pub fn inserts_len(&self) -> usize {
self.els.iter().fold(0, |sum, el| {
sum + match *el {
DeltaElement::Copy(_, _) => 0,
DeltaElement::Insert(ref s) => s.len(),
}
})
}
/// Iterates over all the inserts of the delta.
pub fn iter_inserts(&self) -> InsertsIter<N> {
InsertsIter { pos: 0, last_end: 0, els_iter: self.els.iter() }
}
/// Iterates over all the deletions of the delta.
pub fn iter_deletions(&self) -> DeletionsIter<N> {
DeletionsIter { pos: 0, last_end: 0, base_len: self.base_len, els_iter: self.els.iter() }
}
}
impl<N: NodeInfo> fmt::Debug for Delta<N>
where
Node<N>: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if f.alternate() {
for el in &self.els {
match *el {
DeltaElement::Copy(beg, end) => {
write!(f, "{}", "-".repeat(end - beg))?;
}
DeltaElement::Insert(ref node) => {
node.fmt(f)?;
}
}
}
} else {
write!(f, "Delta(")?;
for el in &self.els {
match *el {
DeltaElement::Copy(beg, end) => {
write!(f, "[{},{}) ", beg, end)?;
}
DeltaElement::Insert(ref node) => {
write!(f, "<ins:{}> ", node.len())?;
}
}
}
write!(f, "base_len: {})", self.base_len)?;
}
Ok(())
}
}
impl<N: NodeInfo> fmt::Debug for InsertDelta<N>
where
Node<N>: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl<N: NodeInfo> InsertDelta<N> {
#![allow(clippy::many_single_char_names)]
/// Do a coordinate transformation on an insert-only delta. The `after` parameter
/// controls whether the insertions in `self` come after those specific in the
/// coordinate transform.
//
// TODO: write accurate equations
pub fn transform_expand(&self, xform: &Subset, after: bool) -> InsertDelta<N> {
let cur_els = &self.0.els;
let mut els = Vec::new();
let mut x = 0; // coordinate within self
let mut y = 0; // coordinate within xform
let mut i = 0; // index into self.els
let mut b1 = 0;
let mut xform_ranges = xform.complement_iter();
let mut last_xform = xform_ranges.next();
let l = xform.count(CountMatcher::All);
while y < l || i < cur_els.len() {
let next_iv_beg = if let Some((xb, _)) = last_xform { xb } else { l };
if after && y < next_iv_beg {
y = next_iv_beg;
}
while i < cur_els.len() {
match cur_els[i] {
DeltaElement::Insert(ref n) => {
if y > b1 {
els.push(DeltaElement::Copy(b1, y));
}
b1 = y;
els.push(DeltaElement::Insert(n.clone()));
i += 1;
}
DeltaElement::Copy(_b, e) => {
if y >= next_iv_beg {
let mut next_y = e + y - x;
if let Some((_, xe)) = last_xform {
next_y = min(next_y, xe);
}
x += next_y - y;
y = next_y;
if x == e {
i += 1;
}
if let Some((_, xe)) = last_xform {
if y == xe {
last_xform = xform_ranges.next();
}
}
}
break;
}
}
}
if !after && y < next_iv_beg {
y = next_iv_beg;
}
}
if y > b1 {
els.push(DeltaElement::Copy(b1, y));
}
InsertDelta(Delta { els, base_len: l })
}
// TODO: it is plausible this method also works on Deltas with deletes
/// Shrink a delta through a deletion of some of its copied regions with
/// the same base. For example, if `self` applies to a union string, and
/// `xform` is the deletions from that union, the resulting Delta will
/// apply to the text.
pub fn transform_shrink(&self, xform: &Subset) -> InsertDelta<N> {
let mut m = xform.mapper(CountMatcher::Zero);
let els = self
.0
.els
.iter()
.map(|elem| match *elem {
DeltaElement::Copy(b, e) => {
DeltaElement::Copy(m.doc_index_to_subset(b), m.doc_index_to_subset(e))
}
DeltaElement::Insert(ref n) => DeltaElement::Insert(n.clone()),
})
.collect();
InsertDelta(Delta { els, base_len: xform.len_after_delete() })
}
/// Return a Subset containing the inserted ranges.
///
/// `d.inserted_subset().delete_from_string(d.apply_to_string(s)) == s`
pub fn inserted_subset(&self) -> Subset {
let mut sb = SubsetBuilder::new();
for elem in &self.0.els {
match *elem {
DeltaElement::Copy(b, e) => {
sb.push_segment(e - b, 0);
}
DeltaElement::Insert(ref n) => {
sb.push_segment(n.len(), 1);
}
}
}
sb.build()
}
}
/// An InsertDelta is a certain kind of Delta, and anything that applies to a
/// Delta that may include deletes also applies to one that definitely
/// doesn't. This impl allows implicit use of those methods.
impl<N: NodeInfo> Deref for InsertDelta<N> {
type Target = Delta<N>;
fn deref(&self) -> &Delta<N> {
&self.0
}
}
/// A mapping from coordinates in the source sequence to coordinates in the sequence after
/// the delta is applied.
// TODO: this doesn't need the new strings, so it should either be based on a new structure
// like Delta but missing the strings, or perhaps the two subsets it's synthesized from.
pub struct Transformer<'a, N: NodeInfo + 'a> {
delta: &'a Delta<N>,
}
impl<'a, N: NodeInfo + 'a> Transformer<'a, N> {
/// Create a new transformer from a delta.
pub fn new(delta: &'a Delta<N>) -> Self {
Transformer { delta }
}
/// Transform a single coordinate. The `after` parameter indicates whether it
/// it should land before or after an inserted region.
// TODO: implement a cursor so we're not scanning from the beginning every time.
pub fn transform(&mut self, ix: usize, after: bool) -> usize {
if ix == 0 && !after {
return 0;
}
let mut result = 0;
for el in &self.delta.els {
match *el {
DeltaElement::Copy(beg, end) => {
if ix <= beg {
return result;
}
if ix < end || (ix == end && !after) {
return result + ix - beg;
}
result += end - beg;
}
DeltaElement::Insert(ref n) => {
result += n.len();
}
}
}
result
}
/// Determine whether a given interval is untouched by the transformation.
pub fn interval_untouched<T: IntervalBounds>(&mut self, iv: T) -> bool {
let iv = iv.into_interval(self.delta.base_len);
let mut last_was_ins = true;
for el in &self.delta.els {
match *el {
DeltaElement::Copy(beg, end) => {
if iv.is_before(end) {
if last_was_ins {
if iv.is_after(beg) {
return true;
}
} else if !iv.is_before(beg) {
return true;
}
} else {
return false;
}
last_was_ins = false;
}
_ => {
last_was_ins = true;
}
}
}
false
}
}
/// A builder for creating new `Delta` objects.
///
/// Note that all edit operations must be sorted; the start point of each
/// interval must be no less than the end point of the previous one.
pub struct Builder<N: NodeInfo> {
delta: Delta<N>,
last_offset: usize,
}
impl<N: NodeInfo> Builder<N> {
/// Creates a new builder, applicable to a base rope of length `base_len`.
pub fn new(base_len: usize) -> Builder<N> {
Builder { delta: Delta { els: Vec::new(), base_len }, last_offset: 0 }
}
/// Deletes the given interval. Panics if interval is not properly sorted.
pub fn delete<T: IntervalBounds>(&mut self, interval: T) {
let interval = interval.into_interval(self.delta.base_len);
let (start, end) = interval.start_end();
assert!(start >= self.last_offset, "Delta builder: intervals not properly sorted");
if start > self.last_offset {
self.delta.els.push(DeltaElement::Copy(self.last_offset, start));
}
self.last_offset = end;
}
/// Replaces the given interval with the new rope. Panics if interval
/// is not properly sorted.
pub fn replace<T: IntervalBounds>(&mut self, interval: T, rope: Node<N>) {
self.delete(interval);
if !rope.is_empty() {
self.delta.els.push(DeltaElement::Insert(rope));
}
}
/// Determines if delta would be a no-op transformation if built.
pub fn is_empty(&self) -> bool {
self.last_offset == 0 && self.delta.els.is_empty()
}
/// Builds the `Delta`.
pub fn build(mut self) -> Delta<N> {
if self.last_offset < self.delta.base_len {
self.delta.els.push(DeltaElement::Copy(self.last_offset, self.delta.base_len));
}
self.delta
}
}
pub struct InsertsIter<'a, N: NodeInfo + 'a> {
pos: usize,
last_end: usize,
els_iter: slice::Iter<'a, DeltaElement<N>>,
}
#[derive(Debug, PartialEq)]
pub struct DeltaRegion {
pub old_offset: usize,
pub new_offset: usize,
pub len: usize,
}
impl DeltaRegion {
fn new(old_offset: usize, new_offset: usize, len: usize) -> Self {
DeltaRegion { old_offset, new_offset, len }
}
}
impl<'a, N: NodeInfo> Iterator for InsertsIter<'a, N> {
type Item = DeltaRegion;
fn next(&mut self) -> Option<Self::Item> {
let mut result = None;
for elem in &mut self.els_iter {
match *elem {
DeltaElement::Copy(b, e) => {
self.pos += e - b;
self.last_end = e;
}
DeltaElement::Insert(ref n) => {
result = Some(DeltaRegion::new(self.last_end, self.pos, n.len()));
self.pos += n.len();
self.last_end += n.len();
break;
}
}
}
result
}
}
pub struct DeletionsIter<'a, N: NodeInfo + 'a> {
pos: usize,
last_end: usize,
base_len: usize,
els_iter: slice::Iter<'a, DeltaElement<N>>,
}
impl<'a, N: NodeInfo> Iterator for DeletionsIter<'a, N> {
type Item = DeltaRegion;
fn next(&mut self) -> Option<Self::Item> {
let mut result = None;
for elem in &mut self.els_iter {
match *elem {
DeltaElement::Copy(b, e) => {
if b > self.last_end {
result = Some(DeltaRegion::new(self.last_end, self.pos, b - self.last_end));
}
self.pos += e - b;
self.last_end = e;
if result.is_some() {
break;
}
}
DeltaElement::Insert(ref n) => {
self.pos += n.len();
self.last_end += n.len();
}
}
}
if result.is_none() && self.last_end < self.base_len {
result = Some(DeltaRegion::new(self.last_end, self.pos, self.base_len - self.last_end));
self.last_end = self.base_len;
}
result
}
}
#[cfg(test)]
mod tests {
use crate::delta::{Builder, Delta, DeltaElement, DeltaRegion};
use crate::interval::Interval;
use crate::rope::{Rope, RopeInfo};
use crate::test_helpers::find_deletions;
const TEST_STR: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#[test]
fn simple() {
let d = Delta::simple_edit(Interval::new(1, 9), Rope::from("era"), 11);
assert_eq!("herald", d.apply_to_string("hello world"));
assert_eq!(6, d.new_document_len());
}
#[test]
fn factor() {
let d = Delta::simple_edit(Interval::new(1, 9), Rope::from("era"), 11);
let (d1, ss) = d.factor();
assert_eq!("heraello world", d1.apply_to_string("hello world"));
assert_eq!("hld", ss.delete_from_string("hello world"));
}
#[test]
fn synthesize() {
let d = Delta::simple_edit(Interval::new(1, 9), Rope::from("era"), 11);
let (d1, del) = d.factor();
let ins = d1.inserted_subset();
let del = del.transform_expand(&ins);
let union_str = d1.apply_to_string("hello world");
let tombstones = ins.complement().delete_from_string(&union_str);
let new_d = Delta::synthesize(&Rope::from(&tombstones), &ins, &del);
assert_eq!("herald", new_d.apply_to_string("hello world"));
let text = del.complement().delete_from_string(&union_str);
let inv_d = Delta::synthesize(&Rope::from(&text), &del, &ins);
assert_eq!("hello world", inv_d.apply_to_string("herald"));
}
#[test]
fn inserted_subset() {
let d = Delta::simple_edit(Interval::new(1, 9), Rope::from("era"), 11);
let (d1, _ss) = d.factor();
assert_eq!("hello world", d1.inserted_subset().delete_from_string("heraello world"));
}
#[test]
fn transform_expand() {
let str1 = "01259DGJKNQTUVWXYcdefghkmopqrstvwxy";
let s1 = find_deletions(str1, TEST_STR);
let d = Delta::simple_edit(Interval::new(10, 12), Rope::from("+"), str1.len());
assert_eq!("01259DGJKN+UVWXYcdefghkmopqrstvwxy", d.apply_to_string(str1));
let (d2, _ss) = d.factor();
assert_eq!("01259DGJKN+QTUVWXYcdefghkmopqrstvwxy", d2.apply_to_string(str1));
let d3 = d2.transform_expand(&s1, false);
assert_eq!(
"0123456789ABCDEFGHIJKLMN+OPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
d3.apply_to_string(TEST_STR)
);
let d4 = d2.transform_expand(&s1, true);
assert_eq!(
"0123456789ABCDEFGHIJKLMNOP+QRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
d4.apply_to_string(TEST_STR)
);
}
#[test]
fn transform_shrink() {
let d = Delta::simple_edit(Interval::new(10, 12), Rope::from("+"), TEST_STR.len());
let (d2, _ss) = d.factor();
assert_eq!(
"0123456789+ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
d2.apply_to_string(TEST_STR)
);
let str1 = "0345678BCxyz";
let s1 = find_deletions(str1, TEST_STR);
let d3 = d2.transform_shrink(&s1);
assert_eq!("0345678+BCxyz", d3.apply_to_string(str1));
let str2 = "356789ABCx";
let s2 = find_deletions(str2, TEST_STR);
let d4 = d2.transform_shrink(&s2);
assert_eq!("356789+ABCx", d4.apply_to_string(str2));
}
#[test]
fn iter_inserts() {
let mut builder = Builder::new(10);
builder.replace(Interval::new(2, 2), Rope::from("a"));
builder.delete(Interval::new(3, 5));
builder.replace(Interval::new(6, 8), Rope::from("b"));
let delta = builder.build();
assert_eq!("01a25b89", delta.apply_to_string("0123456789"));
let mut iter = delta.iter_inserts();
assert_eq!(Some(DeltaRegion::new(2, 2, 1)), iter.next());
assert_eq!(Some(DeltaRegion::new(6, 5, 1)), iter.next());
assert_eq!(None, iter.next());
}
#[test]
fn iter_deletions() {
let mut builder = Builder::new(10);
builder.delete(Interval::new(0, 2));
builder.delete(Interval::new(4, 6));
builder.delete(Interval::new(8, 10));
let delta = builder.build();
assert_eq!("2367", delta.apply_to_string("0123456789"));
let mut iter = delta.iter_deletions();
assert_eq!(Some(DeltaRegion::new(0, 0, 2)), iter.next());
assert_eq!(Some(DeltaRegion::new(4, 2, 2)), iter.next());
assert_eq!(Some(DeltaRegion::new(8, 4, 2)), iter.next());
assert_eq!(None, iter.next());
}
#[test]
fn fancy_bounds() {
let mut builder = Builder::new(10);
builder.delete(..2);
builder.delete(4..=5);
builder.delete(8..);
let delta = builder.build();
assert_eq!("2367", delta.apply_to_string("0123456789"));
}
#[test]
fn is_simple_delete() {
let d = Delta::simple_edit(10..12, Rope::from("+"), TEST_STR.len());
assert_eq!(false, d.is_simple_delete());
let d = Delta::simple_edit(Interval::new(0, 0), Rope::from(""), 0);
assert_eq!(false, d.is_simple_delete());
let d = Delta::simple_edit(Interval::new(10, 11), Rope::from(""), TEST_STR.len());
assert_eq!(true, d.is_simple_delete());
let mut builder = Builder::<RopeInfo>::new(10);
builder.delete(Interval::new(0, 2));
builder.delete(Interval::new(4, 6));
let d = builder.build();
assert_eq!(false, d.is_simple_delete());
let builder = Builder::<RopeInfo>::new(10);
let d = builder.build();
assert_eq!(false, d.is_simple_delete());
let delta = Delta {
els: vec![
DeltaElement::Copy(0, 10),
DeltaElement::Copy(12, 20),
DeltaElement::Insert(Rope::from("hi")),
],
base_len: 20,
};
assert!(!delta.is_simple_delete());
}
#[test]
fn is_identity() {
let d = Delta::simple_edit(10..12, Rope::from("+"), TEST_STR.len());
assert_eq!(false, d.is_identity());
let d = Delta::simple_edit(0..0, Rope::from(""), TEST_STR.len());
assert_eq!(true, d.is_identity());
let d = Delta::simple_edit(0..0, Rope::from(""), 0);
assert_eq!(true, d.is_identity());
}
#[test]
fn as_simple_insert() {
let d = Delta::simple_edit(Interval::new(10, 11), Rope::from("+"), TEST_STR.len());
assert_eq!(None, d.as_simple_insert());
let d = Delta::simple_edit(Interval::new(10, 10), Rope::from("+"), TEST_STR.len());
assert_eq!(Some(Rope::from("+")).as_ref(), d.as_simple_insert());
}
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use crate::rope::{Rope, RopeInfo};
use crate::{Delta, Interval};
use serde_json;
const TEST_STR: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#[test]
fn delta_serde() {
let d = Delta::simple_edit(Interval::new(10, 12), Rope::from("+"), TEST_STR.len());
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | true |
xi-editor/xi-editor | https://github.com/xi-editor/xi-editor/blob/a2dea3059312795c77caadc639df49bf8a7008eb/rust/rope/src/diff.rs | rust/rope/src/diff.rs | // Copyright 2018 The xi-editor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Computing deltas between two ropes.
use std::borrow::Cow;
use std::collections::HashMap;
use crate::compare::RopeScanner;
use crate::delta::{Delta, DeltaElement};
use crate::interval::Interval;
use crate::rope::{LinesMetric, Rope, RopeDelta, RopeInfo};
use crate::tree::{Node, NodeInfo};
/// A trait implemented by various diffing strategies.
pub trait Diff<N: NodeInfo> {
fn compute_delta(base: &Node<N>, target: &Node<N>) -> Delta<N>;
}
/// The minimum length of non-whitespace characters in a line before
/// we consider it for diffing purposes.
const MIN_SIZE: usize = 32;
/// A line-oriented, hash based diff algorithm.
///
/// This works by taking a hash of each line in either document that
/// has a length, ignoring leading whitespace, above some threshold.
///
/// Lines in the target document are matched against lines in the
/// base document. When a match is found, it is extended forwards
/// and backwards as far as possible.
///
/// This runs in O(n+m) in the lengths of the two ropes, and produces
/// results on a variety of workloads that are comparable in quality
/// (measured in terms of serialized diff size) with the results from
/// using a suffix array, while being an order of magnitude faster.
pub struct LineHashDiff;
impl Diff<RopeInfo> for LineHashDiff {
fn compute_delta(base: &Rope, target: &Rope) -> RopeDelta {
let mut builder = DiffBuilder::default();
// before doing anything, scan top down and bottom up for like-ness.
let mut scanner = RopeScanner::new(base, target);
let (start_offset, diff_end) = scanner.find_min_diff_range();
let target_end = target.len() - diff_end;
if start_offset > 0 {
builder.copy(0, 0, start_offset);
}
// if our preliminary scan finds no differences we're done
if start_offset == base.len() && target.len() == base.len() {
return builder.to_delta(base, target);
}
// if a continuous range of text got deleted, we're done
if target.len() < base.len() && start_offset + diff_end == target.len() {
builder.copy(base.len() - diff_end, target_end, diff_end);
return builder.to_delta(base, target);
}
// if a continuous range of text got inserted, we're done
if target.len() > base.len() && start_offset + diff_end == base.len() {
builder.copy(base.len() - diff_end, target_end, diff_end);
return builder.to_delta(base, target);
}
let line_hashes = make_line_hashes(base, MIN_SIZE);
let line_count = target.measure::<LinesMetric>() + 1;
let mut matches = Vec::with_capacity(line_count);
let mut targ_line_offset = 0;
let mut prev_base = 0;
let mut needs_subseq = false;
for line in target.lines_raw(start_offset..target_end) {
let non_ws = non_ws_offset(&line);
if line.len() - non_ws >= MIN_SIZE {
if let Some(base_off) = line_hashes.get(&line[non_ws..]) {
let targ_off = targ_line_offset + non_ws;
matches.push((start_offset + targ_off, *base_off));
if *base_off < prev_base {
needs_subseq = true;
}
prev_base = *base_off;
}
}
targ_line_offset += line.len();
}
// we now have an ordered list of matches and their positions.
// to ensure that our delta only copies non-decreasing base regions,
// we take the longest increasing subsequence.
// TODO: a possible optimization here would be to expand matches
// to adjacent lines first? this would be at best a small win though..
let longest_subseq =
if needs_subseq { longest_increasing_region_set(&matches) } else { matches };
// for each matching region, we extend it forwards and backwards.
// we keep track of how far forward we extend it each time, to avoid
// having a subsequent scan extend backwards over the same region.
let mut prev_end = start_offset;
for (targ_off, base_off) in longest_subseq {
if targ_off <= prev_end {
continue;
}
let (left_dist, mut right_dist) =
expand_match(base, target, base_off, targ_off, prev_end);
// don't let last match expand past target_end
right_dist = right_dist.min(target_end - targ_off);
let targ_start = targ_off - left_dist;
let base_start = base_off - left_dist;
let len = left_dist + right_dist;
prev_end = targ_start + len;
builder.copy(base_start, targ_start, len);
}
if diff_end > 0 {
builder.copy(base.len() - diff_end, target.len() - diff_end, diff_end);
}
builder.to_delta(base, target)
}
}
/// Given two ropes and the offsets of two equal bytes, finds the largest
/// identical substring shared between the two ropes which contains the offset.
///
/// The return value is a pair of offsets, each of which represents an absolute
/// distance. That is to say, the position of the start and end boundaries
/// relative to the input offset.
fn expand_match(
base: &Rope,
target: &Rope,
base_off: usize,
targ_off: usize,
prev_match_targ_end: usize,
) -> (usize, usize) {
let mut scanner = RopeScanner::new(base, target);
let max_left = targ_off - prev_match_targ_end;
let start = scanner.find_ne_char_back(base_off, targ_off, max_left);
debug_assert!(start <= max_left, "{} <= {}", start, max_left);
let end = scanner.find_ne_char(base_off, targ_off, None);
(start.min(max_left), end)
}
/// Finds the longest increasing subset of copyable regions. This is essentially
/// the longest increasing subsequence problem. This implementation is adapted
/// from https://codereview.stackexchange.com/questions/187337/longest-increasing-subsequence-algorithm
fn longest_increasing_region_set(items: &[(usize, usize)]) -> Vec<(usize, usize)> {
let mut result = vec![0];
let mut prev_chain = vec![0; items.len()];
for i in 1..items.len() {
// If the next item is greater than the last item of the current longest
// subsequence, push its index at the end of the result and continue.
let last_idx = *result.last().unwrap();
if items[last_idx].1 < items[i].1 {
prev_chain[i] = last_idx;
result.push(i);
continue;
}
let next_idx = match result.binary_search_by(|&j| items[j].1.cmp(&items[i].1)) {
Ok(_) => continue, // we ignore duplicates
Err(idx) => idx,
};
if items[i].1 < items[result[next_idx]].1 {
if next_idx > 0 {
prev_chain[i] = result[next_idx - 1];
}
result[next_idx] = i;
}
}
// walk backwards from the last item in result to build the final sequence
let mut u = result.len();
let mut v = *result.last().unwrap();
while u != 0 {
u -= 1;
result[u] = v;
v = prev_chain[v];
}
result.iter().map(|i| items[*i]).collect()
}
#[inline]
fn non_ws_offset(s: &str) -> usize {
s.as_bytes().iter().take_while(|b| **b == b' ' || **b == b'\t').count()
}
/// Represents copying `len` bytes from base to target.
#[derive(Debug, Clone, Copy)]
struct DiffOp {
target_idx: usize,
base_idx: usize,
len: usize,
}
/// Keeps track of copy ops during diff construction.
#[derive(Debug, Clone, Default)]
pub struct DiffBuilder {
ops: Vec<DiffOp>,
}
impl DiffBuilder {
fn copy(&mut self, base: usize, target: usize, len: usize) {
if let Some(prev) = self.ops.last_mut() {
let prev_end = prev.target_idx + prev.len;
let base_end = prev.base_idx + prev.len;
assert!(prev_end <= target, "{} <= {} prev {:?}", prev_end, target, prev);
if prev_end == target && base_end == base {
prev.len += len;
return;
}
}
self.ops.push(DiffOp { target_idx: target, base_idx: base, len })
}
fn to_delta(self, base: &Rope, target: &Rope) -> RopeDelta {
let mut els = Vec::with_capacity(self.ops.len() * 2);
let mut targ_pos = 0;
for DiffOp { base_idx, target_idx, len } in self.ops {
if target_idx > targ_pos {
let iv = Interval::new(targ_pos, target_idx);
els.push(DeltaElement::Insert(target.subseq(iv)));
}
els.push(DeltaElement::Copy(base_idx, base_idx + len));
targ_pos = target_idx + len;
}
if targ_pos < target.len() {
let iv = Interval::new(targ_pos, target.len());
els.push(DeltaElement::Insert(target.subseq(iv)));
}
Delta { els, base_len: base.len() }
}
}
/// Creates a map of lines to offsets, ignoring trailing whitespace, and only for those lines
/// where line.len() >= min_size. Offsets refer to the first non-whitespace byte in the line.
fn make_line_hashes(base: &Rope, min_size: usize) -> HashMap<Cow<str>, usize> {
let mut offset = 0;
let mut line_hashes = HashMap::with_capacity(base.len() / 60);
for line in base.lines_raw(..) {
let non_ws = non_ws_offset(&line);
if line.len() - non_ws >= min_size {
let cow = match line {
Cow::Owned(ref s) => Cow::Owned(s[non_ws..].to_string()),
Cow::Borrowed(s) => Cow::Borrowed(&s[non_ws..]),
};
line_hashes.insert(cow, offset + non_ws);
}
offset += line.len();
}
line_hashes
}
#[cfg(test)]
mod tests {
use super::*;
static SMALL_ONE: &str = "This adds FixedSizeAdler32, that has a size set at construction, and keeps bytes in a cyclic buffer of that size to be removed when it fills up.
Current logic (and implementing Write) might be too much, since bytes will probably always be fed one by one anyway. Otherwise a faster way of removing a sequence might be needed (one by one is inefficient).";
static SMALL_TWO: &str = "This adds some function, I guess?, that has a size set at construction, and keeps bytes in a cyclic buffer of that size to be ground up and injested when it fills up.
Currently my sense of smell (and the pain of implementing Write) might be too much, since bytes will probably always be fed one by one anyway. Otherwise crying might be needed (one by one is inefficient).";
static INTERVAL_STR: &str = include_str!("../src/interval.rs");
static BREAKS_STR: &str = include_str!("../src/breaks.rs");
#[test]
fn diff_smoke_test() {
let one = SMALL_ONE.into();
let two = SMALL_TWO.into();
let delta = LineHashDiff::compute_delta(&one, &two);
println!("delta: {:?}", &delta);
let result = delta.apply(&one);
assert_eq!(result, two);
let delta = LineHashDiff::compute_delta(&one, &two);
println!("delta: {:?}", &delta);
let result = delta.apply(&one);
assert_eq!(result, two);
}
#[test]
fn simple_diff() {
let one = "This is a simple string".into();
let two = "This is a string".into();
let delta = LineHashDiff::compute_delta(&one, &two);
println!("delta: {:?}", &delta);
let result = delta.apply(&one);
assert_eq!(result, two);
let delta = LineHashDiff::compute_delta(&two, &one);
println!("delta: {:?}", &delta);
let result = delta.apply(&two);
assert_eq!(result, one);
}
#[test]
fn test_larger_diff() {
let one = INTERVAL_STR.into();
let two = BREAKS_STR.into();
let delta = LineHashDiff::compute_delta(&one, &two);
let result = delta.apply(&one);
assert_eq!(String::from(result), String::from(two));
}
}
| rust | Apache-2.0 | a2dea3059312795c77caadc639df49bf8a7008eb | 2026-01-04T15:41:09.005987Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.