use glory_render::{Error, TextSelection};
pub const MAX_MARKDOWN_BYTES: usize = 1_048_576;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Command {
Bold,
Italic,
Strikethrough,
InlineCode,
Heading(u8),
Quote,
BulletList,
OrderedList,
TaskList,
CodeBlock,
Table,
HorizontalRule,
Link { destination: String },
Image { destination: String },
Insert(String),
Indent,
Outdent,
ContinueLine,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Edit {
pub value: String,
pub selection: TextSelection,
}
pub fn safe_destination(value: &str) -> bool {
let value = value.trim();
if value.is_empty()
|| value.chars().any(|c| c.is_control() || c.is_whitespace())
|| value.starts_with("//")
|| value.contains('\\')
{
return false;
}
let first = value.split(['/', '?', '#']).next().unwrap_or_default();
match first.split_once(':') {
None => true,
Some((scheme, _)) => {
value
.split_once(':')
.is_some_and(|(_, rest)| !rest.is_empty())
&& ["http", "https", "mailto"]
.iter()
.any(|allowed| scheme.eq_ignore_ascii_case(allowed))
}
}
}
fn units(value: &str) -> usize {
value.encode_utf16().count()
}
fn starts(value: &str, prefixes: &[&str]) -> bool {
prefixes.iter().any(|prefix| value.starts_with(prefix))
}
fn selection(value: &str, start: usize, end: usize) -> TextSelection {
TextSelection {
start: units(&value[..start]),
end: units(&value[..end]),
..Default::default()
}
}
fn replace(
source: &str,
range: std::ops::Range<usize>,
value: &str,
selected: std::ops::Range<usize>,
) -> Result<Edit, Error> {
let length = source.len() - range.len() + value.len();
if length > MAX_MARKDOWN_BYTES || value.contains('\0') {
return Err(Error::InvalidProps(
"Markdown edit exceeds its source budget",
));
}
let mut output = String::with_capacity(length);
output.push_str(&source[..range.start]);
output.push_str(value);
output.push_str(&source[range.end..]);
Ok(Edit {
selection: selection(
&output,
range.start + selected.start,
range.start + selected.end,
),
value: output,
})
}
fn delimiter(value: &str, ch: char, minimum: usize) -> String {
let longest = value.split(|c| c != ch).map(str::len).max().unwrap_or(0);
ch.to_string().repeat(minimum.max(longest + 1))
}
fn wrap(source: &str, range: std::ops::Range<usize>, marker: &str) -> Result<Edit, Error> {
let start = range.start;
let end = range.end;
let active = |left: &str, right: &str| {
left.ends_with(marker)
&& right.starts_with(marker)
&& (marker != "*"
|| left.chars().rev().take_while(|ch| *ch == '*').count() % 2 == 1
&& right.chars().take_while(|ch| *ch == '*').count() % 2 == 1)
};
if active(&source[..start], &source[end..]) {
let content = &source[range.clone()];
return replace(
source,
start - marker.len()..end + marker.len(),
content,
0..content.len(),
);
}
let content = &source[range.clone()];
if content.len() >= marker.len() * 2 && active(content, content) {
let inner = &content[marker.len()..content.len() - marker.len()];
return replace(source, range, inner, 0..inner.len());
}
replace(
source,
range,
&format!("{marker}{content}{marker}"),
marker.len()..marker.len() + content.len(),
)
}
fn block_prefix(line: &str) -> usize {
let mut offset = line.len() - line.trim_start_matches([' ', '\t']).len();
while line[offset..].starts_with('>') {
offset += 1;
offset += line[offset..].len() - line[offset..].trim_start_matches([' ', '\t']).len();
}
offset
}
fn list_prefix(line: &str) -> Option<(usize, String)> {
let indent = block_prefix(line);
let body = &line[indent..];
let (mut end, mut next) = if starts(body, &["- ", "* ", "+ "]) {
(2, body[..2].to_owned())
} else {
let digits = body.bytes().take_while(u8::is_ascii_digit).count();
if digits == 0 || digits > 9 || !starts(&body[digits..], &[". ", ") "]) {
return None;
}
let number = body[..digits].parse::<u64>().ok()?;
(
digits + 2,
format!("{}{} ", number + 1, &body[digits..digits + 1]),
)
};
if starts(&body[end..], &["[ ] ", "[x] ", "[X] "]) {
end += 4;
next.push_str("[ ] ");
}
Some((indent + end, format!("{}{next}", &line[..indent])))
}
pub fn edit(source: &str, selected: TextSelection, command: &Command) -> Result<Edit, Error> {
if source.len() > MAX_MARKDOWN_BYTES || source.contains('\0') {
return Err(Error::InvalidProps("Markdown source exceeds its budget"));
}
let range = selected.byte_range(source)?;
let content = &source[range.clone()];
match command {
Command::Bold => return wrap(source, range, "**"),
Command::Italic => return wrap(source, range, "*"),
Command::Strikethrough => return wrap(source, range, "~~"),
Command::InlineCode => {
let marker = delimiter(content, '`', 1);
let pad = if content.starts_with('`')
|| content.ends_with('`')
|| content.starts_with(' ') && content.ends_with(' ')
{
" "
} else {
""
};
let value = format!("{marker}{pad}{content}{pad}{marker}");
let start = marker.len() + pad.len();
return replace(source, range, &value, start..start + content.len());
}
Command::Insert(value) => return replace(source, range, value, value.len()..value.len()),
Command::Link { destination } | Command::Image { destination } => {
if !safe_destination(destination) || destination.contains(['<', '>']) {
return Err(Error::InvalidProps(
"Markdown link requires a safe destination",
));
}
let label = content
.replace('\\', "\\\\")
.replace('[', "\\[")
.replace(']', "\\]");
let prefix = if matches!(command, Command::Image { .. }) {
"");
return replace(
source,
range,
&value,
prefix.len()..prefix.len() + label.len(),
);
}
Command::CodeBlock => {
let marker = delimiter(content, '`', 3);
let prefix = if range.start > 0 && !source[..range.start].ends_with('\n') {
"\n\n"
} else {
""
};
let suffix = if range.end < source.len() && !source[range.end..].starts_with('\n') {
"\n\n"
} else {
"\n"
};
let value = format!(
"{prefix}{marker}\n{content}{}{marker}{suffix}",
if content.ends_with('\n') { "" } else { "\n" }
);
let start = prefix.len() + marker.len() + 1;
return replace(source, range, &value, start..start + content.len());
}
Command::Table | Command::HorizontalRule => {
let body = if matches!(command, Command::Table) {
"| Column | Column |\n| --- | --- |\n| Value | Value |"
} else {
"---"
};
let prefix = if range.start > 0 && !source[..range.start].ends_with("\n\n") {
"\n\n"
} else {
""
};
let value = format!("{prefix}{body}\n\n");
return replace(source, range, &value, value.len()..value.len());
}
Command::ContinueLine => {
let start = source[..range.start].rfind('\n').map_or(0, |i| i + 1);
let line = &source[start..range.start];
let in_code =
pulldown_cmark::Parser::new(source)
.into_offset_iter()
.any(|(event, span)| {
matches!(
event,
pulldown_cmark::Event::Start(pulldown_cmark::Tag::CodeBlock(_))
) && span.start < range.start
&& span.end >= range.start
});
if !in_code && let Some((end, prefix)) = list_prefix(line) {
if line[end..].trim().is_empty() {
let prefix = &line[..block_prefix(line)];
return replace(source, start..range.end, prefix, prefix.len()..prefix.len());
}
let value = format!("\n{prefix}");
return replace(source, range, &value, value.len()..value.len());
}
let indent = &line[..line.len() - line.trim_start_matches([' ', '\t']).len()];
let prefix = if !in_code && line[indent.len()..].starts_with('>') {
line[..block_prefix(line)].to_owned()
} else {
indent.to_owned()
};
let value = format!("\n{prefix}");
return replace(source, range, &value, value.len()..value.len());
}
_ => {}
}
let first = source[..range.start].rfind('\n').map_or(0, |i| i + 1);
let last = if range.end > range.start && source[..range.end].ends_with('\n') {
range.end - 1
} else {
source[range.end..]
.find('\n')
.map_or(source.len(), |i| range.end + i)
};
let lines: Vec<&str> = source[first..last].split('\n').collect();
let marker = match command {
Command::Heading(level) if *level <= 6 => format!(
"{}{}",
"#".repeat(*level as usize),
if *level == 0 { "" } else { " " }
),
Command::Heading(_) => return Err(Error::InvalidProps("Markdown heading must be 0..=6")),
Command::Quote => "> ".into(),
Command::BulletList => "- ".into(),
Command::TaskList => "- [ ] ".into(),
_ => String::new(),
};
let prefix_len = |line: &str| {
if matches!(command, Command::Quote) {
line.len() - line.trim_start_matches([' ', '\t']).len()
} else {
block_prefix(line)
}
};
let toggle = lines.iter().all(|line| {
let body = &line[prefix_len(line)..];
match command {
Command::TaskList => starts(
body,
&[
"- [ ] ", "- [x] ", "- [X] ", "* [ ] ", "* [x] ", "+ [ ] ", "+ [x] ",
],
),
Command::OrderedList => {
body.starts_with(|ch: char| ch.is_ascii_digit()) && list_prefix(line).is_some()
}
_ => !marker.is_empty() && body.starts_with(&marker),
}
});
let value = lines
.iter()
.enumerate()
.map(|(index, line)| {
let indent = prefix_len(line);
let body = &line[indent..];
match command {
Command::Indent => format!(" {line}"),
Command::Outdent => line
.strip_prefix(" ")
.or_else(|| line.strip_prefix('\t'))
.or_else(|| line.strip_prefix(" "))
.unwrap_or(line)
.to_string(),
Command::Heading(_) => {
let hashes = body.bytes().take_while(|c| *c == b'#').count();
let body = if (1..=6).contains(&hashes) && body[hashes..].starts_with(' ') {
&body[hashes + 1..]
} else {
body
};
format!("{}{marker}{body}", &line[..indent])
}
Command::BulletList | Command::OrderedList | Command::TaskList => {
let body = list_prefix(line).map_or(body, |(end, _)| &line[end..]);
let prefix = if toggle {
String::new()
} else if matches!(command, Command::OrderedList) {
format!("{}. ", index + 1)
} else {
marker.clone()
};
format!("{}{prefix}{body}", &line[..indent])
}
_ => format!(
"{}{}{}",
&line[..indent],
if toggle { "" } else { &marker },
if toggle { &body[marker.len()..] } else { body }
),
}
})
.collect::<Vec<_>>()
.join("\n");
let caret = if selected.start == selected.end {
let delta = value.len() as isize - (last - first) as isize;
(range.start as isize - first as isize + delta).max(0) as usize
} else {
0
};
let end = if selected.start == selected.end {
caret.min(value.len())
} else {
value.len()
};
replace(source, first..last, &value, caret.min(value.len())..end)
}
#[cfg(test)]
mod tests {
use super::*;
fn all(value: &str) -> TextSelection {
TextSelection {
start: 0,
end: units(value),
..Default::default()
}
}
#[test]
fn unicode_selection_and_unknown_source_survive() {
let source = "ðŸ˜€ä¸æ–‡\n\n:::unknown \nraw\n:::\n";
let result = edit(
source,
TextSelection {
start: 2,
end: 4,
..Default::default()
},
&Command::Bold,
)
.unwrap();
assert_eq!(result.value, "😀**䏿–‡**\n\n:::unknown \nraw\n:::\n");
assert_eq!(result.selection.start, 4);
assert_eq!(
edit(&result.value, result.selection, &Command::Bold)
.unwrap()
.value,
source
);
assert!(
edit(
source,
TextSelection {
start: 1,
end: 2,
..Default::default()
},
&Command::Bold
)
.is_err()
);
}
#[test]
fn selected_lines_nested_tasks_and_continuation() {
let value = "alpha\n beta\ngamma";
assert_eq!(
edit(value, all(value), &Command::TaskList).unwrap().value,
"- [ ] alpha\n - [ ] beta\n- [ ] gamma"
);
let value = " 9. [x] done";
assert_eq!(
edit(
value,
TextSelection {
start: units(value),
end: units(value),
..Default::default()
},
&Command::ContinueLine
)
.unwrap()
.value,
" 9. [x] done\n 10. [ ] "
);
let value = "- [ ] ";
assert_eq!(
edit(
value,
TextSelection {
start: units(value),
end: units(value),
..Default::default()
},
&Command::ContinueLine
)
.unwrap()
.value,
""
);
}
#[test]
fn code_fences_and_inline_delimiters_do_not_break_content() {
assert_eq!(
edit("a`b", all("a`b"), &Command::InlineCode).unwrap().value,
"``a`b``"
);
assert_eq!(
edit("```\ncode", all("```\ncode"), &Command::CodeBlock)
.unwrap()
.value,
"````\n```\ncode\n````\n"
);
}
#[test]
fn dangerous_links_and_budgets_reject_atomically() {
for url in [
"javascript:alert(1)",
"DATA:text/html,x",
"//tracker.test/x",
"a\\b",
"java\nscript:x",
] {
assert!(!safe_destination(url), "{url}");
}
for url in [
"https://example.com",
"mailto:a@example.com",
"#heading",
"/attachments/a",
"../image.png",
] {
assert!(safe_destination(url), "{url}");
}
assert!(
edit(
"safe",
all("safe"),
&Command::Link {
destination: "javascript:x".into()
}
)
.is_err()
);
assert!(
edit(
&"a".repeat(MAX_MARKDOWN_BYTES),
TextSelection::default(),
&Command::Bold
)
.is_err()
);
}
#[test]
fn end_at_next_line_does_not_format_that_line() {
assert_eq!(
edit(
"one\ntwo",
TextSelection {
start: 0,
end: 4,
..Default::default()
},
&Command::BulletList
)
.unwrap()
.value,
"- one\ntwo"
);
}
#[test]
fn nested_quotes_lists_and_emphasis_keep_the_other_structure() {
let source = "> - [x] done";
let end = units(source);
assert_eq!(
edit(
source,
TextSelection {
start: end,
end,
..Default::default()
},
&Command::ContinueLine
)
.unwrap()
.value,
"> - [x] done\n> - [ ] "
);
assert_eq!(
edit(source, all(source), &Command::TaskList).unwrap().value,
"> done"
);
assert_eq!(
edit("> ## Title", all("> ## Title"), &Command::Heading(1))
.unwrap()
.value,
"> # Title"
);
assert_eq!(
edit(
"**word**",
TextSelection {
start: 2,
end: 6,
..Default::default()
},
&Command::Italic
)
.unwrap()
.value,
"***word***"
);
assert_eq!(
edit("**word**", all("**word**"), &Command::Italic)
.unwrap()
.value,
"***word***"
);
let code = "```\n- literal";
let end = units(code);
assert_eq!(
edit(
code,
TextSelection {
start: end,
end,
..Default::default()
},
&Command::ContinueLine
)
.unwrap()
.value,
"```\n- literal\n"
);
}
}