Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add contents_formatted to InMemoryTerm #531

Merged
merged 1 commit into from
May 26, 2023
Merged
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
39 changes: 39 additions & 0 deletions src/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,45 @@ impl InMemoryTerm {
rows.reverse();
rows.join("\n")
}

pub fn contents_formatted(&self) -> Vec<u8> {
let state = self.state.lock().unwrap();

// For some reason, the `Screen::contents` method doesn't include newlines in what it
// returns, making it useless for our purposes. So we need to manually reconstruct the
// contents by iterating over the rows in the terminal buffer.
let mut rows = state
.parser
.screen()
.rows_formatted(0, state.width)
.collect::<Vec<_>>();

// Reverse the rows and trim empty lines from the end
rows = rows
.into_iter()
.rev()
.skip_while(|line| line.is_empty())
.collect();

// Un-reverse the rows
rows.reverse();

// Calculate buffer size
let reset = b"";
let len = rows.iter().map(|line| line.len() + reset.len() + 1).sum();

// Join rows up with reset codes and newlines
let mut contents = rows.iter().fold(Vec::with_capacity(len), |mut acc, cur| {
acc.extend_from_slice(cur);
acc.extend_from_slice(reset);
acc.push(b'\n');
acc
});

// Remove last newline again, but leave the reset code
contents.truncate(len.saturating_sub(1));
contents
}
}

impl TermLike for InMemoryTerm {
Expand Down