Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@
"menu": {
"cut": "Cut",
"copy": "Copy",
"copyMarkdown": "Copy as Markdown",
"paste": "Paste",
"selectAll": "Select all"
},
Expand Down Expand Up @@ -1014,6 +1015,7 @@
"taskList": "Task list",
"quote": "Quote",
"codeBlock": "Code block",
"copyMarkdown": "Copy as Markdown",
"markdown": "Typed at the start of a line, then a space: heading, list, numbered list, task, quote, code block"
},
"palette": {
Expand Down
2 changes: 2 additions & 0 deletions crates/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@
"menu": {
"cut": "Couper",
"copy": "Copier",
"copyMarkdown": "Copier en Markdown",
"paste": "Coller",
"selectAll": "Tout sélectionner"
},
Expand Down Expand Up @@ -1014,6 +1015,7 @@
"taskList": "Liste de tâches",
"quote": "Citation",
"codeBlock": "Bloc de code",
"copyMarkdown": "Copier en Markdown",
"markdown": "Tapés en début de ligne, suivis d’une espace : titre, liste, liste numérotée, tâche, citation, bloc de code"
},
"palette": {
Expand Down
150 changes: 150 additions & 0 deletions crates/richtext/src/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,156 @@ pub fn selected_text(document: &Document, selection: &Selection) -> String {
out.join("\n")
}

/// What a copy puts on the clipboard: the selected text, each line led by the blocks it sits
/// in — `- `, `3. `, `- [x] ` on an item's first line, two spaces a level of nesting, `> ` in a
/// quote. Inline marks come out as their text. Within one leaf, its text alone.
pub fn copied(document: &Document, selection: &Selection) -> String {
let (start, end) = ordered(selection);
if start.path == end.path {
return selected_text(document, selection);
}
let mut out = Vec::new();
lines(&fragment(document, selection).blocks, ("", ""), &mut out);
out.join("\n")
}

/// The selection as the Markdown a Note is stored in, marks included.
pub fn copied_markdown(document: &Document, selection: &Selection) -> String {
crate::write(&fragment(document, selection))
}

/// The selected blocks, the first and the last leaf cut at the selection's ends.
pub fn fragment(document: &Document, selection: &Selection) -> Document {
let (start, end) = ordered(selection);
let (from, to) = ((&start.path[..], start.offset), (&end.path[..], end.offset));
Document {
blocks: slice(&document.blocks, Some(from), Some(to)),
}
}

/// One end of a cut, as a path below the level it is read at and an offset; `None`, open.
type End<'a> = Option<(&'a [usize], usize)>;

/// The indices kept at this level.
fn kept(from: End<'_>, to: End<'_>) -> std::ops::RangeInclusive<usize> {
let index = |end: End<'_>| end.and_then(|(path, _)| path.first().copied());
index(from).unwrap_or(0)..=index(to).unwrap_or(usize::MAX)
}

