Skip to main content

minus/
prompt.rs

1use crate::{LineNumbers, PagerState};
2use std::sync::Arc;
3
4mod style;
5pub use style::write_prompt_color;
6pub use style::{PromptAttribute, PromptColor, PromptStyle};
7use unicode_segmentation::UnicodeSegmentation;
8use unicode_width::UnicodeWidthStr;
9
10const RESET_STYLE: &str = "\x1b[0m";
11
12/// Runs synchronously while pager state is locked.
13pub type PromptRenderer = Arc<
14    dyn for<'a> Fn(&PromptContext<'a>) -> Result<PromptLine, PromptError> + Send + Sync + 'static,
15>;
16
17#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
18pub enum PromptError {
19    #[error("document layout failed: {0}")]
20    Layout(String),
21    #[error("prompt content must fit on one line")]
22    MultilineText,
23    #[error("prompt content contains unsupported control character {0:?}")]
24    ControlCharacter(char),
25}
26
27pub struct PromptContext<'a> {
28    state: &'a PagerState,
29}
30
31impl<'a> PromptContext<'a> {
32    pub(crate) const fn new(state: &'a PagerState) -> Self {
33        Self { state }
34    }
35
36    #[must_use]
37    pub fn prompt(&self) -> &'a str {
38        &self.state.prompt
39    }
40
41    #[must_use]
42    pub fn message(&self) -> Option<&'a str> {
43        self.state.message.as_deref()
44    }
45
46    /// Whether the outline navigation hint has not yet been acknowledged.
47    #[cfg(feature = "search")]
48    #[must_use]
49    pub const fn toc_hint_visible(&self) -> bool {
50        self.state.toc_hint_visible()
51    }
52
53    #[must_use]
54    pub fn display_text(&self) -> &'a str {
55        self.message().unwrap_or_else(|| self.prompt())
56    }
57
58    #[must_use]
59    pub const fn columns(&self) -> usize {
60        self.state.cols
61    }
62
63    #[must_use]
64    pub const fn rows(&self) -> usize {
65        self.state.rows
66    }
67
68    #[must_use]
69    pub const fn content_rows(&self) -> usize {
70        self.state.content_rows()
71    }
72
73    #[must_use]
74    pub const fn panel_rows(&self) -> usize {
75        self.state.prompt_panel_rows()
76    }
77
78    #[must_use]
79    pub const fn upper_mark(&self) -> usize {
80        self.state.upper_mark
81    }
82
83    #[must_use]
84    pub const fn left_mark(&self) -> usize {
85        self.state.left_mark
86    }
87
88    #[must_use]
89    pub const fn formatted_lines(&self) -> usize {
90        self.state.screen.formatted_lines_count()
91    }
92
93    #[must_use]
94    pub const fn logical_lines(&self) -> usize {
95        self.state.screen.line_count()
96    }
97
98    #[must_use]
99    pub const fn max_scroll_offset(&self) -> usize {
100        self.state.max_upper_mark()
101    }
102
103    #[must_use]
104    pub fn scroll_percentage(&self) -> u8 {
105        let max_offset = self.max_scroll_offset();
106        if max_offset == 0 {
107            return 100;
108        }
109
110        let offset = self.upper_mark().min(max_offset) as u128;
111        let percentage = (offset * 100 + max_offset as u128 / 2) / max_offset as u128;
112        #[allow(clippy::cast_possible_truncation)]
113        let percentage = percentage as u8;
114        percentage
115    }
116
117    #[must_use]
118    pub fn numeric_prefix(&self) -> &'a str {
119        &self.state.prefix_num
120    }
121
122    #[must_use]
123    pub const fn line_numbers(&self) -> LineNumbers {
124        self.state.line_numbers
125    }
126
127    #[must_use]
128    pub const fn line_wrapping(&self) -> bool {
129        self.state.screen.line_wrapping
130    }
131
132    #[must_use]
133    pub const fn follow_output(&self) -> bool {
134        self.state.follow_output
135    }
136
137    #[must_use]
138    #[cfg(feature = "search")]
139    pub fn search_position(&self) -> Option<(usize, usize)> {
140        let total = self.state.search_state.search_matches.len();
141        (total > 0).then_some((self.state.search_state.search_mark + 1, total))
142    }
143
144    /// Returns the selected source line while line-navigation mode is active.
145    #[must_use]
146    #[cfg(feature = "search")]
147    pub const fn line_navigation_position(&self) -> Option<usize> {
148        self.state.line_navigation_position()
149    }
150}
151
152#[derive(Clone, Debug, Eq, PartialEq)]
153pub struct PromptSpan {
154    text: String,
155    style: PromptStyle,
156}
157
158#[allow(clippy::missing_errors_doc)]
159impl PromptSpan {
160    /// Rejects line breaks and terminal control characters.
161    pub fn new(text: impl Into<String>, style: PromptStyle) -> Result<Self, PromptError> {
162        let text = text.into();
163        validate_single_line(&text)?;
164        if let Some(character) = text.chars().find(|character| character.is_control()) {
165            return Err(PromptError::ControlCharacter(character));
166        }
167        Ok(Self { text, style })
168    }
169
170    fn width(&self) -> usize {
171        UnicodeWidthStr::width(self.text.as_str())
172    }
173}
174
175#[derive(Clone, Debug, Default, Eq, PartialEq)]
176pub struct PromptLine {
177    left: Vec<PromptSpan>,
178    right: Vec<PromptSpan>,
179    fill_style: PromptStyle,
180    truncation_indicator: Option<PromptSpan>,
181}
182
183#[allow(clippy::missing_errors_doc)]
184impl PromptLine {
185    #[must_use]
186    pub const fn new() -> Self {
187        Self {
188            left: Vec::new(),
189            right: Vec::new(),
190            fill_style: PromptStyle {
191                foreground: None,
192                background: None,
193                attributes: 0,
194            },
195            truncation_indicator: None,
196        }
197    }
198
199    pub fn plain(text: impl Into<String>) -> Result<Self, PromptError> {
200        Ok(Self::new().left(PromptSpan::new(text, PromptStyle::default())?))
201    }
202
203    #[must_use]
204    pub fn left(mut self, span: PromptSpan) -> Self {
205        self.left.push(span);
206        self
207    }
208
209    #[must_use]
210    pub fn right(mut self, span: PromptSpan) -> Self {
211        self.right.push(span);
212        self
213    }
214
215    #[must_use]
216    pub const fn fill_style(mut self, style: PromptStyle) -> Self {
217        self.fill_style = style;
218        self
219    }
220
221    #[must_use]
222    pub fn truncation_indicator(mut self, span: PromptSpan) -> Self {
223        self.truncation_indicator = Some(span);
224        self
225    }
226
227    #[must_use]
228    pub fn render(&self, columns: usize) -> String {
229        let spans = self.layout(columns);
230        let mut output = String::with_capacity(columns.saturating_add(spans.len() * 16));
231        for span in spans {
232            span.style.write_styled(&mut output, &span.text);
233        }
234        output.push_str(RESET_STYLE);
235        output
236    }
237
238    #[must_use]
239    pub fn render_plain(&self, columns: usize) -> String {
240        self.layout(columns)
241            .into_iter()
242            .map(|span| span.text)
243            .collect()
244    }
245
246    fn layout(&self, columns: usize) -> Vec<PromptSpan> {
247        if columns == 0 {
248            return Vec::new();
249        }
250
251        let right_width = spans_width(&self.right);
252        if right_width >= columns {
253            let right = take_suffix(&self.right, columns);
254            let filler_width = columns.saturating_sub(spans_width(&right));
255            if filler_width == 0 {
256                return right;
257            }
258
259            let mut output = vec![PromptSpan {
260                text: " ".repeat(filler_width),
261                style: self.fill_style,
262            }];
263            output.extend(right);
264            return output;
265        }
266
267        let left_limit = columns - right_width;
268        let mut output = if spans_width(&self.left) > left_limit {
269            self.truncated_left(left_limit)
270        } else {
271            self.left.clone()
272        };
273        let filler_width = columns
274            .saturating_sub(spans_width(&output))
275            .saturating_sub(right_width);
276        if filler_width > 0 {
277            output.push(PromptSpan {
278                text: " ".repeat(filler_width),
279                style: self.fill_style,
280            });
281        }
282        output.extend(self.right.clone());
283        output
284    }
285
286    fn truncated_left(&self, width: usize) -> Vec<PromptSpan> {
287        let indicator = self
288            .truncation_indicator
289            .as_ref()
290            .map_or_else(Vec::new, |span| {
291                take_prefix(std::slice::from_ref(span), width)
292            });
293        let content_width = width.saturating_sub(spans_width(&indicator));
294        let mut left = take_prefix(&self.left, content_width);
295        left.extend(indicator);
296        left
297    }
298}
299
300pub fn validate_single_line(text: &str) -> Result<(), PromptError> {
301    if text.contains(['\n', '\r']) {
302        Err(PromptError::MultilineText)
303    } else {
304        Ok(())
305    }
306}
307
308fn spans_width(spans: &[PromptSpan]) -> usize {
309    spans.iter().map(PromptSpan::width).sum()
310}
311
312fn take_prefix(spans: &[PromptSpan], width: usize) -> Vec<PromptSpan> {
313    let mut remaining = width;
314    let mut output = Vec::new();
315    for span in spans {
316        if remaining == 0 {
317            break;
318        }
319        let text = take_text_prefix(&span.text, remaining);
320        let used = UnicodeWidthStr::width(text.as_str());
321        if !text.is_empty() {
322            output.push(PromptSpan {
323                text,
324                style: span.style,
325            });
326        }
327        remaining = remaining.saturating_sub(used);
328        if used < span.width() {
329            break;
330        }
331    }
332    output
333}
334
335fn take_suffix(spans: &[PromptSpan], width: usize) -> Vec<PromptSpan> {
336    let mut remaining = width;
337    let mut reversed = Vec::new();
338    for span in spans.iter().rev() {
339        if remaining == 0 {
340            break;
341        }
342        let text = take_text_suffix(&span.text, remaining);
343        let used = UnicodeWidthStr::width(text.as_str());
344        if !text.is_empty() {
345            reversed.push(PromptSpan {
346                text,
347                style: span.style,
348            });
349        }
350        remaining = remaining.saturating_sub(used);
351        if used < span.width() {
352            break;
353        }
354    }
355    reversed.reverse();
356    reversed
357}
358
359fn take_text_prefix(text: &str, width: usize) -> String {
360    let mut used = 0;
361    text.graphemes(true)
362        .take_while(|grapheme| {
363            let next = used + UnicodeWidthStr::width(*grapheme);
364            if next > width {
365                return false;
366            }
367            used = next;
368            true
369        })
370        .collect()
371}
372
373fn take_text_suffix(text: &str, width: usize) -> String {
374    let mut used = 0;
375    let mut graphemes = text
376        .graphemes(true)
377        .rev()
378        .take_while(|grapheme| {
379            let next = used + UnicodeWidthStr::width(*grapheme);
380            if next > width {
381                return false;
382            }
383            used = next;
384            true
385        })
386        .collect::<Vec<_>>();
387    graphemes.reverse();
388    graphemes.concat()
389}
390
391#[cfg(test)]
392mod tests;