on master help sign in
Customizable/configurable status line (#2434)

* feat(statusline): add the file type (language id) to the status line * refactor(statusline): move the statusline implementation into an own struct * refactor(statusline): split the statusline implementation into different functions * refactor(statusline): Append elements using a consistent API This is a preparation for the configurability which is about to be implemented. * refactor(statusline): implement render_diagnostics() This avoid cluttering the render() function and will simplify configurability. * feat(statusline): make the status line configurable * refactor(statusline): make clippy happy * refactor(statusline): avoid intermediate StatusLineObject Use a more functional approach to obtain render functions and write to the buffers, and avoid an intermediate StatusLineElement object. * fix(statusline): avoid rendering the left elements twice * refactor(statusline): make clippy happy again * refactor(statusline): rename `buffer` into `parts` * refactor(statusline): ensure the match is exhaustive * fix(statusline): avoid an overflow when calculating the maximal center width * chore(statusline): Describe the statusline configurability in the book * chore(statusline): Correct and add documentation * refactor(statusline): refactor some code following the code review Avoid very small helper functions for the diagnositcs and inline them instead. Rename the config field `status_line` to `statusline` to remain consistent with `bufferline`. * chore(statusline): adjust documentation following the config field refactoring * revert(statusline): revert regression introduced by c0a1870 * chore(statusline): slight adjustment in the configuration documentation * feat(statusline): integrate changes from #2676 after rebasing * refactor(statusline): remove the StatusLine struct Because none of the functions need `Self` and all of them are in an own file, there is no explicit need for the struct. * fix(statusline): restore the configurability of color modes The configuration was ignored after reintegrating the changes of #2676 in 8d28f95. * fix(statusline): remove the spinner padding * refactor(statusline): remove unnecessary format!()

commitdbf68e0370981dc4ad0fa74596b57347f7048fab authorMr. E <2804556+etienne-k@users.noreply.github.com> dateMon 18 Jul 2022, 02:57 (4 years ago) parent43761d4
5 files changed+401−156
book/src/configuration.md+31−1 helix-term/src/ui/editor.rs+8−155 helix-term/src/ui/mod.rs+1 helix-term/src/ui/statusline.rs+310 helix-view/src/editor.rs+51
book/src/configuration.md+31−1
@@ -48,13 +48,43 @@ hidden = false
4848| `rulers` | List of column positions at which to display the rulers. Can be overridden by language specific `rulers` in `languages.toml` file. | `[]` |
4949| `color-modes` | Whether to color the mode indicator with different colors depending on the mode itself | `false` |
5050
51+### `[editor.statusline]` Section
52+
53+Allows configuring the statusline at the bottom of the editor.
54+
55+The configuration distinguishes between three areas of the status line:
56+
57+`[ ... ... LEFT ... ... | ... ... ... ... CENTER ... ... ... ... | ... ... RIGHT ... ... ]`
58+
59+Statusline elements can be defined as follows:
60+
61+```toml
62+[editor.statusline]
63+left = ["mode", "spinner"]
64+center = ["file-name"]
65+right = ["diagnostics", "selections", "position", "file-encoding", "file-type"]
66+```
67+
68+The following elements can be configured:
69+
70+| Key | Description |
71+| ------ | ----------- |
72+| `mode` | The current editor mode (`NOR`/`INS`/`SEL`) |
73+| `spinner` | A progress spinner indicating LSP activity |
74+| `file-name` | The path/name of the opened file |
75+| `file-encoding` | The encoding of the opened file if it differs from UTF-8 |
76+| `file-type` | The type of the opened file |
77+| `diagnostics` | The number of warnings and/or errors |
78+| `selections` | The number of active selections |
79+| `position` | The cursor position |
80+
5181### `[editor.lsp]` Section
5282
5383| Key | Description | Default |
5484| --- | ----------- | ------- |
5585| `display-messages` | Display LSP progress messages below statusline[^1] | `false` |
5686
57−[^1]: A progress spinner is always shown in the statusline beside the file path.
87+[^1]: By default, a progress spinner is shown in the statusline beside the file path.
5888
5989### `[editor.cursor-shape]` Section
6090
helix-term/src/ui/editor.rs+8−155
@@ -7,7 +7,6 @@ use crate::{
77};
88
99use helix_core::{
10− coords_at_pos, encoding,
1110 graphemes::{
1211 ensure_grapheme_boundary_next_byte, next_grapheme_boundary, prev_grapheme_boundary,
1312 },
@@ -17,7 +16,7 @@ use helix_core::{
1716 LineEnding, Position, Range, Selection, Transaction,
1817};
1918use helix_view::{
20− document::{Mode, SCRATCH_BUFFER_NAME},
19+ document::Mode,
2120 editor::{CompleteAction, CursorShapeConfig},
2221 graphics::{Color, CursorKind, Modifier, Rect, Style},
2322 input::KeyEvent,
@@ -29,6 +28,8 @@ use std::borrow::Cow;
2928use crossterm::event::{Event, MouseButton, MouseEvent, MouseEventKind};
3029use tui::buffer::Buffer as Surface;
3130
31+use super::statusline;
32+
3233pub struct EditorView {
3334 pub keymaps: Keymaps,
3435 on_next_key: Option<Box<dyn FnOnce(&mut commands::Context, KeyEvent)>>,
@@ -161,7 +162,11 @@ impl EditorView {
161162 .area
162163 .clip_top(view.area.height.saturating_sub(1))
163164 .clip_bottom(1); // -1 from bottom to remove commandline
164− self.render_statusline(editor, doc, view, statusline_area, surface, is_focused);
165+
166+ let mut context =
167+ statusline::RenderContext::new(editor, doc, view, is_focused, &self.spinners);
168+
169+ statusline::render(&mut context, statusline_area, surface);
165170 }
166171
167172 pub fn render_rulers(
@@ -730,158 +735,6 @@ impl EditorView {
730735 }
731736 }
732737
733− pub fn render_statusline(
734− &self,
735− editor: &Editor,
736− doc: &Document,
737− view: &View,
738− viewport: Rect,
739− surface: &mut Surface,
740− is_focused: bool,
741− ) {
742− use tui::text::{Span, Spans};
743−
744− //-------------------------------
745− // Left side of the status line.
746− //-------------------------------
747−
748− let theme = &editor.theme;
749− let (mode, mode_style) = match doc.mode() {
750− Mode::Insert => (" INS ", theme.get("ui.statusline.insert")),
751− Mode::Select => (" SEL ", theme.get("ui.statusline.select")),
752− Mode::Normal => (" NOR ", theme.get("ui.statusline.normal")),
753− };
754− let progress = doc
755− .language_server()
756− .and_then(|srv| {
757− self.spinners
758− .get(srv.id())
759− .and_then(|spinner| spinner.frame())
760− })
761− .unwrap_or("");
762−
763− let base_style = if is_focused {
764− theme.get("ui.statusline")
765− } else {
766− theme.get("ui.statusline.inactive")
767− };
768− // statusline
769− surface.set_style(viewport.with_height(1), base_style);
770− if is_focused {
771− let color_modes = editor.config().color_modes;
772− surface.set_string(
773− viewport.x,
774− viewport.y,
775− mode,
776− if color_modes { mode_style } else { base_style },
777− );
778− }
779− surface.set_string(viewport.x + 5, viewport.y, progress, base_style);
780−
781− //-------------------------------
782− // Right side of the status line.
783− //-------------------------------
784−
785− let mut right_side_text = Spans::default();
786−
787− // Compute the individual info strings and add them to `right_side_text`.
788−
789− // Diagnostics
790− let diags = doc.diagnostics().iter().fold((0, 0), |mut counts, diag| {
791− use helix_core::diagnostic::Severity;
792− match diag.severity {
793− Some(Severity::Warning) => counts.0 += 1,
794− Some(Severity::Error) | None => counts.1 += 1,
795− _ => {}
796− }
797− counts
798− });
799− let (warnings, errors) = diags;
800− let warning_style = theme.get("warning");
801− let error_style = theme.get("error");
802− for i in 0..2 {
803− let (count, style) = match i {
804− 0 => (warnings, warning_style),
805− 1 => (errors, error_style),
806− _ => unreachable!(),
807− };
808− if count == 0 {
809− continue;
810− }
811− let style = base_style.patch(style);
812− right_side_text.0.push(Span::styled("●", style));
813− right_side_text
814− .0
815− .push(Span::styled(format!(" {} ", count), base_style));
816− }
817−
818− // Selections
819− let sels_count = doc.selection(view.id).len();
820− right_side_text.0.push(Span::styled(
821− format!(
822− " {} sel{} ",
823− sels_count,
824− if sels_count == 1 { "" } else { "s" }
825− ),
826− base_style,
827− ));
828−
829− // Position
830− let pos = coords_at_pos(
831− doc.text().slice(..),
832− doc.selection(view.id)
833− .primary()
834− .cursor(doc.text().slice(..)),
835− );
836− right_side_text.0.push(Span::styled(
837− format!(" {}:{} ", pos.row + 1, pos.col + 1), // Convert to 1-indexing.
838− base_style,
839− ));
840−
841− let enc = doc.encoding();
842− if enc != encoding::UTF_8 {
843− right_side_text
844− .0
845− .push(Span::styled(format!(" {} ", enc.name()), base_style));
846− }
847−
848− // Render to the statusline.
849− surface.set_spans(
850− viewport.x
851− + viewport
852− .width
853− .saturating_sub(right_side_text.width() as u16),
854− viewport.y,
855− &right_side_text,
856− right_side_text.width() as u16,
857− );
858−
859− //-------------------------------
860− // Middle / File path / Title
861− //-------------------------------
862− let title = {
863− let rel_path = doc.relative_path();
864− let path = rel_path
865− .as_ref()
866− .map(|p| p.to_string_lossy())
867− .unwrap_or_else(|| SCRATCH_BUFFER_NAME.into());
868− format!("{}{}", path, if doc.is_modified() { "[+]" } else { "" })
869− };
870−
871− surface.set_string_truncated(
872− viewport.x + 8, // 8: 1 space + 3 char mode string + 1 space + 1 spinner + 1 space
873− viewport.y,
874− &title,
875− viewport
876− .width
877− .saturating_sub(6)
878− .saturating_sub(right_side_text.width() as u16 + 1) as usize, // "+ 1": a space between the title and the selection info
879− |_| base_style,
880− true,
881− true,
882− );
883− }
884−
885738 /// Handle events by looking them up in `self.keymaps`. Returns None
886739 /// if event was handled (a command was executed or a subkeymap was
887740 /// activated). Only KeymapResult::{NotFound, Cancelled} is returned
helix-term/src/ui/mod.rs+1
@@ -8,6 +8,7 @@ mod picker;
88mod popup;
99mod prompt;
1010mod spinner;
11+mod statusline;
1112mod text;
1213
1314pub use completion::Completion;
helix-term/src/ui/statusline.rsnew file+310
@@ -0,0 +1,310 @@
1+use helix_core::{coords_at_pos, encoding};
2+use helix_view::{
3+ document::{Mode, SCRATCH_BUFFER_NAME},
4+ graphics::Rect,
5+ theme::Style,
6+ Document, Editor, View,
7+};
8+
9+use crate::ui::ProgressSpinners;
10+
11+use helix_view::editor::StatusLineElement as StatusLineElementID;
12+use tui::buffer::Buffer as Surface;
13+use tui::text::{Span, Spans};
14+
15+pub struct RenderContext<'a> {
16+ pub editor: &'a Editor,
17+ pub doc: &'a Document,
18+ pub view: &'a View,
19+ pub focused: bool,
20+ pub spinners: &'a ProgressSpinners,
21+ pub parts: RenderBuffer<'a>,
22+}
23+
24+impl<'a> RenderContext<'a> {
25+ pub fn new(
26+ editor: &'a Editor,
27+ doc: &'a Document,
28+ view: &'a View,
29+ focused: bool,
30+ spinners: &'a ProgressSpinners,
31+ ) -> Self {
32+ RenderContext {
33+ editor,
34+ doc,
35+ view,
36+ focused,
37+ spinners,
38+ parts: RenderBuffer::default(),
39+ }
40+ }
41+}
42+
43+#[derive(Default)]
44+pub struct RenderBuffer<'a> {
45+ pub left: Spans<'a>,
46+ pub center: Spans<'a>,
47+ pub right: Spans<'a>,
48+}
49+
50+pub fn render(context: &mut RenderContext, viewport: Rect, surface: &mut Surface) {
51+ let base_style = if context.focused {
52+ context.editor.theme.get("ui.statusline")
53+ } else {
54+ context.editor.theme.get("ui.statusline.inactive")
55+ };
56+
57+ surface.set_style(viewport.with_height(1), base_style);
58+
59+ let write_left = |context: &mut RenderContext, text, style| {
60+ append(&mut context.parts.left, text, &base_style, style)
61+ };
62+ let write_center = |context: &mut RenderContext, text, style| {
63+ append(&mut context.parts.center, text, &base_style, style)
64+ };
65+ let write_right = |context: &mut RenderContext, text, style| {
66+ append(&mut context.parts.right, text, &base_style, style)
67+ };
68+
69+ // Left side of the status line.
70+
71+ let element_ids = &context.editor.config().statusline.left;
72+ element_ids
73+ .iter()
74+ .map(|element_id| get_render_function(*element_id))
75+ .for_each(|render| render(context, write_left));
76+
77+ surface.set_spans(
78+ viewport.x,
79+ viewport.y,
80+ &context.parts.left,
81+ context.parts.left.width() as u16,
82+ );
83+
84+ // Right side of the status line.
85+
86+ let element_ids = &context.editor.config().statusline.right;
87+ element_ids
88+ .iter()
89+ .map(|element_id| get_render_function(*element_id))
90+ .for_each(|render| render(context, write_right));
91+
92+ surface.set_spans(
93+ viewport.x
94+ + viewport
95+ .width
96+ .saturating_sub(context.parts.right.width() as u16),
97+ viewport.y,
98+ &context.parts.right,
99+ context.parts.right.width() as u16,
100+ );
101+
102+ // Center of the status line.
103+
104+ let element_ids = &context.editor.config().statusline.center;
105+ element_ids
106+ .iter()
107+ .map(|element_id| get_render_function(*element_id))
108+ .for_each(|render| render(context, write_center));
109+
110+ // Width of the empty space between the left and center area and between the center and right area.
111+ let spacing = 1u16;
112+
113+ let edge_width = context.parts.left.width().max(context.parts.right.width()) as u16;
114+ let center_max_width = viewport.width.saturating_sub(2 * edge_width + 2 * spacing);
115+ let center_width = center_max_width.min(context.parts.center.width() as u16);
116+
117+ surface.set_spans(
118+ viewport.x + viewport.width / 2 - center_width / 2,
119+ viewport.y,
120+ &context.parts.center,
121+ center_width,
122+ );
123+}
124+
125+fn append(buffer: &mut Spans, text: String, base_style: &Style, style: Option<Style>) {
126+ buffer.0.push(Span::styled(
127+ text,
128+ style.map_or(*base_style, |s| (*base_style).patch(s)),
129+ ));
130+}
131+
132+fn get_render_function<F>(element_id: StatusLineElementID) -> impl Fn(&mut RenderContext, F)
133+where
134+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
135+{
136+ match element_id {
137+ helix_view::editor::StatusLineElement::Mode => render_mode,
138+ helix_view::editor::StatusLineElement::Spinner => render_lsp_spinner,
139+ helix_view::editor::StatusLineElement::FileName => render_file_name,
140+ helix_view::editor::StatusLineElement::FileEncoding => render_file_encoding,
141+ helix_view::editor::StatusLineElement::FileType => render_file_type,
142+ helix_view::editor::StatusLineElement::Diagnostics => render_diagnostics,
143+ helix_view::editor::StatusLineElement::Selections => render_selections,
144+ helix_view::editor::StatusLineElement::Position => render_position,
145+ }
146+}
147+
148+fn render_mode<F>(context: &mut RenderContext, write: F)
149+where
150+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
151+{
152+ let visible = context.focused;
153+
154+ write(
155+ context,
156+ format!(
157+ " {} ",
158+ if visible {
159+ match context.doc.mode() {
160+ Mode::Insert => "INS",
161+ Mode::Select => "SEL",
162+ Mode::Normal => "NOR",
163+ }
164+ } else {
165+ // If not focused, explicitly leave an empty space instead of returning None.
166+ " "
167+ }
168+ ),
169+ if visible && context.editor.config().color_modes {
170+ match context.doc.mode() {
171+ Mode::Insert => Some(context.editor.theme.get("ui.statusline.insert")),
172+ Mode::Select => Some(context.editor.theme.get("ui.statusline.select")),
173+ Mode::Normal => Some(context.editor.theme.get("ui.statusline.normal")),
174+ }
175+ } else {
176+ None
177+ },
178+ );
179+}
180+
181+fn render_lsp_spinner<F>(context: &mut RenderContext, write: F)
182+where
183+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
184+{
185+ write(
186+ context,
187+ context
188+ .doc
189+ .language_server()
190+ .and_then(|srv| {
191+ context
192+ .spinners
193+ .get(srv.id())
194+ .and_then(|spinner| spinner.frame())
195+ })
196+ // Even if there's no spinner; reserve its space to avoid elements frequently shifting.
197+ .unwrap_or(" ")
198+ .to_string(),
199+ None,
200+ );
201+}
202+
203+fn render_diagnostics<F>(context: &mut RenderContext, write: F)
204+where
205+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
206+{
207+ let (warnings, errors) = context
208+ .doc
209+ .diagnostics()
210+ .iter()
211+ .fold((0, 0), |mut counts, diag| {
212+ use helix_core::diagnostic::Severity;
213+ match diag.severity {
214+ Some(Severity::Warning) => counts.0 += 1,
215+ Some(Severity::Error) | None => counts.1 += 1,
216+ _ => {}
217+ }
218+ counts
219+ });
220+
221+ if warnings > 0 {
222+ write(
223+ context,
224+ "●".to_string(),
225+ Some(context.editor.theme.get("warning")),
226+ );
227+ write(context, format!(" {} ", warnings), None);
228+ }
229+
230+ if errors > 0 {
231+ write(
232+ context,
233+ "●".to_string(),
234+ Some(context.editor.theme.get("error")),
235+ );
236+ write(context, format!(" {} ", errors), None);
237+ }
238+}
239+
240+fn render_selections<F>(context: &mut RenderContext, write: F)
241+where
242+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
243+{
244+ let count = context.doc.selection(context.view.id).len();
245+ write(
246+ context,
247+ format!(" {} sel{} ", count, if count == 1 { "" } else { "s" }),
248+ None,
249+ );
250+}
251+
252+fn render_position<F>(context: &mut RenderContext, write: F)
253+where
254+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
255+{
256+ let position = coords_at_pos(
257+ context.doc.text().slice(..),
258+ context
259+ .doc
260+ .selection(context.view.id)
261+ .primary()
262+ .cursor(context.doc.text().slice(..)),
263+ );
264+
265+ write(
266+ context,
267+ format!(" {}:{} ", position.row + 1, position.col + 1),
268+ None,
269+ );
270+}
271+
272+fn render_file_encoding<F>(context: &mut RenderContext, write: F)
273+where
274+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
275+{
276+ let enc = context.doc.encoding();
277+
278+ if enc != encoding::UTF_8 {
279+ write(context, format!(" {} ", enc.name()), None);
280+ }
281+}
282+
283+fn render_file_type<F>(context: &mut RenderContext, write: F)
284+where
285+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
286+{
287+ let file_type = context.doc.language_id().unwrap_or("text");
288+
289+ write(context, format!(" {} ", file_type), None);
290+}
291+
292+fn render_file_name<F>(context: &mut RenderContext, write: F)
293+where
294+ F: Fn(&mut RenderContext, String, Option<Style>) + Copy,
295+{
296+ let title = {
297+ let rel_path = context.doc.relative_path();
298+ let path = rel_path
299+ .as_ref()
300+ .map(|p| p.to_string_lossy())
301+ .unwrap_or_else(|| SCRATCH_BUFFER_NAME.into());
302+ format!(
303+ " {}{} ",
304+ path,
305+ if context.doc.is_modified() { "[+]" } else { "" }
306+ )
307+ };
308+
309+ write(context, title, None);
310+}
helix-view/src/editor.rs+51
@@ -147,6 +147,8 @@ pub struct Config {
147147 /// Whether to display infoboxes. Defaults to true.
148148 pub auto_info: bool,
149149 pub file_picker: FilePickerConfig,
150+ /// Configuration of the statusline elements
151+ pub statusline: StatusLineConfig,
150152 /// Shape for cursor in each mode
151153 pub cursor_shape: CursorShapeConfig,
152154 /// Set to `true` to override automatic detection of terminal truecolor support in the event of a false negative. Defaults to `false`.
@@ -180,6 +182,54 @@ pub struct SearchConfig {
180182 pub wrap_around: bool,
181183}
182184
185+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
186+#[serde(rename_all = "kebab-case", default, deny_unknown_fields)]
187+pub struct StatusLineConfig {
188+ pub left: Vec<StatusLineElement>,
189+ pub center: Vec<StatusLineElement>,
190+ pub right: Vec<StatusLineElement>,
191+}
192+
193+impl Default for StatusLineConfig {
194+ fn default() -> Self {
195+ use StatusLineElement as E;
196+
197+ Self {
198+ left: vec![E::Mode, E::Spinner, E::FileName],
199+ center: vec![],
200+ right: vec![E::Diagnostics, E::Selections, E::Position, E::FileEncoding],
201+ }
202+ }
203+}
204+
205+#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
206+#[serde(rename_all = "kebab-case")]
207+pub enum StatusLineElement {
208+ /// The editor mode (Normal, Insert, Visual/Selection)
209+ Mode,
210+
211+ /// The LSP activity spinner
212+ Spinner,
213+
214+ /// The file nane/path, including a dirty flag if it's unsaved
215+ FileName,
216+
217+ /// The file encoding
218+ FileEncoding,
219+
220+ /// The file type (language ID or "text")
221+ FileType,
222+
223+ /// A summary of the number of errors and warnings
224+ Diagnostics,
225+
226+ /// The number of selections (cursors)
227+ Selections,
228+
229+ /// The cursor position
230+ Position,
231+}
232+
183233// Cursor shape is read and used on every rendered frame and so needs
184234// to be fast. Therefore we avoid a hashmap and use an enum indexed array.
185235#[derive(Debug, Clone, PartialEq)]
@@ -409,6 +459,7 @@ impl Default for Config {
409459 completion_trigger_len: 2,
410460 auto_info: true,
411461 file_picker: FilePickerConfig::default(),
462+ statusline: StatusLineConfig::default(),
412463 cursor_shape: CursorShapeConfig::default(),
413464 true_color: false,
414465 search: SearchConfig::default(),