Merge branch 'main' into gpui-events

Mikayla Maki created

Change summary

Cargo.lock                                          |   2 
assets/settings/default.json                        |  20 
crates/activity_indicator/src/activity_indicator.rs |   6 
crates/editor/src/display_map/block_map.rs          |   1 
crates/editor/src/display_map/fold_map.rs           |   1 
crates/editor/src/display_map/wrap_map.rs           |   1 
crates/editor/src/element.rs                        | 308 ++++++++------
crates/editor/src/multi_buffer.rs                   |   1 
crates/git/src/diff.rs                              |   3 
crates/journal/Cargo.toml                           |   2 
crates/journal/src/journal.rs                       |  87 +++
crates/settings/src/settings.rs                     |  37 +
crates/terminal/src/terminal.rs                     |  76 +--
13 files changed, 345 insertions(+), 200 deletions(-)

Detailed changes

Cargo.lock 🔗

@@ -2946,6 +2946,8 @@ dependencies = [
  "editor",
  "gpui",
  "log",
+ "settings",
+ "shellexpand",
  "util",
  "workspace",
 ]

assets/settings/default.json 🔗

@@ -83,9 +83,19 @@
         //      "git_gutter": "hide"
         "git_gutter": "tracked_files"
     },
+    // Settings specific to journaling
+    "journal": {
+        // The path of the directory where journal entries are stored
+        "path": "~",
+        // What format to display the hours in
+        // May take 2 values:
+        // 1. hour12
+        // 2. hour24
+        "hour_format": "hour12"
+    },
     // Settings specific to the terminal
     "terminal": {
-        // What shell to use when opening a terminal. May take 3 values: 
+        // What shell to use when opening a terminal. May take 3 values:
         // 1. Use the system's default terminal configuration (e.g. $TERM).
         //      "shell": "system"
         // 2. A program:
@@ -102,7 +112,7 @@
         "shell": "system",
         // What working directory to use when launching the terminal.
         // May take 4 values:
-        // 1. Use the current file's project directory.  Will Fallback to the 
+        // 1. Use the current file's project directory.  Will Fallback to the
         //    first project directory strategy if unsuccessful
         //      "working_directory": "current_project_directory"
         // 2. Use the first project in this workspace's directory
@@ -112,7 +122,7 @@
         // 4. Always use a specific directory. This value will be shell expanded.
         //    If this path is not a valid directory the terminal will default to
         //    this platform's home directory  (if we can find it)
-        //      "working_directory": { 
+        //      "working_directory": {
         //        "always": {
         //          "directory": "~/zed/projects/"
         //        }
@@ -124,7 +134,7 @@
         // May take 4 values:
         //  1. Never blink the cursor, ignoring the terminal mode
         //         "blinking": "off",
-        //  2. Default the cursor blink to off, but allow the terminal to 
+        //  2. Default the cursor blink to off, but allow the terminal to
         //     set blinking
         //         "blinking": "terminal_controlled",
         //  3. Always blink the cursor, ignoring the terminal mode
@@ -132,7 +142,7 @@
         "blinking": "terminal_controlled",
         // Set whether Alternate Scroll mode (code: ?1007) is active by default.
         // Alternate Scroll mode converts mouse scroll events into up / down key
-        // presses when in the alternate screen (e.g. when running applications 
+        // presses when in the alternate screen (e.g. when running applications
         // like vim or  less). The terminal can still set and unset this mode.
         // May take 2 values:
         //  1. Default alternate scroll mode to on

crates/activity_indicator/src/activity_indicator.rs 🔗

@@ -46,6 +46,7 @@ impl ActivityIndicator {
         cx: &mut ViewContext<Workspace>,
     ) -> ViewHandle<ActivityIndicator> {
         let project = workspace.project().clone();
+        let auto_updater = AutoUpdater::get(cx);
         let this = cx.add_view(|cx: &mut ViewContext<Self>| {
             let mut status_events = languages.language_server_binary_statuses();
             cx.spawn_weak(|this, mut cx| async move {
@@ -66,11 +67,14 @@ impl ActivityIndicator {
             })
             .detach();
             cx.observe(&project, |_, _, cx| cx.notify()).detach();
+            if let Some(auto_updater) = auto_updater.as_ref() {
+                cx.observe(auto_updater, |_, _, cx| cx.notify()).detach();
+            }
 
             Self {
                 statuses: Default::default(),
                 project: project.clone(),
-                auto_updater: AutoUpdater::get(cx),
+                auto_updater,
             }
         });
         cx.subscribe(&this, move |workspace, _, event, cx| match event {

crates/editor/src/display_map/block_map.rs 🔗

@@ -157,6 +157,7 @@ pub struct BlockChunks<'a> {
     max_output_row: u32,
 }
 
+#[derive(Clone)]
 pub struct BlockBufferRows<'a> {
     transforms: sum_tree::Cursor<'a, Transform, (BlockRow, WrapRow)>,
     input_buffer_rows: wrap_map::WrapBufferRows<'a>,

crates/editor/src/display_map/fold_map.rs 🔗

@@ -987,6 +987,7 @@ impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
     }
 }
 
+#[derive(Clone)]
 pub struct FoldBufferRows<'a> {
     cursor: Cursor<'a, Transform, (FoldPoint, Point)>,
     input_buffer_rows: MultiBufferRows<'a>,

crates/editor/src/display_map/wrap_map.rs 🔗

@@ -62,6 +62,7 @@ pub struct WrapChunks<'a> {
     transforms: Cursor<'a, Transform, (WrapPoint, TabPoint)>,
 }
 
+#[derive(Clone)]
 pub struct WrapBufferRows<'a> {
     input_buffer_rows: fold_map::FoldBufferRows<'a>,
     input_buffer_row: Option<u32>,

crates/editor/src/element.rs 🔗

@@ -12,11 +12,11 @@ use crate::{
         GoToFetchedDefinition, GoToFetchedTypeDefinition, UpdateGoToDefinitionLink,
     },
     mouse_context_menu::DeployMouseContextMenu,
-    EditorStyle,
+    AnchorRangeExt, EditorStyle,
 };
 use clock::ReplicaId;
 use collections::{BTreeMap, HashMap};
