Skip to content
Closed
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
116 changes: 116 additions & 0 deletions crates/edit/src/bin/edit/documents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use edit::lsh::{FILE_ASSOCIATIONS, Language, process_file_associations};
use edit::{path, sys};

use crate::apperr;
use crate::markdown_preview::MarkdownPreview;
use crate::settings::Settings;
use crate::state::DisplayablePathBuf;

Expand All @@ -23,9 +24,18 @@ pub struct Document {
pub file_id: Option<sys::FileId>,
pub new_file_counter: usize,
pub language_override: Option<Option<&'static Language>>,
pub markdown_preview: MarkdownPreview,
}

impl Document {
pub fn is_markdown(&self) -> bool {
self.buffer.borrow().language().is_some_and(|language| language.id == "markdown")
}

pub fn markdown_preview_enabled(&self) -> bool {
self.is_markdown() && self.markdown_preview.is_enabled()
}

pub fn save(&mut self, new_path: Option<PathBuf>) -> apperr::Result<()> {
let path = new_path.as_deref().unwrap_or_else(|| self.path.as_ref().unwrap().as_path());
let mut file = DocumentManager::open_for_writing(path)?;
Expand Down Expand Up @@ -171,11 +181,15 @@ impl DocumentManager {
std::ptr::copy_nonoverlapping(temp.as_ptr(), last, 1);
}

self.list.last_mut().unwrap().markdown_preview.active_document_changed();
true
}

pub fn remove_active(&mut self) {
self.list.pop();
if let Some(document) = self.list.last_mut() {
document.markdown_preview.active_document_changed();
}
}

pub fn add_untitled(&mut self) -> apperr::Result<&mut Document> {
Expand All @@ -188,6 +202,7 @@ impl DocumentManager {
file_id: None,
new_file_counter: 0,
language_override: None,
markdown_preview: Default::default(),
};
self.gen_untitled_name(&mut doc);

Expand Down Expand Up @@ -240,6 +255,7 @@ impl DocumentManager {
file_id,
new_file_counter: 0,
language_override: None,
markdown_preview: Default::default(),
};
doc.set_path(path);

Expand Down Expand Up @@ -358,6 +374,106 @@ pub fn parse_filename_goto(path: &Path) -> (&Path, Option<Point>) {
#[cfg(test)]
mod tests {
use super::*;
use edit::lsh::LANGUAGES;

fn markdown_document(filename: &str, source: &str) -> Document {
let buffer = TextBuffer::new_rc(false).unwrap();
{
let mut tb = buffer.borrow_mut();
tb.write_raw(source.as_bytes());
let language = LANGUAGES.iter().find(|language| language.id == "markdown").unwrap();
tb.set_language(Some(language));
}

Document {
buffer,
path: None,
dir: None,
filename: filename.to_string(),
file_id: None,
new_file_counter: 0,
language_override: None,
markdown_preview: Default::default(),
}
}

fn preview_text(document: &Document) -> String {
document
.markdown_preview
.lines()
.iter()
.flat_map(|line| line.spans.iter())
.map(|span| span.text.as_str())
.collect()
}

#[test]
fn documents_keep_independent_preview_state_and_cache() {
let mut documents = DocumentManager::default();
documents.list.push(markdown_document("first.md", "# First"));
documents.list.push(markdown_document("second.md", "# Second"));

{
let second = documents.active_mut().unwrap();
second.markdown_preview.set_enabled(true);
second.markdown_preview.prepare(&second.buffer, 80);
}
assert!(documents.update_active(|document| document.filename == "first.md"));
{
let first = documents.active_mut().unwrap();
first.markdown_preview.set_enabled(true);
first.markdown_preview.prepare(&first.buffer, 80);
}
assert!(documents.update_active(|document| document.filename == "second.md"));
documents.active_mut().unwrap().markdown_preview.set_enabled(false);

assert!(documents.update_active(|document| document.filename == "first.md"));
let first = documents.active().unwrap();
assert!(first.markdown_preview_enabled());
assert_eq!(preview_text(first), "First");

assert!(documents.update_active(|document| document.filename == "second.md"));
let second = documents.active().unwrap();
assert!(!second.markdown_preview_enabled());
assert_eq!(preview_text(second), "Second");
}

#[test]
fn switching_documents_requests_independent_preview_scroll_resets() {
let mut documents = DocumentManager::default();
documents.list.push(markdown_document("first.md", "# First"));
documents.list.push(markdown_document("second.md", "# Second"));

{
let second = documents.active_mut().unwrap();
second.markdown_preview.set_enabled(true);
second.markdown_preview.prepare(&second.buffer, 80);
assert!(second.markdown_preview.take_scroll_reset());
}

assert!(documents.update_active(|document| document.filename == "first.md"));
{
let first = documents.active_mut().unwrap();
first.markdown_preview.set_enabled(true);
first.markdown_preview.prepare(&first.buffer, 80);
assert!(first.markdown_preview.take_scroll_reset());
}

assert!(documents.update_active(|document| document.filename == "second.md"));
assert!(documents.active_mut().unwrap().markdown_preview.take_scroll_reset());

assert!(documents.update_active(|document| document.filename == "first.md"));
assert!(documents.active_mut().unwrap().markdown_preview.take_scroll_reset());
}

#[test]
fn non_markdown_document_never_exposes_preview() {
let mut document = markdown_document("notes.txt", "plain text");
document.buffer.borrow_mut().set_language(None);
document.markdown_preview.set_enabled(true);

assert!(!document.markdown_preview_enabled());
}

#[test]
fn test_parse_last_numbers() {
Expand Down
15 changes: 13 additions & 2 deletions crates/edit/src/bin/edit/draw_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use edit::input::{kbmod, vk};
use edit::tui::*;
use stdext::string_from_utf8_lossy_owned;

use crate::draw_markdown_preview::draw_markdown_preview;
use crate::localization::*;
use crate::state::*;

Expand All @@ -24,8 +25,18 @@ pub fn draw_editor(ctx: &mut Context, state: &mut State) {
_ => 2,
};

if let Some(doc) = state.documents.active() {
ctx.textarea("textarea", doc.buffer.clone());
if let Some(document) = state.documents.active_mut() {
let buffer = document.buffer.clone();
if document.markdown_preview_enabled() {
draw_markdown_preview(
ctx,
&buffer,
&mut document.markdown_preview,
size.height - height_reduction,
);
} else {
ctx.textarea("textarea", buffer);
}
ctx.inherit_focus();
} else {
ctx.block_begin("empty");
Expand Down
86 changes: 86 additions & 0 deletions crates/edit/src/bin/edit/draw_markdown_preview.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use edit::buffer::RcTextBuffer;
use edit::framebuffer::{Attributes, IndexedColor};
use edit::helpers::*;
use edit::tui::*;

use crate::markdown_preview::{InlineStyle, MarkdownPreview, RenderedLineKind};

pub fn draw_markdown_preview(
ctx: &mut Context,
buffer: &RcTextBuffer,
preview: &mut MarkdownPreview,
height: CoordType,
) {
let width = (ctx.size().width - 3).max(2);
preview.prepare(buffer, width);
let reset_scroll = preview.take_scroll_reset();

ctx.scrollarea_begin("markdown-preview", Size { width: 0, height });
ctx.focus_on_first_present();
ctx.attr_padding(Rect::two(0, 1));
if reset_scroll {
ctx.scrollarea_scroll_to(Point::default());
}
{
for (index, line) in preview.lines().iter().enumerate() {
ctx.next_block_id_mixin(index as u64);
ctx.styled_label_begin("line");

let mut style = None;
for span in &line.spans {
if style != Some(span.style) {
style = Some(span.style);
ctx.styled_label_set_attributes(attributes(span.style));
}
ctx.styled_label_add_text(&span.text);
}

ctx.styled_label_end();

match line.kind {
RenderedLineKind::Text => {}
RenderedLineKind::Heading(level) => {
let color =
if level <= 2 { IndexedColor::BrightCyan } else { IndexedColor::Cyan };
ctx.attr_foreground_rgba(ctx.indexed(color));
}
RenderedLineKind::Quote => {
ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightGreen));
}
RenderedLineKind::Rule => {
ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightBlack));
}
RenderedLineKind::Code => {
ctx.attr_background_rgba(ctx.indexed_alpha(IndexedColor::Black, 1, 4));
ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightYellow));
}
RenderedLineKind::Unavailable => {
ctx.attr_foreground_rgba(ctx.indexed(IndexedColor::BrightYellow));
}
}
}
}
ctx.scrollarea_end();
}

fn attributes(style: InlineStyle) -> Attributes {
let mut attributes = Attributes::None;

if style.is_bold() {
attributes = attributes | Attributes::Bold;
}
if style.is_italic() || style.is_code() {
attributes = attributes | Attributes::Italic;
}
if style.is_strikethrough() {
attributes = attributes | Attributes::Strikethrough;
}
if style.is_link() || style.is_code() {
attributes = attributes | Attributes::Underlined;
}

attributes
}
21 changes: 17 additions & 4 deletions crates/edit/src/bin/edit/draw_menubar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub fn draw_menubar(ctx: &mut Context, state: &mut State) {
ctx.steal_focus();
}
if state.documents.active().is_some() {
if ctx.menubar_menu_begin(loc(LocId::Edit), 'E') {
if !state.markdown_preview_enabled() && ctx.menubar_menu_begin(loc(LocId::Edit), 'E') {
draw_menu_edit(ctx, state);
}
if ctx.menubar_menu_begin(loc(LocId::View), 'V') {
Expand Down Expand Up @@ -122,10 +122,18 @@ fn draw_menu_edit(ctx: &mut Context, state: &mut State) {
}

fn draw_menu_view(ctx: &mut Context, state: &mut State) {
if let Some(doc) = state.documents.active() {
let mut tb = doc.buffer.borrow_mut();
let word_wrap = tb.is_word_wrap_enabled();
if state.markdown_preview_available()
&& ctx.menubar_menu_checkbox(
loc(LocId::ViewMarkdownPreview),
'P',
kbmod::ALT | vk::P,
state.markdown_preview_enabled(),
)
{
state.toggle_markdown_preview();
}

if state.documents.active().is_some() {
// All values on the statusbar are currently document specific.
if ctx.menubar_menu_button(loc(LocId::ViewFocusStatusbar), 'S', vk::NULL) {
state.wants_statusbar_focus = true;
Expand All @@ -134,8 +142,13 @@ fn draw_menu_view(ctx: &mut Context, state: &mut State) {
state.wants_go_to_file = true;
}
if ctx.menubar_menu_button(loc(LocId::FileGoto), 'G', kbmod::CTRL | vk::G) {
state.disable_markdown_preview();
state.wants_goto = true;
}

let doc = state.documents.active().unwrap();
let mut tb = doc.buffer.borrow_mut();
let word_wrap = tb.is_word_wrap_enabled();
if ctx.menubar_menu_checkbox(loc(LocId::ViewWordWrap), 'W', kbmod::ALT | vk::Z, word_wrap) {
tb.set_word_wrap(!word_wrap);
ctx.needs_rerender();
Expand Down
8 changes: 8 additions & 0 deletions crates/edit/src/bin/edit/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ mod apperr;
mod documents;
mod draw_editor;
mod draw_filepicker;
mod draw_markdown_preview;
mod draw_menubar;
mod draw_statusbar;
mod localization;
mod markdown_preview;
mod settings;
mod state;

Expand Down Expand Up @@ -386,23 +388,29 @@ fn draw(ctx: &mut Context, state: &mut State) {
state.wants_save = true;
} else if key == kbmod::CTRL_SHIFT | vk::S {
state.wants_file_picker = StateFilePicker::SaveAs;
} else if key == kbmod::ALT | vk::P {
state.toggle_markdown_preview();
} else if key == kbmod::CTRL | vk::W {
state.wants_close = true;
} else if key == kbmod::CTRL | vk::P {
state.wants_go_to_file = true;
} else if key == kbmod::CTRL | vk::Q {
state.wants_exit = true;
} else if key == kbmod::CTRL | vk::G {
state.disable_markdown_preview();
state.wants_goto = true;
} else if key == kbmod::CTRL | vk::F && state.wants_search.kind != StateSearchKind::Disabled
{
state.disable_markdown_preview();
state.wants_search.kind = StateSearchKind::Search;
state.wants_search.focus = true;
} else if key == kbmod::CTRL | vk::R && state.wants_search.kind != StateSearchKind::Disabled
{
state.disable_markdown_preview();
state.wants_search.kind = StateSearchKind::Replace;
state.wants_search.focus = true;
} else if key == vk::F3 {
state.disable_markdown_preview();
search_execute(ctx, state, SearchAction::Search);
} else {
return;
Expand Down
Loading