mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-15 23:32:37 +00:00
Find and replace text in Edit text mode: a Replace row in the Find box, Replace all as one undo step (#2467)
This commit is contained in:
1 parent
2b46f8bf8c
commit
b7cfbd3980
32 files changed
+1569
-39
No files matched your search
@@ -198,6 +198,9 @@ pub const COMMANDS: &[CommandSpec] = &[
|
||||
ct("edit.undo", "Undo", EDIT, Some(Shortcut::cmd("Z")), Undo, "undo-2"),
|
||||
ct("edit.redo", "Redo", EDIT, Some(Shortcut::cmd_shift("Z")), Redo, "redo-2"),
|
||||
c("edit.find", "Find…", EDIT, Some(Shortcut::cmd("F")), Document, "search"),
|
||||
// Find and replace, in Edit text mode (the Find box's Replace row). Not ⌘H/Ctrl+H: macOS
|
||||
// takes ⌘H to hide the app, and Ctrl+H is Read mode on Windows and Linux (as in Acrobat).
|
||||
c("edit.replace", "Replace…", EDIT, Some(Shortcut::cmd_shift("H")), Modification, "replace"),
|
||||
c("edit.advanced_search", "Advanced search…", EDIT, Some(Shortcut::cmd_shift("F")), Document, "search"),
|
||||
c("view.palette", "Find tools and commands…", VIEW, Some(Shortcut::cmd("K")), Nothing, "search"),
|
||||
// Page display: View ▸ Page display and the rail's button list the base layouts as radios and
|
||||
|
||||
@@ -167,8 +167,16 @@ pub const EDIT_LABELS: &[&str] = &[
|
||||
/// The names of the batches built below L7, which an interface shows in the same places as
|
||||
/// [`EDIT_LABELS`] and so translates the same way. A batch built in the interface itself arrives
|
||||
/// already worded in the interface's language.
|
||||
pub const BATCH_LABELS: &[&str] =
|
||||
&["Set document title", "Mark differences", "Detect form fields", "Run JavaScript", "Recognize text", field_table::LABEL, "Style"];
|
||||
pub const BATCH_LABELS: &[&str] = &[
|
||||
"Set document title",
|
||||
"Mark differences",
|
||||
"Detect form fields",
|
||||
"Run JavaScript",
|
||||
"Recognize text",
|
||||
field_table::LABEL,
|
||||
"Style",
|
||||
crate::find_replace::REPLACE_ALL,
|
||||
];
|
||||
|
||||
impl Edit {
|
||||
/// Label for the Edit menu and history ("Undo Rotate pages").
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
//! Find and replace in the page text (Edit text ▸ Replace, the `text_replace` tool).
|
||||
//!
|
||||
//! Each match is rewritten inside its own paragraph ([`crate::Document::text_blocks`]) through
|
||||
//! [`Edit::EditTextBlock`], so the paragraph keeps its fonts, sizes and colours and rewraps in its
|
||||
//! box. The paragraph's `editor_text` is matched with the find bar's own rules
|
||||
//! ([`pdfcraft_render::text::find_in_text`]) and the replacement takes the style of the run it
|
||||
//! lands in ([`pdfcraft_edit::TextBlock::replaced`]); every other run keeps its own.
|
||||
//!
|
||||
//! A longer replacement changes the paragraph only, measured with its own fonts' widths, and
|
||||
//! nothing is shrunk or hyphenated to fit. A paragraph of one row grows to the right, up to 36 pt
|
||||
//! from the crop box (a centred line stays in its own box), then wraps; a paragraph of several rows
|
||||
//! keeps its width and rewraps at spaces. New rows go below the last one at the paragraph's line
|
||||
//! spacing and nothing else on the page moves, so they can run over what is below, or off the page,
|
||||
//! without being reported. A word wider than the width stays whole, past the box.
|
||||
//!
|
||||
//! A match is left alone, and counted, when it runs from one paragraph into the next, lies in
|
||||
//! invisible text over a scan, would need another font (the paragraph's own can't draw the new
|
||||
//! text, see [`pdfcraft_edit::LineEdit::substituted`]) or is not page text the paragraphs hold
|
||||
//! (a form field, a comment, text drawn inside a form XObject). Each paragraph is rewritten on a
|
||||
//! copy first, so the edit returned is exactly what will apply: [`Edit::Batch`] for Replace all,
|
||||
//! one undo step.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::ops::Range;
|
||||
|
||||
use crate::edit::check_permission;
|
||||
use crate::{Document, Edit, EditError, guard};
|
||||
|
||||
/// What to look for and what to put in its place, with the find bar's options.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Replace {
|
||||
pub find: String,
|
||||
/// May be empty: the match is deleted.
|
||||
pub with: String,
|
||||
pub case_sensitive: bool,
|
||||
pub whole_words: bool,
|
||||
}
|
||||
|
||||
/// Which matches to replace.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Which {
|
||||
/// Every match on the pages.
|
||||
All,
|
||||
/// The match the find bar highlights on `page`: the centres of its first and last glyphs, in
|
||||
/// view space (points from the top-left of the displayed page, y down: the text layer's).
|
||||
At { page: usize, start: [f32; 2], end: [f32; 2] },
|
||||
}
|
||||
|
||||
impl Which {
|
||||
/// The first match the find bar shows (page text order: pages in order, then reading order),
|
||||
/// as an [`Which::At`] on its first and last glyphs, or `None` when no page has one. `texts`
|
||||
/// are the pages' text, in page order. Replacing "the first match" is replacing this one: if
|
||||
/// no paragraph holds it, [`Document::plan_replace`] reports it as not editable and replaces
|
||||
/// nothing, rather than passing it for a later match that is.
|
||||
pub fn first_in<'a>(texts: impl IntoIterator<Item = (usize, &'a pdfcraft_render::PageText)>, query: &Replace) -> Option<Which> {
|
||||
texts.into_iter().find_map(|(page, text)| {
|
||||
let found = text.find_opts_limited(&query.find, query.case_sensitive, query.whole_words, 1).into_iter().next()?;
|
||||
let centre = |g: usize| text.glyphs.get(g).map(|g| [(g.rect[0] + g.rect[2]) / 2.0, (g.rect[1] + g.rect[3]) / 2.0]);
|
||||
Some(Which::At { page, start: centre(found.start)?, end: centre(found.end.saturating_sub(1))? })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a match was left as it is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum Skip {
|
||||
/// It runs from one paragraph into the next.
|
||||
SpansParagraphs,
|
||||
/// It is invisible text over a scanned image (recognized text).
|
||||
ScannedText,
|
||||
/// The paragraph's font can't draw the new text; another font would have stepped in.
|
||||
MissingGlyphs,
|
||||
/// The paragraph couldn't be rewritten (see [`Replacement::refusals`]).
|
||||
Refused,
|
||||
/// It is not in the page's editable text: a form field, a comment, text inside a form XObject.
|
||||
NotEditable,
|
||||
}
|
||||
|
||||
impl Skip {
|
||||
/// How the reason is said after a count ("2 skipped: …"); an interface translates it.
|
||||
pub fn wording(self) -> &'static str {
|
||||
match self {
|
||||
Skip::SpansParagraphs => "spans two paragraphs",
|
||||
Skip::ScannedText => "scanned text",
|
||||
Skip::MissingGlyphs => "the font can't draw it",
|
||||
Skip::Refused => "the paragraph can't be rewritten",
|
||||
Skip::NotEditable => "not editable text",
|
||||
}
|
||||
}
|
||||
|
||||
/// A short name for tools.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Skip::SpansParagraphs => "spans_paragraphs",
|
||||
Skip::ScannedText => "scanned_text",
|
||||
Skip::MissingGlyphs => "missing_glyphs",
|
||||
Skip::Refused => "refused",
|
||||
Skip::NotEditable => "not_editable",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every [`Skip::wording`], for an interface to translate.
|
||||
pub const SKIP_WORDINGS: &[&str] =
|
||||
&["spans two paragraphs", "scanned text", "the font can't draw it", "the paragraph can't be rewritten", "not editable text"];
|
||||
|
||||
/// What a replacement would do: the edit (apply it with [`crate::Session::apply`]) and the counts.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Replacement {
|
||||
/// `None` when nothing can be replaced.
|
||||
pub edit: Option<Edit>,
|
||||
/// Matches replaced.
|
||||
pub replaced: usize,
|
||||
/// The pages (0-based, ascending) where something was replaced.
|
||||
pub pages: Vec<usize>,
|
||||
/// Matches left alone, by reason.
|
||||
pub skipped: BTreeMap<Skip, usize>,
|
||||
/// What the engine said about the paragraphs it refused (at most [`MAX_REFUSALS`]).
|
||||
pub refusals: Vec<String>,
|
||||
}
|
||||
|
||||
/// Refusal messages kept in a [`Replacement`].
|
||||
pub const MAX_REFUSALS: usize = 10;
|
||||
|
||||
impl Replacement {
|
||||
pub fn skipped_total(&self) -> usize {
|
||||
self.skipped.values().fold(0, |a, b| a.saturating_add(*b))
|
||||
}
|
||||
|
||||
/// Say that `page`'s text could not be read for the find bar (`why`): its matches can't be
|
||||
/// counted, so one is counted as [`Skip::Refused`] and the page is named in the refusals.
|
||||
pub fn unreadable_page(&mut self, page: usize, why: &str) {
|
||||
refused(self, 1, page, format!("its text could not be read: {why}"));
|
||||
}
|
||||
|
||||
fn skip(&mut self, why: Skip, n: usize) {
|
||||
if n > 0 {
|
||||
let count = self.skipped.entry(why).or_insert(0);
|
||||
*count = count.saturating_add(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The label of Replace all in the history (one of [`crate::BATCH_LABELS`]).
|
||||
pub const REPLACE_ALL: &str = "Replace all";
|
||||
|
||||
impl Document {
|
||||
/// The edit that replaces `query`'s matches on `pages` (0-based; others are ignored), and
|
||||
/// what it replaces and leaves. `found` is how many matches the find bar has on each page:
|
||||
/// those no paragraph holds are counted as [`Skip::NotEditable`] (`None`: not counted). The
|
||||
/// document is not changed; the same permission check as Edit text applies.
|
||||
pub fn plan_replace(
|
||||
&self,
|
||||
pages: &[usize],
|
||||
query: &Replace,
|
||||
which: Which,
|
||||
found: Option<&BTreeMap<usize, usize>>,
|
||||
) -> Result<Replacement, EditError> {
|
||||
let editor = self.editor.as_ref().ok_or_else(|| EditError::ReadOnly(self.read_only_reason.clone().unwrap_or_default()))?;
|
||||
// What Edit text checks: the document's permissions.
|
||||
let probe = Edit::EditTextBlock { page: 0, block: 0, text: String::new(), style: Default::default() };
|
||||
if let Some(p) = editor.cos.permissions() {
|
||||
check_permission(&probe, &p)?;
|
||||
}
|
||||
if query.find.split_whitespace().next().is_none() {
|
||||
return Err(EditError::Invalid("there is nothing to find".into()));
|
||||
}
|
||||
let n = self.info.pages.len();
|
||||
let mut pages: Vec<usize> = pages.iter().copied().filter(|p| *p < n).collect();
|
||||
pages.sort_unstable();
|
||||
pages.dedup();
|
||||
if let Which::At { page, .. } = which {
|
||||
pages.retain(|p| *p == page);
|
||||
}
|
||||
let mut out = Replacement::default();
|
||||
let mut work = editor.cos.clone();
|
||||
let mut edits = Vec::new();
|
||||
for page in pages {
|
||||
// A page whose text can't be read is reported, and the others still replaced.
|
||||
let blocks = match pdfcraft_edit::text_blocks(&work, page) {
|
||||
Ok(blocks) => blocks,
|
||||
Err(e) => {
|
||||
refused(&mut out, found.and_then(|f| f.get(&page)).copied().unwrap_or(0), page, e.to_string());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let matches: Vec<Vec<Range<usize>>> = blocks.iter().map(|b| find(&b.editor_text, query, usize::MAX)).collect();
|
||||
// Paragraph `k`'s matches to replace now.
|
||||
let mut chosen: BTreeMap<usize, Vec<Range<usize>>> = BTreeMap::new();
|
||||
match which {
|
||||
Which::All => {
|
||||
let held = matches.iter().fold(0usize, |a, m| a.saturating_add(m.len()));
|
||||
let spanning = spanning(&blocks, query);
|
||||
out.skip(Skip::SpansParagraphs, spanning);
|
||||
if let Some(f) = found.and_then(|f| f.get(&page)) {
|
||||
out.skip(Skip::NotEditable, f.saturating_sub(held.saturating_add(spanning)));
|
||||
}
|
||||
chosen.extend(matches.into_iter().enumerate().filter(|(_, m)| !m.is_empty()));
|
||||
}
|
||||
Which::At { start, end, .. } => match at(self, &work, page, &blocks, &matches, start, end) {
|
||||
Ok((k, m)) => {
|
||||
chosen.insert(k, vec![m]);
|
||||
}
|
||||
Err(why) => out.skip(why, 1),
|
||||
},
|
||||
}
|
||||
// Last paragraph first, which usually leaves those before it where they were. That is
|
||||
// checked, not assumed: once a paragraph on this page is rewritten, the page is read
|
||||
// again and a paragraph that is no longer what the match was found in is refused.
|
||||
let mut rewrote = false;
|
||||
for (k, ranges) in chosen.into_iter().rev() {
|
||||
let Some(block) = blocks.get(k) else { continue };
|
||||
let count = ranges.len();
|
||||
if rewrote {
|
||||
let same = pdfcraft_edit::text_blocks(&work, page)
|
||||
.ok()
|
||||
.is_some_and(|now| now.get(k).is_some_and(|b| b.editor_text == block.editor_text));
|
||||
if !same {
|
||||
refused(&mut out, count, page, "the page's paragraphs moved after an earlier replacement".into());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if block.invisible {
|
||||
out.skip(Skip::ScannedText, count);
|
||||
continue;
|
||||
}
|
||||
let Some((text, sources)) = block.replaced(&ranges, &query.with) else {
|
||||
out.skip(Skip::Refused, count);
|
||||
continue;
|
||||
};
|
||||
if text == block.editor_text {
|
||||
// The replacement is what was there.
|
||||
out.replaced = out.replaced.saturating_add(count);
|
||||
continue;
|
||||
}
|
||||
let style = pdfcraft_edit::BlockStyle { sources, ..Default::default() };
|
||||
let mut trial = work.clone();
|
||||
match guard(|| pdfcraft_edit::rewrite_block(&mut trial, page, k, Some(&text), &style)) {
|
||||
Ok(Ok(pdfcraft_edit::LineEdit { substituted: None })) => {
|
||||
work = trial;
|
||||
rewrote = true;
|
||||
edits.push(Edit::EditTextBlock { page, block: k, text, style });
|
||||
out.replaced = out.replaced.saturating_add(count);
|
||||
if !out.pages.contains(&page) {
|
||||
out.pages.push(page);
|
||||
}
|
||||
}
|
||||
Ok(Ok(pdfcraft_edit::LineEdit { substituted: Some(_) })) => out.skip(Skip::MissingGlyphs, count),
|
||||
Ok(Err(e)) => refused(&mut out, count, page, e.to_string()),
|
||||
Err(panic) => refused(&mut out, count, page, panic),
|
||||
}
|
||||
}
|
||||
}
|
||||
out.pages.sort_unstable();
|
||||
out.edit = match (which, edits.len()) {
|
||||
(_, 0) => None,
|
||||
(Which::All, _) => Some(Edit::Batch { label: REPLACE_ALL.into(), edits }),
|
||||
(Which::At { .. }, _) => edits.pop(),
|
||||
};
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn find(text: &str, query: &Replace, limit: usize) -> Vec<Range<usize>> {
|
||||
pdfcraft_render::text::find_in_text(text, &query.find, query.case_sensitive, query.whole_words, limit)
|
||||
}
|
||||
|
||||
fn refused(out: &mut Replacement, count: usize, page: usize, why: String) {
|
||||
out.skip(Skip::Refused, count);
|
||||
if out.refusals.len() < MAX_REFUSALS {
|
||||
out.refusals.push(format!("page {}: {why}", page.saturating_add(1)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Matches that start in one paragraph and end in a later one: the page's paragraphs read one
|
||||
/// after another (a line break between two), as the find bar reads the page.
|
||||
fn spanning(blocks: &[pdfcraft_edit::TextBlock], query: &Replace) -> usize {
|
||||
let mut joined = String::new();
|
||||
let mut ends = Vec::with_capacity(blocks.len());
|
||||
for b in blocks {
|
||||
if !joined.is_empty() {
|
||||
joined.push('\n');
|
||||
}
|
||||
joined.push_str(&b.editor_text);
|
||||
ends.push(joined.len());
|
||||
}
|
||||
// Which paragraph a byte of `joined` is in (a separator counts with the paragraph after it).
|
||||
let paragraph = |byte: usize| ends.partition_point(|end| *end <= byte);
|
||||
find(&joined, query, usize::MAX).into_iter().filter(|r| paragraph(r.start) != paragraph(r.end.saturating_sub(1))).count()
|
||||
}
|
||||
|
||||
/// The paragraph match the find bar's match at `start` … `end` (view space) is: the paragraph
|
||||
/// whose box holds both, and its match nearest `start`.
|
||||
fn at(
|
||||
doc: &Document,
|
||||
cos: &pdfcraft_cos::Document,
|
||||
page: usize,
|
||||
blocks: &[pdfcraft_edit::TextBlock],
|
||||
matches: &[Vec<Range<usize>>],
|
||||
start: [f32; 2],
|
||||
end: [f32; 2],
|
||||
) -> Result<(usize, Range<usize>), Skip> {
|
||||
let info = doc.info.pages.get(page).ok_or(Skip::NotEditable)?;
|
||||
let view = |x: f64, y: f64| info.user_to_view(x as f32, y as f32);
|
||||
// A paragraph's box in view space, a little larger so a glyph's centre on its edge is inside.
|
||||
let holds = |b: &pdfcraft_edit::TextBlock, p: [f32; 2]| {
|
||||
let corners = [view(b.rect[0], b.rect[1]), view(b.rect[2], b.rect[3]), view(b.rect[0], b.rect[3]), view(b.rect[2], b.rect[1])];
|
||||
let pad = (b.size as f32 * 0.3).clamp(1.0, 12.0);
|
||||
let (x0, x1) = corners.iter().fold((f32::MAX, f32::MIN), |(a, b), c| (a.min(c[0]), b.max(c[0])));
|
||||
let (y0, y1) = corners.iter().fold((f32::MAX, f32::MIN), |(a, b), c| (a.min(c[1]), b.max(c[1])));
|
||||
p[0] >= x0 - pad && p[0] <= x1 + pad && p[1] >= y0 - pad && p[1] <= y1 + pad
|
||||
};
|
||||
let lines = pdfcraft_edit::text_lines(cos, page).unwrap_or_default();
|
||||
// Where a match's first character is drawn, estimated along its run.
|
||||
let place = |b: &pdfcraft_edit::TextBlock, r: &Range<usize>| -> Option<[f32; 2]> {
|
||||
let (span, line) = b.spans.iter().find(|(s, _)| s.contains(&r.start)).or_else(|| b.spans.iter().find(|(s, _)| s.start >= r.start))?;
|
||||
let line = lines.get(*line)?;
|
||||
let run = b.editor_text.get(span.clone())?;
|
||||
let before = b.editor_text.get(span.start..r.start.max(span.start))?.chars().count() as f64;
|
||||
let total = run.chars().count().max(1) as f64;
|
||||
let along = ((before + 0.5) / total).clamp(0.0, 1.0);
|
||||
let x = line.rect[0] + along * (line.rect[2] - line.rect[0]);
|
||||
Some(view(x, (line.rect[1] + line.rect[3]) / 2.0))
|
||||
};
|
||||
let distance = |p: [f32; 2]| (p[0] - start[0]).hypot(p[1] - start[1]);
|
||||
let mut best: Option<(f32, usize, Range<usize>)> = None;
|
||||
for (k, b) in blocks.iter().enumerate().filter(|(_, b)| holds(b, start)) {
|
||||
for r in matches.get(k).into_iter().flatten() {
|
||||
let d = place(b, r).map_or(f32::MAX, distance);
|
||||
if best.as_ref().is_none_or(|(e, ..)| d < *e) {
|
||||
best = Some((d, k, r.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
match best {
|
||||
Some((_, k, r)) if blocks.get(k).is_some_and(|b| holds(b, end)) => Ok((k, r)),
|
||||
Some(_) => Err(Skip::SpansParagraphs),
|
||||
None if blocks.iter().any(|b| holds(b, start)) && blocks.iter().any(|b| holds(b, end) && !holds(b, start)) => Err(Skip::SpansParagraphs),
|
||||
None => Err(Skip::NotEditable),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod rewrite_order_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Replacing in several paragraphs of one page: each is checked against the page as it is after
|
||||
//! the earlier rewrites, and a paragraph that still reads as it was found is replaced.
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::{DocId, Session};
|
||||
|
||||
fn page_with(content: &str) -> Vec<u8> {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".into(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn open(bytes: Vec<u8>) -> (Session, DocId) {
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("order.pdf", None, Arc::new(bytes), None).expect("opens");
|
||||
(s, id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_in_every_paragraph_of_a_page_still_replaces_each_one() {
|
||||
let (mut s, id) = open(page_with("BT /F1 12 Tf 72 700 Td (red apple) Tj 0 -60 Td (red pear) Tj 0 -60 Td (red plum) Tj ET"));
|
||||
let q = Replace { find: "red".into(), with: "green".into(), ..Default::default() };
|
||||
let plan = s.get(id).unwrap().plan_replace(&[0], &q, Which::All, None).unwrap();
|
||||
assert_eq!(plan.replaced, 3, "refusals: {:?}", plan.refusals);
|
||||
assert!(plan.refusals.is_empty(), "{:?}", plan.refusals);
|
||||
let edit = plan.edit.expect("an edit");
|
||||
s.apply(id, edit).unwrap();
|
||||
let texts: Vec<String> = s.get(id).unwrap().text_blocks(0).into_iter().map(|b| b.text).collect();
|
||||
assert_eq!(texts, ["green apple", "green pear", "green plum"]);
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::{DocId, Session};
|
||||
|
||||
/// A one-page document with `content` and two fonts: `F1` Helvetica, `F2` Helvetica-Bold, and
|
||||
/// `F3` a subset of a face no computer has, with glyphs for `a` and `b` only.
|
||||
fn pdf(content: &str) -> Vec<u8> {
|
||||
let objs: Vec<String> = vec![
|
||||
"<< /Type /Catalog /Pages 2 0 R >>".into(),
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R /F2 6 0 R /F3 7 0 R >> >> >>".into(),
|
||||
format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
|
||||
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>".into(),
|
||||
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+NoSuchFace /FirstChar 97 /LastChar 99 /Widths [500 520 0] /Encoding /WinAnsiEncoding >>"
|
||||
.into(),
|
||||
];
|
||||
let mut out = b"%PDF-1.7\n".to_vec();
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(out.len());
|
||||
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
|
||||
}
|
||||
let xref = out.len();
|
||||
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
|
||||
for o in offsets {
|
||||
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
|
||||
}
|
||||
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
fn open(bytes: Vec<u8>) -> (Session, DocId) {
|
||||
let mut s = Session::new().with_clock(|| 1_700_000_000);
|
||||
let id = s.open("replace.pdf", None, Arc::new(bytes), None).expect("opens");
|
||||
(s, id)
|
||||
}
|
||||
|
||||
fn query(find: &str, with: &str) -> Replace {
|
||||
Replace { find: find.into(), with: with.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Plan and apply; the plan's counts.
|
||||
fn replace_all(s: &mut Session, id: DocId, q: &Replace) -> Replacement {
|
||||
let pages: Vec<usize> = (0..s.get(id).unwrap().info.pages.len()).collect();
|
||||
let plan = s.get(id).unwrap().plan_replace(&pages, q, Which::All, None).unwrap();
|
||||
if let Some(edit) = plan.edit.clone() {
|
||||
s.apply(id, edit).unwrap();
|
||||
}
|
||||
plan
|
||||
}
|
||||
|
||||
fn texts(s: &Session, id: DocId, page: usize) -> Vec<String> {
|
||||
s.get(id).unwrap().text_blocks(page).into_iter().map(|b| b.text).collect()
|
||||
}
|
||||
|
||||
/// The page text as the find bar reads it (the text layer's glyphs).
|
||||
fn page_text(s: &Session, id: DocId, page: usize) -> pdfcraft_render::PageText {
|
||||
let doc = s.get(id).unwrap();
|
||||
let mut r = pdfcraft_render::PageRenderer::new(doc.bytes.clone(), pdfcraft_render::RenderConfig::default());
|
||||
let out = r.render(pdfcraft_render::RenderRequest { page, kind: pdfcraft_render::RequestKind::Text, scale: 1.0, ..Default::default() });
|
||||
out.text.map(|t| t.as_ref().clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_replaced_word_keeps_its_paragraphs_font_and_size() {
|
||||
let (mut s, id) = open(pdf("BT /F1 14 Tf 72 700 Td (The quick brown fox) Tj ET"));
|
||||
let plan = replace_all(&mut s, id, &query("quick", "slow"));
|
||||
assert_eq!((plan.replaced, plan.pages.clone(), plan.skipped_total()), (1, vec![0], 0));
|
||||
assert_eq!(texts(&s, id, 0), ["The slow brown fox"]);
|
||||
let lines = s.get(id).unwrap().text_lines(0);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert_eq!((lines[0].font.as_str(), lines[0].base_font.as_str(), lines[0].size), ("F1", "Helvetica", 14.0));
|
||||
assert_eq!(s.get(id).unwrap().can_undo(), Some("Replace all"));
|
||||
}
|
||||
|
||||
/// A red word and a bold name inside a paragraph keep their own style when words around them
|
||||
/// are replaced; a replacement inside the red word stays red.
|
||||
#[test]
|
||||
fn a_mixed_style_paragraph_keeps_the_other_runs_styles() {
|
||||
let content = "BT /F1 12 Tf 72 700 Td 0 g (Please pay the invoice ) Tj 1 0 0 rg (now) Tj 0 g (, before the end of the month,) Tj ET
|
||||
BT /F1 12 Tf 72 686 Td 0 g (as agreed with ) Tj /F2 12 Tf (Ada Lovelace) Tj /F1 12 Tf (.) Tj ET";
|
||||
let (mut s, id) = open(pdf(content));
|
||||
assert_eq!(texts(&s, id, 0).len(), 1, "one paragraph of five runs");
|
||||
let q = Replace { whole_words: true, ..query("the", "THE") };
|
||||
let plan = replace_all(&mut s, id, &q);
|
||||
assert_eq!(plan.replaced, 3);
|
||||
let plan = replace_all(&mut s, id, &query("now", "today"));
|
||||
assert_eq!(plan.replaced, 1);
|
||||
assert_eq!(texts(&s, id, 0), ["Please pay THE invoice today, before THE end of THE month, as agreed with Ada Lovelace."]);
|
||||
let lines = s.get(id).unwrap().text_lines(0);
|
||||
let run = |word: &str| lines.iter().find(|l| l.text.contains(word)).unwrap_or_else(|| panic!("no run with {word:?}: {lines:?}"));
|
||||
assert_eq!(run("today").color, [1.0, 0.0, 0.0], "the replacement takes the red run it lands in");
|
||||
assert_eq!(run("today").text.trim(), "today", "and only it is red");
|
||||
assert_eq!(run("Ada").base_font, "Helvetica-Bold");
|
||||
assert_eq!(run("Ada").text.trim(), "Ada Lovelace");
|
||||
assert_eq!(run("invoice").color, [0.0, 0.0, 0.0]);
|
||||
assert_eq!(run("invoice").base_font, "Helvetica");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_all_across_pages_is_one_undo_step() {
|
||||
let (mut s, id) = open(crate::tests::fixture(3));
|
||||
let before = s.get(id).unwrap().bytes.clone();
|
||||
let plan = replace_all(&mut s, id, &query("page", "Sheet"));
|
||||
assert_eq!((plan.replaced, plan.pages.clone()), (3, vec![0, 1, 2]));
|
||||
assert!(matches!(&plan.edit, Some(Edit::Batch { edits, .. }) if edits.len() == 3));
|
||||
for p in 0..3 {
|
||||
assert_eq!(texts(&s, id, p), [format!("Sheet {}", p + 1)]);
|
||||
}
|
||||
s.undo(id).unwrap();
|
||||
for p in 0..3 {
|
||||
assert_eq!(texts(&s, id, p), [format!("Page {}", p + 1)]);
|
||||
}
|
||||
assert_eq!(s.get(id).unwrap().can_undo(), None, "one step undid all three pages");
|
||||
assert_eq!(s.get(id).unwrap().bytes, before, "the original bytes are back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_words_and_case_follow_the_find_options() {
|
||||
let content = "BT /F1 12 Tf 72 700 Td (cat Cats concat CAT) Tj ET";
|
||||
let count = |q: Replace| {
|
||||
let (s, id) = open(pdf(content));
|
||||
s.get(id).unwrap().plan_replace(&[0], &q, Which::All, None).unwrap().replaced
|
||||
};
|
||||
assert_eq!(count(query("cat", "dog")), 4);
|
||||
assert_eq!(count(Replace { whole_words: true, ..query("cat", "dog") }), 2);
|
||||
assert_eq!(count(Replace { case_sensitive: true, ..query("cat", "dog") }), 2);
|
||||
assert_eq!(count(Replace { case_sensitive: true, whole_words: true, ..query("CAT", "dog") }), 1);
|
||||
let (mut s, id) = open(pdf(content));
|
||||
replace_all(&mut s, id, &Replace { whole_words: true, ..query("cat", "dog") });
|
||||
assert_eq!(texts(&s, id, 0), ["dog Cats concat dog"]);
|
||||
// An empty replacement deletes the match.
|
||||
replace_all(&mut s, id, &query(" concat", ""));
|
||||
assert_eq!(texts(&s, id, 0), ["dog Cats dog"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_match_spanning_two_paragraphs_is_skipped_and_counted() {
|
||||
let content = "BT /F1 12 Tf 72 700 Td (The first ends here) Tj ET BT /F1 12 Tf 72 500 Td (second starts there) Tj ET";
|
||||
let (mut s, id) = open(pdf(content));
|
||||
assert_eq!(texts(&s, id, 0).len(), 2);
|
||||
let plan = replace_all(&mut s, id, &query("here second", "x"));
|
||||
assert_eq!(plan.replaced, 0);
|
||||
assert_eq!(plan.skipped, BTreeMap::from([(Skip::SpansParagraphs, 1)]));
|
||||
assert!(plan.edit.is_none());
|
||||
assert_eq!(texts(&s, id, 0), ["The first ends here", "second starts there"]);
|
||||
}
|
||||
|
||||
/// The subset in `F3` has glyphs for `a` and `b` only, from a face no computer has: a `c` would
|
||||
/// be drawn in Helvetica instead. That paragraph is left alone and counted, the other replaced.
|
||||
#[test]
|
||||
fn a_character_the_font_cannot_draw_is_skipped_and_counted() {
|
||||
let content = "BT /F3 12 Tf 72 700 Td (ab ba) Tj ET BT /F1 12 Tf 72 500 Td (ab in Helvetica) Tj ET";
|
||||
let (mut s, id) = open(pdf(content));
|
||||
let before = texts(&s, id, 0);
|
||||
assert_eq!(before, ["ab ba", "ab in Helvetica"]);
|
||||
let plan = replace_all(&mut s, id, &query("ab", "cb"));
|
||||
assert_eq!(plan.replaced, 1);
|
||||
assert_eq!(plan.skipped, BTreeMap::from([(Skip::MissingGlyphs, 1)]));
|
||||
assert_eq!(texts(&s, id, 0), ["ab ba", "cb in Helvetica"]);
|
||||
let lines = s.get(id).unwrap().text_lines(0);
|
||||
assert!(lines.iter().filter(|l| l.text.contains("ab ba")).all(|l| l.font == "F3"), "the subset paragraph keeps its font: {lines:?}");
|
||||
// What the subset can draw still goes in.
|
||||
let plan = replace_all(&mut s, id, &query("ab ba", "ba ab"));
|
||||
assert_eq!((plan.replaced, plan.skipped_total()), (1, 0));
|
||||
assert_eq!(texts(&s, id, 0)[0], "ba ab");
|
||||
}
|
||||
|
||||
/// The styled rewrite (a paragraph of several runs) reports the missing character as the
|
||||
/// one-style rewrite above does.
|
||||
#[test]
|
||||
fn a_character_the_font_cannot_draw_is_skipped_in_a_paragraph_of_several_runs() {
|
||||
let (mut s, id) = open(pdf("BT /F3 12 Tf 72 700 Td (ab ) Tj /F1 12 Tf (and Helvetica) Tj ET"));
|
||||
let plan = replace_all(&mut s, id, &query("ab", "cb"));
|
||||
assert_eq!(plan.replaced, 0);
|
||||
assert_eq!(plan.skipped, BTreeMap::from([(Skip::MissingGlyphs, 1)]));
|
||||
assert!(plan.edit.is_none());
|
||||
}
|
||||
|
||||
/// A character Helvetica has no code for is never written as a box or a `?`: whether another font
|
||||
/// has it or none does, the match is left alone and reported.
|
||||
#[test]
|
||||
fn a_replacement_outside_the_fonts_encoding_is_reported_and_changes_nothing() {
|
||||
for with in ["\u{65E5}\u{672C}", "\u{1F600}"] {
|
||||
let (mut s, id) = open(pdf("BT /F1 12 Tf 72 700 Td (one cat) Tj ET"));
|
||||
let plan = replace_all(&mut s, id, &query("cat", with));
|
||||
assert_eq!((plan.replaced, plan.skipped_total()), (0, 1), "{with}: {plan:?}");
|
||||
assert!(plan.edit.is_none(), "{with}");
|
||||
assert_eq!(texts(&s, id, 0), ["one cat"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// The rects of the page's text lines holding `word`.
|
||||
fn line_rects(s: &Session, id: DocId, word: &str) -> Vec<[f64; 4]> {
|
||||
s.get(id).unwrap().text_lines(0).into_iter().filter(|l| l.text.contains(word)).map(|l| l.rect).collect()
|
||||
}
|
||||
|
||||
/// A paragraph of several rows keeps its width and gains rows below; what is under it stays where
|
||||
/// it was, so the new rows run over it.
|
||||
#[test]
|
||||
fn a_longer_replacement_adds_rows_and_moves_nothing_else() {
|
||||
let content =
|
||||
"BT /F1 12 Tf 14 TL 72 700 Td (alpha beta gamma delta) Tj T* (epsilon zeta eta theta) Tj ET BT /F1 12 Tf 72 650 Td (next paragraph) Tj ET";
|
||||
let (mut s, id) = open(pdf(content));
|
||||
assert_eq!(texts(&s, id, 0).len(), 2);
|
||||
let right = s.get(id).unwrap().text_blocks(0)[0].rect[2];
|
||||
let next = line_rects(&s, id, "next paragraph");
|
||||
let with = "a much longer replacement that takes several more rows than the paragraph has";
|
||||
let plan = replace_all(&mut s, id, &query("beta", with));
|
||||
assert_eq!((plan.replaced, plan.skipped_total()), (1, 0));
|
||||
let lines = s.get(id).unwrap().text_lines(0);
|
||||
let rows: Vec<_> = lines.iter().filter(|l| !l.text.contains("next paragraph")).collect();
|
||||
assert!(rows.len() >= 5, "{rows:?}");
|
||||
assert!(rows.iter().all(|l| l.rect[2] <= right + 1.0), "the rows keep the width: {rows:?}");
|
||||
assert!(rows.iter().any(|l| l.rect[1] < next[0][1]), "the new rows go past what was below: {rows:?}");
|
||||
assert_eq!(line_rects(&s, id, "next paragraph"), next);
|
||||
}
|
||||
|
||||
/// One row grows to the right up to the margin, then wraps; a word wider than that stays whole.
|
||||
#[test]
|
||||
fn a_longer_replacement_grows_one_row_to_the_margin() {
|
||||
let (mut s, id) = open(pdf("BT /F1 12 Tf 72 700 Td (short) Tj ET"));
|
||||
replace_all(&mut s, id, &query("short", "a line far wider than the word it took the place of"));
|
||||
assert_eq!(s.get(id).unwrap().text_lines(0).len(), 1);
|
||||
let (mut s, id) = open(pdf("BT /F1 12 Tf 72 700 Td (short) Tj ET"));
|
||||
replace_all(&mut s, id, &query("short", &"many words in a row ".repeat(8)));
|
||||
let lines = s.get(id).unwrap().text_lines(0);
|
||||
assert!(lines.len() > 1 && lines.iter().all(|l| l.rect[2] <= 595.0 - 36.0 + 1.0), "{lines:?}");
|
||||
let (mut s, id) = open(pdf("BT /F1 12 Tf 72 700 Td (short) Tj ET"));
|
||||
replace_all(&mut s, id, &query("short", &"w".repeat(80)));
|
||||
let lines = s.get(id).unwrap().text_lines(0);
|
||||
assert_eq!(lines.len(), 1);
|
||||
assert!(lines[0].rect[2] > 595.0, "the word runs past the page: {lines:?}");
|
||||
}
|
||||
|
||||
/// A match can run over a row's end hyphen, typed as the find bar reads it (the break is a space);
|
||||
/// Replace all then folds case, joins the rows and counts what the find bar counts. The word read
|
||||
/// unhyphenated is also a find-bar match, but no paragraph's text holds it: left alone and counted.
|
||||
#[test]
|
||||
fn case_insensitive_replace_all_takes_a_match_across_a_hyphenated_row_end() {
|
||||
let content = "BT /F1 12 Tf 14 TL 72 700 Td (An EXAM-) Tj T* (PLE and an Exam-) Tj T* (ple to end) Tj ET";
|
||||
let (mut s, id) = open(pdf(content));
|
||||
assert_eq!(texts(&s, id, 0), ["An EXAMPLE and an Example to end"]);
|
||||
let text = page_text(&s, id, 0);
|
||||
let whole = query("example", "sample");
|
||||
let found = BTreeMap::from([(0, text.find_opts(&whole.find, false, false).len())]);
|
||||
assert_eq!(found[&0], 2);
|
||||
let none = s.get(id).unwrap().plan_replace(&[0], &whole, Which::All, Some(&found)).unwrap();
|
||||
assert_eq!((none.replaced, none.skipped_total(), none.edit.is_none()), (0, 2, true));
|
||||
let q = query("exam- ple", "sample");
|
||||
let found = BTreeMap::from([(0, text.find_opts(&q.find, false, false).len())]);
|
||||
assert_eq!(found[&0], 2);
|
||||
let plan = s.get(id).unwrap().plan_replace(&[0], &q, Which::All, Some(&found)).unwrap();
|
||||
assert_eq!((plan.replaced, plan.skipped_total()), (2, 0));
|
||||
s.apply(id, plan.edit.unwrap()).unwrap();
|
||||
assert_eq!(texts(&s, id, 0), ["An sample and an sample to end"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invisible_text_over_a_scan_is_skipped() {
|
||||
let (mut s, id) = open(pdf("BT 3 Tr /F1 12 Tf 72 700 Td (recognized words) Tj ET"));
|
||||
let plan = replace_all(&mut s, id, &query("words", "text"));
|
||||
assert_eq!(plan.skipped, BTreeMap::from([(Skip::ScannedText, 1)]));
|
||||
assert!(plan.edit.is_none());
|
||||
}
|
||||
|
||||
/// What the find bar counts on a page beyond what the paragraphs hold is reported as not
|
||||
/// editable text (a form field, a comment), so the counts add up to what was highlighted.
|
||||
#[test]
|
||||
fn matches_the_paragraphs_dont_hold_are_counted_as_not_editable() {
|
||||
let (s, id) = open(pdf("BT /F1 12 Tf 72 700 Td (one cat) Tj ET"));
|
||||
let found = BTreeMap::from([(0, 3)]);
|
||||
let plan = s.get(id).unwrap().plan_replace(&[0], &query("cat", "dog"), Which::All, Some(&found)).unwrap();
|
||||
assert_eq!(plan.replaced, 1);
|
||||
assert_eq!(plan.skipped, BTreeMap::from([(Skip::NotEditable, 2)]));
|
||||
}
|
||||
|
||||
/// Replace (one match): the highlighted one, found by where the find bar's glyphs are, even when
|
||||
/// the paragraph holds the word twice.
|
||||
#[test]
|
||||
fn the_highlighted_match_is_the_one_replaced() {
|
||||
let (mut s, id) = open(pdf("BT /F1 12 Tf 72 700 Td (cat and cat) Tj ET BT /F1 12 Tf 72 500 Td (no match) Tj ET"));
|
||||
let text = page_text(&s, id, 0);
|
||||
let found = text.find("cat");
|
||||
assert_eq!(found.len(), 2);
|
||||
let centre = |g: usize| {
|
||||
let r = text.glyphs[g].rect;
|
||||
[(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]
|
||||
};
|
||||
let second = &found[1];
|
||||
let which = Which::At { page: 0, start: centre(second.start), end: centre(second.end - 1) };
|
||||
let plan = s.get(id).unwrap().plan_replace(&[0], &query("cat", "dog"), which, None).unwrap();
|
||||
assert_eq!(plan.replaced, 1);
|
||||
assert!(matches!(&plan.edit, Some(Edit::EditTextBlock { block: 0, .. })), "one paragraph edit, not a batch: {:?}", plan.edit);
|
||||
s.apply(id, plan.edit.unwrap()).unwrap();
|
||||
assert_eq!(texts(&s, id, 0), ["cat and dog", "no match"]);
|
||||
// A point in no paragraph is not editable text.
|
||||
let away = Which::At { page: 0, start: [500.0, 20.0], end: [510.0, 20.0] };
|
||||
let plan = s.get(id).unwrap().plan_replace(&[0], &query("cat", "dog"), away, None).unwrap();
|
||||
assert_eq!(plan.skipped, BTreeMap::from([(Skip::NotEditable, 1)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_replaces_only_the_first_match_in_document_order() {
|
||||
let (mut s, id) = open(crate::tests::fixture(2));
|
||||
let q = query("page", "Sheet");
|
||||
let texts_of: Vec<_> = (0..2).map(|p| page_text(&s, id, p)).collect();
|
||||
let which = Which::first_in(texts_of.iter().enumerate(), &q).expect("the find bar has a match");
|
||||
assert!(matches!(which, Which::At { page: 0, .. }));
|
||||
let plan = s.get(id).unwrap().plan_replace(&[0, 1], &q, which, None).unwrap();
|
||||
assert_eq!((plan.replaced, plan.pages.clone()), (1, vec![0]));
|
||||
s.apply(id, plan.edit.unwrap()).unwrap();
|
||||
assert_eq!((texts(&s, id, 0), texts(&s, id, 1)), (vec!["Sheet 1".to_string()], vec!["Page 2".to_string()]));
|
||||
assert!(Which::first_in(texts_of.iter().enumerate(), &query("absent", "x")).is_none());
|
||||
}
|
||||
|
||||
/// The first match is the find bar's, not the first one a paragraph holds: when it is a match no
|
||||
/// paragraph holds (a word split by a line-end hyphen), it is reported and nothing is replaced,
|
||||
/// not the later paragraph that has the word whole.
|
||||
#[test]
|
||||
fn first_does_not_skip_a_match_no_paragraph_holds_for_a_later_one() {
|
||||
let content = "BT /F1 12 Tf 14 TL 72 700 Td (An EXAM-) Tj T* (PLE to end) Tj ET BT /F1 12 Tf 72 400 Td (a second example) Tj ET";
|
||||
let (s, id) = open(pdf(content));
|
||||
let q = query("example", "sample");
|
||||
let text = page_text(&s, id, 0);
|
||||
assert_eq!(text.find_opts("example", false, false).len(), 2, "the find bar has both");
|
||||
let which = Which::first_in([(0, &text)], &q).unwrap();
|
||||
let plan = s.get(id).unwrap().plan_replace(&[0], &q, which, None).unwrap();
|
||||
assert_eq!((plan.replaced, plan.edit.is_none()), (0, true), "{plan:?}");
|
||||
assert_eq!(plan.skipped, BTreeMap::from([(Skip::NotEditable, 1)]));
|
||||
assert_eq!(texts(&s, id, 0).last().unwrap(), "a second example");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_to_find_is_refused() {
|
||||
let (s, id) = open(crate::tests::fixture(1));
|
||||
assert!(matches!(s.get(id).unwrap().plan_replace(&[0], &query(" ", "x"), Which::All, None), Err(EditError::Invalid(_))));
|
||||
}
|
||||
@@ -32,6 +32,7 @@ mod error;
|
||||
pub mod export;
|
||||
pub mod field_table;
|
||||
mod fill_sign;
|
||||
pub mod find_replace;
|
||||
mod history;
|
||||
pub mod js;
|
||||
mod layers;
|
||||
|
||||
Reference in new issue
Block a user