-use git::diff::{DiffHunk, DiffHunkStatus};
+use git::diff::DiffHunkStatus;
 use gpui::{
     color::Color,
     elements::*,
@@ -34,7 +34,7 @@ use gpui::{
     Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle,
 };
 use json::json;
-use language::{Bias, DiagnosticSeverity, OffsetUtf16, Selection};
+use language::{Bias, DiagnosticSeverity, OffsetUtf16, Point, Selection};
 use project::ProjectPath;
 use settings::{GitGutter, Settings};
 use smallvec::SmallVec;
@@ -45,7 +45,13 @@ use std::{
     ops::{DerefMut, Range},
     sync::Arc,
 };
-use theme::DiffStyle;
+
+#[derive(Debug)]
+struct DiffHunkLayout {
+    visual_range: Range<u32>,
+    status: DiffHunkStatus,
+    is_folded: bool,
+}
 
 struct SelectionLayout {
     head: DisplayPoint,
@@ -516,85 +522,11 @@ impl EditorElement {
         layout: &mut LayoutState,
         cx: &mut PaintContext,
     ) {
-        struct GutterLayout {
-            line_height: f32,
-            // scroll_position: Vector2F,
-            scroll_top: f32,
-            bounds: RectF,
-        }
-
-        struct DiffLayout<'a> {
-            buffer_row: u32,
-            last_diff: Option<&'a DiffHunk<u32>>,
-        }
-
-        fn diff_quad(
-            hunk: &DiffHunk<u32>,
-            gutter_layout: &GutterLayout,
-            diff_style: &DiffStyle,
-        ) -> Quad {
-            let color = match hunk.status() {
-                DiffHunkStatus::Added => diff_style.inserted,
-                DiffHunkStatus::Modified => diff_style.modified,
-
-                //TODO: This rendering is entirely a horrible hack
-                DiffHunkStatus::Removed => {
-                    let row = hunk.buffer_range.start;
-
-                    let offset = gutter_layout.line_height / 2.;
-                    let start_y =
-                        row as f32 * gutter_layout.line_height + offset - gutter_layout.scroll_top;
-                    let end_y = start_y + gutter_layout.line_height;
-
-                    let width = diff_style.removed_width_em * gutter_layout.line_height;
-                    let highlight_origin = gutter_layout.bounds.origin() + vec2f(-width, start_y);
-                    let highlight_size = vec2f(width * 2., end_y - start_y);
-                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
-
-                    return Quad {
-                        bounds: highlight_bounds,
-                        background: Some(diff_style.deleted),
-                        border: Border::new(0., Color::transparent_black()),
-                        corner_radius: 1. * gutter_layout.line_height,
-                    };
-                }
-            };
-
-            let start_row = hunk.buffer_range.start;
-            let end_row = hunk.buffer_range.end;
-
-            let start_y = start_row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
-            let end_y = end_row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
-
-            let width = diff_style.width_em * gutter_layout.line_height;
-            let highlight_origin = gutter_layout.bounds.origin() + vec2f(-width, start_y);
-            let highlight_size = vec2f(width * 2., end_y - start_y);
-            let highlight_bounds = RectF::new(highlight_origin, highlight_size);
-
-            Quad {
-                bounds: highlight_bounds,
-                background: Some(color),
-                border: Border::new(0., Color::transparent_black()),
-                corner_radius: diff_style.corner_radius * gutter_layout.line_height,
-            }
-        }
+        let line_height = layout.position_map.line_height;
 
         let scroll_position = layout.position_map.snapshot.scroll_position();
-        let gutter_layout = {
-            let line_height = layout.position_map.line_height;
-            GutterLayout {
-                scroll_top: scroll_position.y() * line_height,
-                line_height,
-                bounds,
-            }
-        };
-
-        let mut diff_layout = DiffLayout {
-            buffer_row: scroll_position.y() as u32,
-            last_diff: None,
-        };
+        let scroll_top = scroll_position.y() * line_height;
 
-        let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
         let show_gutter = matches!(
             &cx.global::<Settings>()
                 .git_overrides
@@ -603,55 +535,104 @@ impl EditorElement {
             GitGutter::TrackedFiles
         );
 
-        // line is `None` when there's a line wrap
+        if show_gutter {
+            Self::paint_diff_hunks(bounds, layout, cx);
+        }
+
         for (ix, line) in layout.line_number_layouts.iter().enumerate() {
             if let Some(line) = line {
                 let line_origin = bounds.origin()
                     + vec2f(
                         bounds.width() - line.width() - layout.gutter_padding,
-                        ix as f32 * gutter_layout.line_height
-                            - (gutter_layout.scroll_top % gutter_layout.line_height),
+                        ix as f32 * line_height - (scroll_top % line_height),
                     );
 
-                line.paint(line_origin, visible_bounds, gutter_layout.line_height, cx);
+                line.paint(line_origin, visible_bounds, line_height, cx);
+            }
+        }
+
+        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
+            let mut x = bounds.width() - layout.gutter_padding;
+            let mut y = *row as f32 * line_height - scroll_top;
+            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
+            y += (line_height - indicator.size().y()) / 2.;
+            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
+        }
+    }
+
+    fn paint_diff_hunks(bounds: RectF, layout: &mut LayoutState, cx: &mut PaintContext) {
+        let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
+        let line_height = layout.position_map.line_height;
+
+        let scroll_position = layout.position_map.snapshot.scroll_position();
+        let scroll_top = scroll_position.y() * line_height;
 
-                if show_gutter {
-                    //This line starts a buffer line, so let's do the diff calculation
-                    let new_hunk = get_hunk(diff_layout.buffer_row, &layout.diff_hunks);
+        for hunk in &layout.hunk_layouts {
+            let color = match (hunk.status, hunk.is_folded) {
+                (DiffHunkStatus::Added, false) => diff_style.inserted,
+                (DiffHunkStatus::Modified, false) => diff_style.modified,
 
-                    let (is_ending, is_starting) = match (diff_layout.last_diff, new_hunk) {
-                        (Some(old_hunk), Some(new_hunk)) if new_hunk == old_hunk => (false, false),
-                        (a, b) => (a.is_some(), b.is_some()),
-                    };
+                //TODO: This rendering is entirely a horrible hack
+                (DiffHunkStatus::Removed, false) => {
+                    let row = hunk.visual_range.start;
 
-                    if is_ending {
-                        let last_hunk = diff_layout.last_diff.take().unwrap();
-                        cx.scene
-                            .push_quad(diff_quad(last_hunk, &gutter_layout, diff_style));
-                    }
+                    let offset = line_height / 2.;
+                    let start_y = row as f32 * line_height - offset - scroll_top;
+                    let end_y = start_y + line_height;
+
+                    let width = diff_style.removed_width_em * line_height;
+                    let highlight_origin = bounds.origin() + vec2f(-width, start_y);
+                    let highlight_size = vec2f(width * 2., end_y - start_y);
+                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
+
+                    cx.scene.push_quad(Quad {
+                        bounds: highlight_bounds,
+                        background: Some(diff_style.deleted),
+                        border: Border::new(0., Color::transparent_black()),
+                        corner_radius: 1. * line_height,
+                    });
+
+                    continue;
+                }
+
+                (_, true) => {
+                    let row = hunk.visual_range.start;
+                    let start_y = row as f32 * line_height - scroll_top;
+                    let end_y = start_y + line_height;
 
-                    if is_starting {
-                        let new_hunk = new_hunk.unwrap();
-                        diff_layout.last_diff = Some(new_hunk);
-                    };
+                    let width = diff_style.removed_width_em * line_height;
+                    let highlight_origin = bounds.origin() + vec2f(-width, start_y);
+                    let highlight_size = vec2f(width * 2., end_y - start_y);
+                    let highlight_bounds = RectF::new(highlight_origin, highlight_size);
 
-                    diff_layout.buffer_row += 1;
+                    cx.scene.push_quad(Quad {
+                        bounds: highlight_bounds,
+                        background: Some(diff_style.modified),
+                        border: Border::new(0., Color::transparent_black()),
+                        corner_radius: 1. * line_height,
+                    });
+
+                    continue;
                 }
-            }
-        }
+            };
 
-        // If we ran out with a diff hunk still being prepped, paint it now
-        if let Some(last_hunk) = diff_layout.last_diff {
-            cx.scene
-                .push_quad(diff_quad(last_hunk, &gutter_layout, diff_style))
-        }
+            let start_row = hunk.visual_range.start;
+            let end_row = hunk.visual_range.end;
 
-        if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
-            let mut x = bounds.width() - layout.gutter_padding;
-            let mut y = *row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
-            x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
-            y += (gutter_layout.line_height - indicator.size().y()) / 2.;
-            indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
+            let start_y = start_row as f32 * line_height - scroll_top;
+            let end_y = end_row as f32 * line_height - scroll_top;
+
+            let width = diff_style.width_em * line_height;
+            let highlight_origin = bounds.origin() + vec2f(-width, start_y);
+            let highlight_size = vec2f(width * 2., end_y - start_y);
+            let highlight_bounds = RectF::new(highlight_origin, highlight_size);
+
+            cx.scene.push_quad(Quad {
+                bounds: highlight_bounds,
+                background: Some(color),
+                border: Border::new(0., Color::transparent_black()),
+                corner_radius: diff_style.corner_radius * line_height,
+            });
         }
     }
 
