Skip to content

Commit

Permalink
fix(ast): preserve newline structure at end of gemtext
Browse files Browse the repository at this point in the history
  • Loading branch information
Fuwn committed Jun 19, 2024
1 parent 7f70215 commit fd63acb
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
18 changes: 15 additions & 3 deletions src/ast/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,14 @@ impl Ast {
));
}

if source.chars().last().map_or(false, |c| c == '\n') {
if let Some(last) = ast.last() {
if !matches!(last, Node::Whitespace) {
ast.push(Node::Whitespace);
}
}
}

Self { inner: ast }
}

Expand All @@ -95,10 +103,10 @@ impl Ast {
/// // the original Gemtext.
/// assert_eq!(
/// germ::ast::Ast::from_nodes(
/// germ::gemini_to_ast!("=> / Home\n").inner().to_vec()
/// germ::gemini_to_ast!("=> / Home").inner().to_vec()
/// )
/// .to_gemtext(),
/// "=> / Home\n"
/// "=> / Home"
/// );
/// ```
#[must_use]
Expand Down Expand Up @@ -145,6 +153,10 @@ impl Ast {
}
}

if gemtext.ends_with('\n') && !gemtext.ends_with("\n\n") {
gemtext.pop();
}

gemtext
}

Expand Down Expand Up @@ -279,7 +291,7 @@ impl Ast {

break;
}
// This as a catchall, it does a number of things.
// This as a catchall. It does a number of things.
_ => {
if *in_preformatted {
// If we are in a preformatted line context, add the line to the
Expand Down
2 changes: 1 addition & 1 deletion src/ast/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
/// germ::gemini_to_ast!("=> / A link!").to_gemtext(),
/// // `to_gemtext` appends a newline to all responses, so let's make sure we
/// // account for that.
/// format!("{}\n", "=> / A link!"),
/// "=> / A link!",
/// );
#[macro_export]
macro_rules! gemini_to_ast {
Expand Down
8 changes: 4 additions & 4 deletions tests/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ That was a link without text."#;
Ast::from_string(EXAMPLE_GEMTEXT).to_gemtext(),
// `to_gemtext` appends a newline to all responses, so let's make sure we
// account for that.
format!("{}\n", EXAMPLE_GEMTEXT),
EXAMPLE_GEMTEXT
);
}

Expand All @@ -98,16 +98,16 @@ That was a link without text."#;
germ::gemini_to_ast!(EXAMPLE_GEMTEXT).to_gemtext(),
// `to_gemtext` appends a newline to all responses, so let's make sure we
// account for that.
format!("{}\n", EXAMPLE_GEMTEXT),
EXAMPLE_GEMTEXT
);
}

#[test]
fn gemtext_to_ast_then_node_to_ast_to_gemtext() {
assert_eq!(
Ast::from_nodes(germ::gemini_to_ast!("=> / Home\n").inner().to_vec())
Ast::from_nodes(germ::gemini_to_ast!("=> / Home").inner().to_vec())
.to_gemtext(),
"=> / Home\n"
"=> / Home"
);
}
}

0 comments on commit fd63acb

Please sign in to comment.