Remove leading blank lines from document contents.

This commit is contained in:
Tom Alexander 2023-12-15 15:30:46 -05:00
parent 45a506334c
commit fce5b92091
Signed by: talexander
GPG Key ID: D3A179C9A53C0EDE
2 changed files with 9 additions and 23 deletions

View File

@ -181,8 +181,10 @@ fn _document<'b, 'g, 'r, 's>(
let zeroth_section_matcher = parser_with_context!(zeroth_section)(context);
let heading_matcher = parser_with_context!(heading(0))(context);
let (remaining, _blank_lines) = many0(blank_line)(input)?;
let contents_begin = remaining;
let (remaining, zeroth_section) = opt(zeroth_section_matcher)(remaining)?;
let (remaining, children) = many0(heading_matcher)(remaining)?;
let contents = get_consumed(contents_begin, remaining);
let source = get_consumed(input, remaining);
Ok((
remaining,
@ -192,6 +194,11 @@ fn _document<'b, 'g, 'r, 's>(
path: None,
zeroth_section,
children,
contents: if contents.len() > 0 {
Some(Into::<&str>::into(contents))
} else {
None
},
},
))
}

View File

@ -1,6 +1,5 @@
use std::path::PathBuf;
use super::remove_trailing::RemoveTrailing;
use super::Element;
use super::NodeProperty;
use super::Object;
@ -18,6 +17,7 @@ pub struct Document<'s> {
pub path: Option<PathBuf>,
pub zeroth_section: Option<Section<'s>>,
pub children: Vec<Heading<'s>>,
pub contents: Option<&'s str>,
}
#[derive(Debug)]
@ -63,28 +63,7 @@ impl<'s> StandardProperties<'s> for Document<'s> {
}
fn get_contents<'b>(&'b self) -> Option<&'s str> {
let post_blank = self.get_post_blank();
let mut content_lines = self
.source
.split_inclusive('\n')
.remove_trailing(post_blank);
let first_line = content_lines.next();
let last_line = content_lines.last().or(first_line);
match (first_line, last_line) {
(None, None) => None,
(None, Some(_)) | (Some(_), None) => unreachable!(),
(Some(first_line), Some(last_line)) => {
let first_line_offset = first_line.as_ptr() as usize;
let last_line_offset = last_line.as_ptr() as usize + last_line.len();
let source_offset = self.source.as_ptr() as usize;
debug_assert!(super::lesser_element::is_slice_of(self.source, first_line));
debug_assert!(super::lesser_element::is_slice_of(self.source, last_line));
Some(
&self.source[(first_line_offset - source_offset)
..(last_line_offset - first_line_offset)],
)
}
}
self.contents
}
fn get_post_blank(&self) -> PostBlank {