@@ -1113,6 +1094,75 @@ impl EditorElement {
             .width()
     }
 
+    //Folds contained in a hunk are ignored apart from shrinking visual size
+    //If a fold contains any hunks then that fold line is marked as modified
+    fn layout_git_gutters(
+        &self,
+        rows: Range<u32>,
+        snapshot: &EditorSnapshot,
+    ) -> Vec<DiffHunkLayout> {
+        let buffer_snapshot = &snapshot.buffer_snapshot;
+        let visual_start = DisplayPoint::new(rows.start, 0).to_point(snapshot).row;
+        let visual_end = DisplayPoint::new(rows.end, 0).to_point(snapshot).row;
+        let hunks = buffer_snapshot.git_diff_hunks_in_range(visual_start..visual_end);
+
+        let mut layouts = Vec::<DiffHunkLayout>::new();
+
+        for hunk in hunks {
+            let hunk_start_point = Point::new(hunk.buffer_range.start, 0);
+            let hunk_end_point = Point::new(hunk.buffer_range.end, 0);
+            let hunk_start_point_sub = Point::new(hunk.buffer_range.start.saturating_sub(1), 0);
+            let hunk_end_point_sub = Point::new(
+                hunk.buffer_range
+                    .end
+                    .saturating_sub(1)
+                    .max(hunk.buffer_range.start),
+                0,
+            );
+
+            let is_removal = hunk.status() == DiffHunkStatus::Removed;
+
+            let folds_start = Point::new(hunk.buffer_range.start.saturating_sub(1), 0);
+            let folds_end = Point::new(hunk.buffer_range.end + 1, 0);
+            let folds_range = folds_start..folds_end;
+
+            let containing_fold = snapshot.folds_in_range(folds_range).find(|fold_range| {
+                let fold_point_range = fold_range.to_point(buffer_snapshot);
+                let fold_point_range = fold_point_range.start..=fold_point_range.end;
+
+                let folded_start = fold_point_range.contains(&hunk_start_point);
+                let folded_end = fold_point_range.contains(&hunk_end_point_sub);
+                let folded_start_sub = fold_point_range.contains(&hunk_start_point_sub);
+
+                (folded_start && folded_end) || (is_removal && folded_start_sub)
+            });
+
+            let visual_range = if let Some(fold) = containing_fold {
+                let row = fold.start.to_display_point(snapshot).row();
+                row..row
+            } else {
+                let start = hunk_start_point.to_display_point(snapshot).row();
+                let end = hunk_end_point.to_display_point(snapshot).row();
+                start..end
+            };
+
+            let has_existing_layout = match layouts.last() {
+                Some(e) => visual_range == e.visual_range && e.status == hunk.status(),
+                None => false,
+            };
+
+            if !has_existing_layout {
+                layouts.push(DiffHunkLayout {
+                    visual_range,
+                    status: hunk.status(),
+                    is_folded: containing_fold.is_some(),
+                });
+            }
+        }
+
+        layouts
+    }
+
     fn layout_line_numbers(
         &self,
         rows: Range<u32>,
@@ -1465,27 +1515,6 @@ impl EditorElement {
     }
 }
 