/// An end, one level down inside the block or item at `index`: open when it lies elsewhere.
fn below(end: End<'_>, index: usize) -> End<'_> {
end.filter(|(path, _)| path.first() == Some(&index))
.map(|(path, offset)| (&path[1..], offset))
}

fn slice(blocks: &[Block], from: End<'_>, to: End<'_>) -> Vec<Block> {
let kept = kept(from, to);
blocks
.iter()
.enumerate()
.filter(|(index, _)| kept.contains(index))
.map(|(index, block)| cut_block(block, below(from, index), below(to, index)))
.collect()
}

fn cut_block(block: &Block, from: End<'_>, to: End<'_>) -> Block {
let (start, end) = (from.map(|(_, at)| at), to.map(|(_, at)| at));
match block {
Block::Paragraph(content) => Block::Paragraph(cut_inlines(content, start, end)),
Block::Heading { level, content } => Block::Heading {
level: *level,
content: cut_inlines(content, start, end),
},
Block::CodeBlock { language, text } => Block::CodeBlock {
language: language.clone(),
text: text
.chars()
.take(end.unwrap_or(usize::MAX))
.skip(start.unwrap_or(0))
.collect(),
},
Block::List { kind, items } => {
let kept = kept(from, to);
// A numbered item keeps its number.
let kind = match *kind {
ListKind::Ordered { start } => ListKind::Ordered {
start: start + u64::try_from(*kept.start()).unwrap_or(0),
},
other => other,
};
let items = items
.iter()
.enumerate()
.filter(|(index, _)| kept.contains(index))
.map(|(index, item)| Item {
checked: item.checked,
blocks: slice(&item.blocks, below(from, index), below(to, index)),
})
.collect();
Block::List { kind, items }
}
Block::Quote(inner) => Block::Quote(slice(inner, from, to)),
Block::Table(_) | Block::Image { .. } | Block::Rule => block.clone(),
}
}

fn cut_inlines(content: &[Inline], start: Option<usize>, end: Option<usize>) -> Vec<Inline> {
let before_end = match end {
Some(end) => inlines::split(content, end).0,
None => content.to_vec(),
};
match start {
Some(start) => inlines::split(&before_end, start).1,
None => before_end,
}
}

/// The blocks as lines of text, `first` before the first line, `rest` before every other.
fn lines(blocks: &[Block], (first, rest): (&str, &str), out: &mut Vec<String>) {
for (index, block) in blocks.iter().enumerate() {
let lead = if index == 0 { first } else { rest };
match block {
Block::Paragraph(content) | Block::Heading { content, .. } => {
text_lines(&inlines::plain(content), (lead, rest), out);
}
Block::CodeBlock { text, .. } => text_lines(text, (lead, rest), out),
Block::List { kind, items } => {
let nested = format!("{rest} ");
for (at, item) in items.iter().enumerate() {
let lead = if at == 0 { lead } else { rest };
let marked = format!("{lead}{}", marker(*kind, at, item.checked));
lines(&item.blocks, (&marked, &nested), out);
}
}
Block::Quote(inner) => {
lines(inner, (&format!("{lead}> "), &format!("{rest}> ")), out);
}
Block::Table(rows) => {
for (at, cell) in rows.iter().flatten().enumerate() {
let lead = if at == 0 { lead } else { rest };
text_lines(&inlines::plain(cell), (lead, rest), out);
}
}
Block::Image { .. } | Block::Rule => {}
}
}
}

fn text_lines(text: &str, (lead, rest): (&str, &str), out: &mut Vec<String>) {
for (at, line) in text.split('\n').enumerate() {
out.push(format!("{}{line}", if at == 0 { lead } else { rest }));
}
}

fn marker(kind: ListKind, at: usize, checked: bool) -> String {
match kind {
ListKind::Bullet => "- ".to_owned(),
ListKind::Ordered { start } => format!("{}. ", start + u64::try_from(at).unwrap_or(0)),
ListKind::Task if checked => "- [x] ".to_owned(),
ListKind::Task => "- [ ] ".to_owned(),
}
}

/// Text typed at the caret, in place of what is selected.
pub fn insert_text(
document: &mut Document,
Expand Down
54 changes: 54 additions & 0 deletions crates/richtext/src/edit/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,3 +241,57 @@ fn a_paragraph_left_empty_after_a_code_block_is_not_written() {
leave_code(&mut document, &caret_at(&[0], 1));
assert_eq!(read(&write(&document)), read("```\na\n```"));
}

fn whole(document: &Document) -> Selection {
let leaves = tree::leaves(document);
let last = leaves.last().unwrap();
let length = tree::leaf(document, last).unwrap().len();
range((&leaves[0], 0), (last, length))
}

#[test]
fn a_copy_keeps_the_markers_of_its_blocks_and_none_of_the_marks() {
let cases = [
("- one\n- two", "- one\n- two"),
("3. three\n4. four", "3. three\n4. four"),
("- [ ] open\n- [x] done", "- [ ] open\n- [x] done"),
("- one\n - nested\n- two", "- one\n - nested\n- two"),
("> quoted\n>\n> again", "> quoted\n> again"),
("# Title\n\n**bold** and `code`", "Title\nbold and code"),
];
for (markdown, expected) in cases {
let document = read(markdown);
assert_eq!(copied(&document, &whole(&document)), expected, "{markdown}");
}
}

#[test]
fn a_copy_cut_inside_items_keeps_their_numbers_and_within_one_item_its_text_alone() {
let document = read("1. first\n2. second\n3. third");
let from_second = range((&[0, 1, 0], 3), (&[0, 2, 0], 2));
assert_eq!(copied(&document, &from_second), "2. ond\n3. th");
let within = range((&[0, 1, 0], 0), (&[0, 1, 0], 6));
assert_eq!(copied(&document, &within), "second");
}

#[test]
fn copied_as_markdown_reads_back_to_the_same_blocks() {
for markdown in [
"- one **bold**\n- two",
"3. three\n4. four",
"- [ ] open\n- [x] done",
"- one\n - nested\n- two",
"> quoted",
"# Title\n\n**bold** and `code`",
] {
let document = read(markdown);
let copied = copied_markdown(&document, &whole(&document));
assert_eq!(read(&copied), document, "{markdown} gave {copied}");
}
let document = read("1. first\n2. second\n3. third");
let from_second = range((&[0, 1, 0], 0), (&[0, 2, 0], 5));
assert_eq!(
copied_markdown(&document, &from_second),
"2. second\n3. third"
);
}
49 changes: 49 additions & 0 deletions crates/ui/src/app/captures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2034,3 +2034,52 @@ fn an_empty_folder_opened() {
settle(&mut harness);
capture(&mut harness, "folder-empty");
}

#[test]
fn a_wrapped_list_selected_whole() {
use engine::notes::kind::NoteKind;
use engine::notes::language::Language;
let profile = tempfile::tempdir().unwrap();
let mut harness = launch(profile.path());
type_into(&mut harness, "vault-passphrase", PASSPHRASE);
type_into(&mut harness, "vault-confirmation", PASSPHRASE);
click(&mut harness, "vault-submit");
settle(&mut harness);
let backend = &harness.state().backend;
let space = crate::testing::note(backend, "seed").space_id.clone();
let long =
"Une tâche assez longue pour tenir sur plusieurs lignes de la Note ouverte. ".repeat(3);
let content = format!(
"- {}\n- Relire la procédure\n- {}",
long.trim_end(),
long.trim_end()
);
engine::db::run_here(backend.engine(), move |engine| {
let draft = engine::notes::model::NoteDraft {
kind: NoteKind::Note,
language: Language::Txt,
content,
..crate::testing::snippet(space, "Mise en production".to_owned())
};
engine::notes::create_note(engine, draft)
})
.unwrap();
harness.state_mut().state.revision.bump();
settle(&mut harness);
harness
.get_by(|node| {
node.author_id() == Some("note-card-open")
&& node.label().as_deref() == Some("Mise en production")
})
.click();
settle(&mut harness);
click(&mut harness, "editor-rich");
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
settle(&mut harness);
capture(&mut harness, "note-list-selected");
harness
.get_by(|node| node.author_id() == Some("editor-rich"))
.click_secondary();
settle(&mut harness);
capture(&mut harness, "note-menu");
}
Loading
Loading