-/// Get the hunk that contains buffer_line, starting from start_idx
-/// Returns none if there is none found, and
-fn get_hunk(buffer_line: u32, hunks: &[DiffHunk<u32>]) -> Option<&DiffHunk<u32>> {
-    for i in 0..hunks.len() {
-        // Safety: Index out of bounds is handled by the check above
-        let hunk = hunks.get(i).unwrap();
-        if hunk.buffer_range.contains(&(buffer_line as u32)) {
-            return Some(hunk);
-        } else if hunk.status() == DiffHunkStatus::Removed && buffer_line == hunk.buffer_range.start
-        {
-            return Some(hunk);
-        } else if hunk.buffer_range.start > buffer_line as u32 {
-            // If we've passed the buffer_line, just stop
-            return None;
-        }
-    }
-
-    // We reached the end of the array without finding a hunk, just return none.
-    return None;
-}
-
 impl Element for EditorElement {
     type LayoutState = LayoutState;
     type PaintState = ();
@@ -1665,10 +1694,7 @@ impl Element for EditorElement {
         let line_number_layouts =
             self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
 
-        let diff_hunks = snapshot
-            .buffer_snapshot
-            .git_diff_hunks_in_range(start_row..end_row)
-            .collect();
+        let hunk_layouts = self.layout_git_gutters(start_row..end_row, &snapshot);
 
         let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
 
@@ -1826,7 +1852,7 @@ impl Element for EditorElement {
                 highlighted_rows,
                 highlighted_ranges,
                 line_number_layouts,
-                diff_hunks,
+                hunk_layouts,
                 blocks,
                 selections,
                 context_menu,
@@ -1948,6 +1974,7 @@ pub struct LayoutState {
     active_rows: BTreeMap<u32, bool>,
     highlighted_rows: Option<Range<u32>>,
     line_number_layouts: Vec<Option<text_layout::Line>>,
+    hunk_layouts: Vec<DiffHunkLayout>,
     blocks: Vec<BlockLayout>,
     highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
     selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
@@ -1955,7 +1982,6 @@ pub struct LayoutState {
     show_scrollbars: bool,
     max_row: u32,
     context_menu: Option<(DisplayPoint, ElementBox)>,
-    diff_hunks: Vec<DiffHunk<u32>>,
     code_actions_indicator: Option<(u32, ElementBox)>,
     hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
 }

crates/editor/src/multi_buffer.rs 🔗

@@ -143,6 +143,7 @@ struct ExcerptSummary {
     text: TextSummary,
 }
 
+#[derive(Clone)]
 pub struct MultiBufferRows<'a> {
     buffer_row_range: Range<u32>,
     excerpts: Cursor<'a, Excerpt, Point>,

crates/git/src/diff.rs 🔗

@@ -190,7 +190,6 @@ impl BufferDiff {
             }
 
             if kind == GitDiffLineType::Deletion {
-                *buffer_row_divergence -= 1;
                 let end = content_offset + content_len;
 
                 match &mut head_byte_range {
@@ -203,6 +202,8 @@ impl BufferDiff {
                     let row = old_row as i64 + *buffer_row_divergence;
                     first_deletion_buffer_row = Some(row as u32);
                 }
+
+                *buffer_row_divergence -= 1;
             }
         }
 

crates/journal/Cargo.toml 🔗

@@ -15,3 +15,5 @@ workspace = { path = "../workspace" }
 chrono = "0.4"
 dirs = "4.0"
 log = { version = "0.4.16", features = ["kv_unstable_serde"] }
+settings = { path = "../settings" }
+shellexpand = "2.1.0"

crates/journal/src/journal.rs 🔗

@@ -1,7 +1,12 @@
-use chrono::{Datelike, Local, Timelike};
+use chrono::{Datelike, Local, NaiveTime, Timelike};
 use editor::{Autoscroll, Editor};
 use gpui::{actions, MutableAppContext};
-use std::{fs::OpenOptions, sync::Arc};
+use settings::{HourFormat, Settings};
+use std::{
+    fs::OpenOptions,
+    path::{Path, PathBuf},
+    sync::Arc,
+};
 use util::TryFutureExt as _;
 use workspace::AppState;
 
@@ -12,24 +17,23 @@ pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
 }
 
 pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
-    let now = Local::now();
-    let home_dir = match dirs::home_dir() {
-        Some(home_dir) => home_dir,
+    let settings = cx.global::<Settings>();
+    let journal_dir = match journal_dir(&settings) {
+        Some(journal_dir) => journal_dir,
         None => {
-            log::error!("can't determine home directory");
+            log::error!("Can't determine journal directory");
             return;
         }
     };
 
-    let journal_dir = home_dir.join("journal");
+    let now = Local::now();
     let month_dir = journal_dir
         .join(format!("{:02}", now.year()))
         .join(format!("{:02}", now.month()));
     let entry_path = month_dir.join(format!("{:02}.md", now.day()));
     let now = now.time();
-    let (pm, hour) = now.hour12();
-    let am_or_pm = if pm { "PM" } else { "AM" };
-    let entry_heading = format!("# {}:{:02} {}\n\n", hour, now.minute(), am_or_pm);
+    let hour_format = &settings.journal_overrides.hour_format;
+    let entry_heading = heading_entry(now, &hour_format);
 
     let create_entry = cx.background().spawn(async move {
         std::fs::create_dir_all(month_dir)?;
@@ -64,6 +68,7 @@ pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
                             editor.insert("\n\n", cx);
                         }
                         editor.insert(&entry_heading, cx);
+                        editor.insert("\n\n", cx);
                     });
                 }
             }
@@ -74,3 +79,65 @@ pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
     })
     .detach();
 }
+
+fn journal_dir(settings: &Settings) -> Option<PathBuf> {
+    let journal_dir = settings
+        .journal_overrides
+        .path
+        .as_ref()
+        .unwrap_or(settings.journal_defaults.path.as_ref()?);
+
+    let expanded_journal_dir = shellexpand::full(&journal_dir) //TODO handle this better
+        .ok()
+        .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
+
+    return expanded_journal_dir;
+}
+
+fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
+    match hour_format {
+        Some(HourFormat::Hour24) => {
+            let hour = now.hour();
+            format!("# {}:{:02}", hour, now.minute())
+        }
+        _ => {
+            let (pm, hour) = now.hour12();
+            let am_or_pm = if pm { "PM" } else { "AM" };
+            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    mod heading_entry_tests {
+        use super::super::*;
+
+        #[test]
+        fn test_heading_entry_defaults_to_hour_12() {
+            let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
+            let actual_heading_entry = heading_entry(naive_time, &None);
+            let expected_heading_entry = "# 3:00 PM";
+
+            assert_eq!(actual_heading_entry, expected_heading_entry);
+        }
+
+        #[test]
+        fn test_heading_entry_is_hour_12() {
+            let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
+            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
+            let expected_heading_entry = "# 3:00 PM";
+
+            assert_eq!(actual_heading_entry, expected_heading_entry);
+        }
+
+        #[test]
+        fn test_heading_entry_is_hour_24() {
+            let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
+            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
+            let expected_heading_entry = "# 15:00";
+
+            assert_eq!(actual_heading_entry, expected_heading_entry);
+        }
+    }
+}

crates/settings/src/settings.rs 🔗

@@ -37,6 +37,8 @@ pub struct Settings {
     pub editor_overrides: EditorSettings,
     pub git: GitSettings,
     pub git_overrides: GitSettings,
+    pub journal_defaults: JournalSettings,
+    pub journal_overrides: JournalSettings,
     pub terminal_defaults: TerminalSettings,
     pub terminal_overrides: TerminalSettings,
     pub language_defaults: HashMap<Arc<str>, EditorSettings>,
@@ -122,6 +124,34 @@ pub enum Autosave {
     OnWindowChange,
 }
 
+#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
+pub struct JournalSettings {
+    pub path: Option<String>,
+    pub hour_format: Option<HourFormat>,
+}
+
+impl Default for JournalSettings {
+    fn default() -> Self {
+        Self {
+            path: Some("~".into()),
+            hour_format: Some(Default::default()),
+        }
+    }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum HourFormat {
+    Hour12,
+    Hour24,
+}
+
+impl Default for HourFormat {
+    fn default() -> Self {
+        Self::Hour12
+    }
+}
+
 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
 pub struct TerminalSettings {
     pub shell: Option<Shell>,
@@ -216,6 +246,8 @@ pub struct SettingsFileContent {
     #[serde(flatten)]
     pub editor: EditorSettings,
     #[serde(default)]
+    pub journal: JournalSettings,
+    #[serde(default)]
     pub terminal: TerminalSettings,
     #[serde(default)]
     pub git: Option<GitSettings>,
@@ -278,6 +310,8 @@ impl Settings {
             editor_overrides: Default::default(),
             git: defaults.git.unwrap(),
             git_overrides: Default::default(),
+            journal_defaults: defaults.journal,
+            journal_overrides: Default::default(),
             terminal_defaults: defaults.terminal,
             terminal_overrides: Default::default(),
             language_defaults: defaults.languages,
@@ -330,6 +364,7 @@ impl Settings {
 
         self.editor_overrides = data.editor;
         self.git_overrides = data.git.unwrap_or_default();
+        self.journal_overrides = data.journal;
         self.terminal_defaults.font_size = data.terminal.font_size;
         self.terminal_overrides.copy_on_select = data.terminal.copy_on_select;
         self.terminal_overrides = data.terminal;
@@ -416,6 +451,8 @@ impl Settings {
                 enable_language_server: Some(true),
             },
             editor_overrides: Default::default(),
+            journal_defaults: Default::default(),
+            journal_overrides: Default::default(),
             terminal_defaults: Default::default(),
             terminal_overrides: Default::default(),
             git: Default::default(),

crates/terminal/src/terminal.rs 🔗

@@ -1018,55 +1018,34 @@ impl Terminal {
             self.last_content.size,
             self.last_content.display_offset,
         );
-        // let side = mouse_side(position, self.last_content.size);
 
         if self.mouse_mode(e.shift) {
             if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) {
                 self.pty_tx.notify(bytes);
             }
         } else if e.button == MouseButton::Left {
-            self.left_click(e, origin)
-        }
-    }
-
-    pub fn left_click(&mut self, e: &MouseDown, origin: Vector2F) {
-        let position = e.position.sub(origin);
-        if !self.mouse_mode(e.shift) {
-            //Hyperlinks
-            {
-                let mouse_cell_index = content_index_for_mouse(position, &self.last_content);
-                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
-                    open_uri(link.uri()).log_err();
-                } else {
-                    self.events
-                        .push_back(InternalEvent::FindHyperlink(position, true));
-                }
-            }
+            let position = e.position.sub(origin);
+            let point = grid_point(
+                position,
+                self.last_content.size,
+                self.last_content.display_offset,
+            );
+            let side = mouse_side(position, self.last_content.size);
 
-            // Selections
-            {
-                let point = grid_point(
-                    position,
-                    self.last_content.size,
-                    self.last_content.display_offset,
-                );
-                let side = mouse_side(position, self.last_content.size);
-
-                let selection_type = match e.click_count {
-                    0 => return, //This is a release
-                    1 => Some(SelectionType::Simple),
-                    2 => Some(SelectionType::Semantic),
-                    3 => Some(SelectionType::Lines),
-                    _ => None,
-                };
+            let selection_type = match e.click_count {
+                0 => return, //This is a release
+                1 => Some(SelectionType::Simple),
+                2 => Some(SelectionType::Semantic),
+                3 => Some(SelectionType::Lines),
+                _ => None,
+            };
 
-                let selection = selection_type
-                    .map(|selection_type| Selection::new(selection_type, point, side));
+            let selection =
+                selection_type.map(|selection_type| Selection::new(selection_type, point, side));
 
-                if let Some(sel) = selection {
-                    self.events
-                        .push_back(InternalEvent::SetSelection(Some((sel, point))));
-                }
+            if let Some(sel) = selection {
+                self.events
+                    .push_back(InternalEvent::SetSelection(Some((sel, point))));
             }
         }
     }
@@ -1094,8 +1073,21 @@ impl Terminal {
             if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) {
                 self.pty_tx.notify(bytes);
             }
-        } else if e.button == MouseButton::Left && copy_on_select {
-            self.copy();
+        } else {
+            if e.button == MouseButton::Left && copy_on_select {
+                self.copy();
+            }
+
+            //Hyperlinks
+            if self.selection_phase == SelectionPhase::Ended {
+                let mouse_cell_index = content_index_for_mouse(position, &self.last_content);
+                if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
+                    open_uri(link.uri()).log_err();
+                } else {
+                    self.events
+                        .push_back(InternalEvent::FindHyperlink(position, true));
+                }
+            }
         }
 
         self.selection_phase = SelectionPhase::Ended;