Enum broot::pattern::Pattern

source ·
pub enum Pattern {
    None,
    NameExact(ExactPattern),
    NameFuzzy(FuzzyPattern),
    NameRegex(RegexPattern),
    NameTokens(TokPattern),
    PathExact(ExactPattern),
    PathFuzzy(FuzzyPattern),
    PathRegex(RegexPattern),
    PathTokens(TokPattern),
    ContentExact(ContentExactPattern),
    ContentRegex(ContentRegexPattern),
    Composite(CompositePattern),
}
Expand description

a pattern for filtering and sorting files.

Variants§

§

None

§

NameExact(ExactPattern)

§

NameFuzzy(FuzzyPattern)

§

NameRegex(RegexPattern)

§

NameTokens(TokPattern)

§

PathExact(ExactPattern)

§

PathFuzzy(FuzzyPattern)

§

PathRegex(RegexPattern)

§

PathTokens(TokPattern)

§

ContentExact(ContentExactPattern)

§

ContentRegex(ContentRegexPattern)

§

Composite(CompositePattern)

Implementations§

Examples found in repository?
src/pattern/input_pattern.rs (line 39)
34
35
36
37
38
39
40
41
    pub fn new(
        raw: String,
        parts_expr: &BeTree<PatternOperator, PatternParts>,
        con: &AppContext,
    ) -> Result<Self, PatternError> {
        let pattern = Pattern::new(parts_expr, &con.search_modes, con.content_search_max_file_size)?;
        Ok(Self { raw, pattern })
    }
Examples found in repository?
src/pattern/pattern.rs (line 110)
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    pub fn object(&self) -> PatternObject {
        let mut object = PatternObject::default();
        match self {
            Self::None => {}
            Self::NameExact(_) | Self::NameFuzzy(_) | Self::NameRegex(_) | Self::NameTokens(_) => {
                object.name = true;
            }
            Self::PathExact(_) | Self::PathFuzzy(_) | Self::PathRegex(_) | Self::PathTokens(_) => {
                object.subpath = true;
            }
            Self::ContentExact(_) | Self::ContentRegex(_) => {
                object.content = true;
            }
            Self::Composite(cp) => {
                for atom in cp.expr.iter_atoms() {
                    object |= atom.object();
                }
            }
        }
        object
    }
More examples
Hide additional examples
src/stage/stage_state.rs (line 308)
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
    fn display(
        &mut self,
        w: &mut W,
        disc: &DisplayContext,
    ) -> Result<(), ProgramError> {
        let stage = &disc.app_state.stage;
        self.stage_sum.see_stage(stage); // this may invalidate the sum
        if self.filtered_stage.update(stage) {
            self.fix_scroll();
        }
        let area = &disc.state_area;
        let styles = &disc.panel_skin.styles;
        let width = area.width as usize;
        w.queue(cursor::MoveTo(area.left, 0))?;
        let mut cw = CropWriter::new(w, width);
        self.write_title_line(stage, &mut cw, styles)?;
        let list_area = Area::new(area.left, area.top + 1, area.width, area.height - 1);
        self.page_height = list_area.height as usize;
        let pattern = &self.filtered_stage.pattern().pattern;
        let pattern_object = pattern.object();
        let scrollbar = list_area.scrollbar(self.scroll, self.filtered_stage.len());
        for idx in 0..self.page_height {
            let y = list_area.top + idx as u16;
            let stage_idx = idx + self.scroll;
            w.queue(cursor::MoveTo(area.left, y))?;
            let mut cw = CropWriter::new(w, width - 1);
            let cw = &mut cw;
            if let Some((path, selected)) = self.filtered_stage.path_sel(stage, stage_idx) {
                let mut style = if path.is_dir() {
                    &styles.directory
                } else {
                    &styles.file
                };
                let mut bg_style;
                if selected {
                    bg_style = style.clone();
                    if let Some(c) = styles.selected_line.get_bg() {
                        bg_style.set_bg(c);
                    }
                    style = &bg_style;
                }
                let mut bg_style_match;
                let mut style_match = &styles.char_match;
                if selected {
                    bg_style_match = style_match.clone();
                    if let Some(c) = styles.selected_line.get_bg() {
                        bg_style_match.set_bg(c);
                    }
                    style_match = &bg_style_match;
                }
                if disc.con.show_selection_mark && self.filtered_stage.has_selection() {
                    cw.queue_char(style, if selected { '▶' } else { ' ' })?;
                }
                if pattern_object.subpath {
                    let label = path.to_string_lossy();
                    // we must display the matching on the whole path
                    // (subpath is the path for the staging area)
                    let name_match = pattern.search_string(&label);
                    let matched_string = MatchedString::new(
                        name_match,
                        &label,
                        style,
                        style_match,
                    );
                    matched_string.queue_on(cw)?;
                } else if let Some(file_name) = path.file_name() {
                    let label = file_name.to_string_lossy();
                    let label_cols = label.width();
                    if label_cols + 2 < cw.allowed {
                        if let Some(parent_path) = path.parent() {
                            let mut parent_style = &styles.parent;
                            let mut bg_style;
                            if selected {
                                bg_style = parent_style.clone();
                                if let Some(c) = styles.selected_line.get_bg() {
                                    bg_style.set_bg(c);
                                }
                                parent_style = &bg_style;
                            }
                            let cols_max = cw.allowed - label_cols - 3;
                            let parent_path = parent_path.to_string_lossy();
                            let parent_cols = parent_path.width();
                            if parent_cols <= cols_max {
                                cw.queue_str(
                                    parent_style,
                                    &parent_path,
                                )?;
                            } else {
                                // TODO move to (crop_writer ? termimad ?)
                                // we'll compute the size of the tail fitting
                                // the width minus one (for the ellipsis)
                                let mut bytes_count = 0;
                                let mut cols_count = 0;
                                for c in parent_path.chars().rev() {
                                    let char_width = UnicodeWidthChar::width(c).unwrap_or(0);
                                    let next_str_width = cols_count + char_width;
                                    if next_str_width > cols_max {
                                        break;
                                    }
                                    cols_count = next_str_width;
                                    bytes_count += c.len_utf8();
                                }
                                cw.queue_char(
                                    parent_style,
                                    ELLIPSIS,
                                )?;
                                cw.queue_str(
                                    parent_style,
                                    &parent_path[parent_path.len()-bytes_count..],
                                )?;
                            }
                            cw.queue_char(
                                parent_style,
                                '/',
                            )?;
                        }
                    }
                    let name_match = pattern.search_string(&label);
                    let matched_string = MatchedString::new(
                        name_match,
                        &label,
                        style,
                        style_match,
                    );
                    matched_string.queue_on(cw)?;
                } else {
                    // this should not happen
                    warn!("how did we fall on a path without filename?");
                }
                cw.fill(style, &SPACE_FILLING)?;
            }
            cw.fill(&styles.default, &SPACE_FILLING)?;
            let scrollbar_style = if ScrollCommand::is_thumb(y, scrollbar) {
                &styles.scrollbar_thumb
            } else {
                &styles.scrollbar_track
            };
            scrollbar_style.queue_str(w, "▐")?;
        }
        Ok(())
    }
src/display/displayable_tree.rs (line 474)
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
    pub fn write_on<W: Write>(&self, f: &mut W) -> Result<(), ProgramError> {
        #[cfg(not(any(target_family = "windows", target_os = "android")))]
        let perm_writer = super::PermWriter::for_tree(self.skin, self.tree);

        let tree = self.tree;
        let total_size = tree.total_sum();
        let scrollbar = if self.in_app {
            termimad::compute_scrollbar(
                tree.scroll,
                tree.lines.len() - 1, // the root line isn't scrolled
                self.area.height - 1, // the scrollbar doesn't cover the first line
                self.area.top + 1,
            )
        } else {
            None
        };
        if self.in_app {
            f.queue(cursor::MoveTo(self.area.left, self.area.top))?;
        }
        let mut cw = CropWriter::new(f, self.area.width as usize);
        let pattern_object = tree.options.pattern.pattern.object();
        self.write_root_line(&mut cw, self.in_app && tree.selection == 0)?;
        self.skin.queue_reset(f)?;

        let visible_cols: Vec<Col> = tree
            .options
            .cols_order
            .iter()
            .filter(|col| col.is_visible(tree, self.app_state))
            .cloned()
            .collect();

        // if necessary we compute the width of the count column
        let count_len = if tree.options.show_counts {
            tree.lines.iter()
                .skip(1) // we don't show the counts of the root
                .map(|l| l.sum.map_or(0, |s| s.to_count()))
                .max()
                .map(|c| format_count(c).len())
                .unwrap_or(0)
        } else {
            0
        };

        // we compute the length of the dates, depending on the format
        let date_len = if tree.options.show_dates {
            let date_time: DateTime<Local> = Local::now();
            date_time.format(tree.options.date_time_format).to_string().len()
        } else {
            0 // we don't care
        };

        for y in 1..self.area.height {
            if self.in_app {
                f.queue(cursor::MoveTo(self.area.left, y + self.area.top))?;
            } else {
                write!(f, "\r\n")?;
            }
            let mut line_index = y as usize;
            if line_index > 0 {
                line_index += tree.scroll as usize;
            }
            let mut selected = false;
            let mut cw = CropWriter::new(f, self.area.width as usize);
            let cw = &mut cw;
            if line_index < tree.lines.len() {
                let line = &tree.lines[line_index];
                selected = self.in_app && line_index == tree.selection;
                let label_style = self.label_style(line, selected);
                let mut in_branch = false;
                let space_style = if selected {
                    &self.skin.selected_line
                } else {
                    &self.skin.default
                };
                if visible_cols[0].needs_left_margin() {
                    cw.queue_char(space_style, ' ')?;
                }
                let staged = self.app_state
                    .map_or(false, |a| a.stage.contains(&line.path));
                for col in &visible_cols {
                    let void_len = match col {

                        Col::Mark => {
                            self.write_line_selection_mark(cw, &label_style, selected)?
                        }

                        Col::Git => {
                            self.write_line_git_status(cw, line, selected)?
                        }

                        Col::Branch => {
                            in_branch = true;
                            self.write_branch(cw, line_index, line, selected, staged)?
                        }

                        Col::DeviceId => {
                            #[cfg(not(unix))]
                            { 0 }

                            #[cfg(unix)]
                            self.write_line_device_id(cw, line, selected)?
                        }

                        Col::Permission => {
                            #[cfg(any(target_family = "windows", target_os = "android"))]
                            { 0 }

                            #[cfg(not(any(target_family = "windows", target_os = "android")))]
                            perm_writer.write_permissions(cw, line, selected)?
                        }

                        Col::Date => {
                            if let Some(seconds) = line.sum.and_then(|sum| sum.to_valid_seconds()) {
                                self.write_date(cw, seconds, selected)?
                            } else {
                                date_len + 1
                            }
                        }

                        Col::Size => {
                            if tree.options.sort.prevent_deep_display() {
                                // as soon as there's only one level displayed we can show the size bars
                                self.write_line_size_with_bar(cw, line, &label_style, total_size, selected)?
                            } else {
                                self.write_line_size(cw, line, &label_style, selected)?
                            }
                        }

                        Col::Count => {
                            self.write_line_count(cw, line, count_len, selected)?
                        }

                        Col::Staged => {
                            self.write_line_stage_mark(cw, &label_style, staged)?
                        }

                        Col::Name => {
                            in_branch = false;
                            self.write_line_label(cw, line, &label_style, pattern_object, selected)?
                        }

                    };
                    // void: intercol & replacing missing cells
                    if in_branch && void_len > 2 {
                        cond_bg!(void_style, self, selected, self.skin.tree);
                        cw.repeat(void_style, &BRANCH_FILLING, void_len)?;
                    } else {
                        cond_bg!(void_style, self, selected, self.skin.default);
                        cw.repeat(void_style, &SPACE_FILLING, void_len)?;
                    }
                }

                if cw.allowed > 8 && pattern_object.content {
                    let extract = tree.options.pattern.pattern
                        .search_content(&line.path, cw.allowed - 2);
                    if let Some(extract) = extract {
                        self.write_content_extract(cw, extract, selected)?;
                    }
                }
            }
            self.extend_line_bg(cw, selected)?;
            self.skin.queue_reset(f)?;
            if self.in_app {
                if let Some((sctop, scbottom)) = scrollbar {
                    f.queue(cursor::MoveTo(self.area.left + self.area.width - 1, y))?;
                    let style = if sctop <= y && y <= scbottom {
                        &self.skin.scrollbar_thumb
                    } else {
                        &self.skin.scrollbar_track
                    };
                    style.queue_str(f, "▐")?;
                }
            }
        }
        if !self.in_app {
            write!(f, "\r\n")?;
        }
        Ok(())
    }
Examples found in repository?
src/help/help_verbs.rs (line 56)
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
pub fn matching_verb_rows<'v>(
    pat: &Pattern,
    con: &'v AppContext,
) -> Vec<MatchingVerbRow<'v>> {
    let mut rows = Vec::new();
    for verb in &con.verb_store.verbs {
        if !verb.show_in_doc {
            continue;
        }
        let mut name = None;
        let mut shortcut = None;
        if pat.is_some() {
            let mut ok = false;
            name = verb.names.get(0).and_then(|s| {
                pat.search_string(s).map(|nm| {
                    ok = true;
                    nm.wrap(s, "**", "**")
                })
            });
            shortcut = verb.names.get(1).and_then(|s| {
                pat.search_string(s).map(|nm| {
                    ok = true;
                    nm.wrap(s, "**", "**")
                })
            });
            if !ok {
                continue;
            }
        }
        rows.push(MatchingVerbRow {
            name,
            shortcut,
            verb,
        });
    }
    rows
}
More examples
Hide additional examples
src/pattern/composite_pattern.rs (line 91)
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    pub fn search_string(&self, candidate: &str) -> Option<NameMatch> {
        // an ideal algorithm would call score_of on patterns when the object is different
        // to deal with exclusions but I'll start today with something simpler
        use PatternOperator::*;
        let composite_result: Option<Option<NameMatch>> = self.expr.eval(
            // score evaluation
            |pat| pat.search_string(candidate),
            // operator
            |op, a, b| match (op, a, b) {
                (Not, Some(_), _) => None,
                (_, Some(ma), _) => Some(ma),
                (_, None, Some(omb)) => omb,
                _ => None,
            },
            |op, a| match (op, a) {
                (Or, Some(_)) => true,
                _ => false,
            },
        );
        // it's possible we didn't find a result because the composition
        composite_result
            .unwrap_or_else(||{
                warn!("unexpectedly missing result ");
                None
            })
    }
src/display/displayable_tree.rs (line 312)
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
    fn write_line_label<'w, W: Write>(
        &self,
        cw: &mut CropWriter<'w, W>,
        line: &TreeLine,
        style: &CompoundStyle,
        pattern_object: PatternObject,
        selected: bool,
    ) -> Result<usize, ProgramError> {
        cond_bg!(char_match_style, self, selected, self.skin.char_match);
        if let Some(icon) = line.icon {
            cw.queue_char(style, icon)?;
            cw.queue_char(style, ' ')?;
            cw.queue_char(style, ' ')?;
        }
        if pattern_object.subpath {
            if self.tree.options.show_matching_characters_on_path_searches && line.unlisted == 0 {
                let name_match = self.tree.options.pattern.pattern
                    .search_string(&line.subpath);
                let mut path_ms = MatchedString::new(
                    name_match,
                    &line.subpath,
                    style,
                    char_match_style,
                );
                let name_ms = path_ms.split_on_last('/');
                cond_bg!(parent_style, self, selected, self.skin.parent);
                if name_ms.is_some() {
                    path_ms.base_style = parent_style;
                }
                path_ms.queue_on(cw)?;
                if let Some(name_ms) = name_ms {
                    name_ms.queue_on(cw)?;
                }
            } else {
                cw.queue_str(style, &line.name)?;
            }
        } else {
            let name_match = self.tree.options.pattern.pattern
                .search_string(&line.name);
            let matched_string = MatchedString::new(
                name_match,
                &line.name,
                style,
                char_match_style,
            );
            matched_string.queue_on(cw)?;
        }
        match &line.line_type {
            TreeLineType::Dir => {
                if line.unlisted > 0 {
                    cw.queue_str(style, " …")?;
                }
            }
            TreeLineType::BrokenSymLink(direct_path) => {
                cw.queue_str(style, " -> ")?;
                cond_bg!(error_style, self, selected, self.skin.file_error);
                cw.queue_str(error_style, direct_path)?;
            }
            TreeLineType::SymLink {
                final_is_dir,
                direct_target,
                ..
            } => {
                cw.queue_str(style, " -> ")?;
                let target_style = if *final_is_dir {
                    &self.skin.directory
                } else {
                    &self.skin.file
                };
                cond_bg!(target_style, self, selected, target_style);
                cw.queue_str(target_style, direct_target)?;
            }
            _ => {}
        }
        Ok(1)
    }
src/syntactic/syntactic_view.rs (line 150)
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    fn read_lines(
        &mut self,
        dam: &mut Dam,
        con: &AppContext,
        no_style: bool,
    ) -> Result<bool, ProgramError> {
        let f = File::open(&self.path)?;
        {
            // if we detect the file isn't mappable, we'll
            // let the ZeroLenFilePreview try to read it
            let mmap = unsafe { Mmap::map(&f) };
            if mmap.is_err() {
                return Err(ProgramError::UnmappableFile);
            }
        }
        let md = f.metadata()?;
        if md.len() == 0 {
            return Err(ProgramError::ZeroLenFile);
        }
        let with_style = !no_style && md.len() < MAX_SIZE_FOR_STYLING;
        let mut reader = BufReader::new(f);
        self.lines.clear();
        let mut line = String::new();
        self.total_lines_count = 0;
        let mut offset = 0;
        let mut number = 0;
        static SYNTAXER: Lazy<Syntaxer> = Lazy::new(Syntaxer::default);
        let mut highlighter = if with_style {
            SYNTAXER.highlighter_for(&self.path, con)
        } else {
            None
        };
        let pattern = &self.pattern.pattern;
        while reader.read_line(&mut line)? > 0 {
            number += 1;
            self.total_lines_count += 1;
            let start = offset;
            offset += line.len();
            for c in line.chars() {
                if !is_char_printable(c) {
                    debug!("unprintable char: {:?}", c);
                    return Err(ProgramError::UnprintableFile);
                }
            }
            // We don't remove '\n' or '\r' at this point because some syntax sets
            // need them for correct detection of comments. See #477
            // Those chars are removed on printing
            if pattern.is_empty() || pattern.score_of_string(&line).is_some() {
                let name_match = pattern.search_string(&line);
                let regions = if let Some(highlighter) = highlighter.as_mut() {
                    highlighter
                        .highlight(&line, &SYNTAXER.syntax_set)
                        .map_err(|e| ProgramError::SyntectCrashed { details: e.to_string() })?
                        .iter()
                        .map(Region::from_syntect)
                        .collect()
                } else {
                    Vec::new()
                };
                self.lines.push(Line {
                    regions,
                    start,
                    len: line.len(),
                    name_match,
                    number,
                });
            }
            line.clear();
            if dam.has_event() {
                info!("event interrupted preview filtering");
                return Ok(false);
            }
        }
        Ok(true)
    }
src/stage/stage_state.rs (line 346)
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
    fn display(
        &mut self,
        w: &mut W,
        disc: &DisplayContext,
    ) -> Result<(), ProgramError> {
        let stage = &disc.app_state.stage;
        self.stage_sum.see_stage(stage); // this may invalidate the sum
        if self.filtered_stage.update(stage) {
            self.fix_scroll();
        }
        let area = &disc.state_area;
        let styles = &disc.panel_skin.styles;
        let width = area.width as usize;
        w.queue(cursor::MoveTo(area.left, 0))?;
        let mut cw = CropWriter::new(w, width);
        self.write_title_line(stage, &mut cw, styles)?;
        let list_area = Area::new(area.left, area.top + 1, area.width, area.height - 1);
        self.page_height = list_area.height as usize;
        let pattern = &self.filtered_stage.pattern().pattern;
        let pattern_object = pattern.object();
        let scrollbar = list_area.scrollbar(self.scroll, self.filtered_stage.len());
        for idx in 0..self.page_height {
            let y = list_area.top + idx as u16;
            let stage_idx = idx + self.scroll;
            w.queue(cursor::MoveTo(area.left, y))?;
            let mut cw = CropWriter::new(w, width - 1);
            let cw = &mut cw;
            if let Some((path, selected)) = self.filtered_stage.path_sel(stage, stage_idx) {
                let mut style = if path.is_dir() {
                    &styles.directory
                } else {
                    &styles.file
                };
                let mut bg_style;
                if selected {
                    bg_style = style.clone();
                    if let Some(c) = styles.selected_line.get_bg() {
                        bg_style.set_bg(c);
                    }
                    style = &bg_style;
                }
                let mut bg_style_match;
                let mut style_match = &styles.char_match;
                if selected {
                    bg_style_match = style_match.clone();
                    if let Some(c) = styles.selected_line.get_bg() {
                        bg_style_match.set_bg(c);
                    }
                    style_match = &bg_style_match;
                }
                if disc.con.show_selection_mark && self.filtered_stage.has_selection() {
                    cw.queue_char(style, if selected { '▶' } else { ' ' })?;
                }
                if pattern_object.subpath {
                    let label = path.to_string_lossy();
                    // we must display the matching on the whole path
                    // (subpath is the path for the staging area)
                    let name_match = pattern.search_string(&label);
                    let matched_string = MatchedString::new(
                        name_match,
                        &label,
                        style,
                        style_match,
                    );
                    matched_string.queue_on(cw)?;
                } else if let Some(file_name) = path.file_name() {
                    let label = file_name.to_string_lossy();
                    let label_cols = label.width();
                    if label_cols + 2 < cw.allowed {
                        if let Some(parent_path) = path.parent() {
                            let mut parent_style = &styles.parent;
                            let mut bg_style;
                            if selected {
                                bg_style = parent_style.clone();
                                if let Some(c) = styles.selected_line.get_bg() {
                                    bg_style.set_bg(c);
                                }
                                parent_style = &bg_style;
                            }
                            let cols_max = cw.allowed - label_cols - 3;
                            let parent_path = parent_path.to_string_lossy();
                            let parent_cols = parent_path.width();
                            if parent_cols <= cols_max {
                                cw.queue_str(
                                    parent_style,
                                    &parent_path,
                                )?;
                            } else {
                                // TODO move to (crop_writer ? termimad ?)
                                // we'll compute the size of the tail fitting
                                // the width minus one (for the ellipsis)
                                let mut bytes_count = 0;
                                let mut cols_count = 0;
                                for c in parent_path.chars().rev() {
                                    let char_width = UnicodeWidthChar::width(c).unwrap_or(0);
                                    let next_str_width = cols_count + char_width;
                                    if next_str_width > cols_max {
                                        break;
                                    }
                                    cols_count = next_str_width;
                                    bytes_count += c.len_utf8();
                                }
                                cw.queue_char(
                                    parent_style,
                                    ELLIPSIS,
                                )?;
                                cw.queue_str(
                                    parent_style,
                                    &parent_path[parent_path.len()-bytes_count..],
                                )?;
                            }
                            cw.queue_char(
                                parent_style,
                                '/',
                            )?;
                        }
                    }
                    let name_match = pattern.search_string(&label);
                    let matched_string = MatchedString::new(
                        name_match,
                        &label,
                        style,
                        style_match,
                    );
                    matched_string.queue_on(cw)?;
                } else {
                    // this should not happen
                    warn!("how did we fall on a path without filename?");
                }
                cw.fill(style, &SPACE_FILLING)?;
            }
            cw.fill(&styles.default, &SPACE_FILLING)?;
            let scrollbar_style = if ScrollCommand::is_thumb(y, scrollbar) {
                &styles.scrollbar_thumb
            } else {
                &styles.scrollbar_track
            };
            scrollbar_style.queue_str(w, "▐")?;
        }
        Ok(())
    }
src/filesystems/filesystems_state.rs (line 371)
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
    fn display(
        &mut self,
        w: &mut W,
        disc: &DisplayContext,
    ) -> Result<(), ProgramError> {
        let area = &disc.state_area;
        let con = &disc.con;
        self.page_height = area.height as usize - 2;
        let (mounts, selection_idx) = if let Some(filtered) = &self.filtered {
            (filtered.mounts.as_slice(), filtered.selection_idx)
        } else {
            (self.mounts.as_slice(), self.selection_idx)
        };
        let scrollbar = area.scrollbar(self.scroll, mounts.len());
        //- style preparation
        let styles = &disc.panel_skin.styles;
        let selection_bg = styles.selected_line.get_bg()
            .unwrap_or(Color::AnsiValue(240));
        let match_style = &styles.char_match;
        let mut selected_match_style = styles.char_match.clone();
        selected_match_style.set_bg(selection_bg);
        let border_style = &styles.help_table_border;
        let mut selected_border_style = styles.help_table_border.clone();
        selected_border_style.set_bg(selection_bg);
        //- width computations and selection of columns to display
        let width = area.width as usize;
        let w_fs = mounts.iter()
            .map(|m| m.info.fs.chars().count())
            .max().unwrap_or(0)
            .max("filesystem".len());
        let mut wc_fs = w_fs; // width of the column (may include selection mark)
        if con.show_selection_mark {
            wc_fs += 1;
        }
        let w_dsk = 5; // max width of a lfs-core disk type
        let w_type = mounts.iter()
            .map(|m| m.info.fs_type.chars().count())
            .max().unwrap_or(0)
            .max("type".len());
        let w_size = 4;
        let w_use = 4;
        let mut w_use_bar = 1; // min size, may grow if space available
        let w_use_share = 4;
        let mut wc_use = w_use; // sum of all the parts of the usage column
        let w_free = 4;
        let w_mount_point = mounts.iter()
            .map(|m| m.info.mount_point.to_string_lossy().chars().count())
            .max().unwrap_or(0)
            .max("mount point".len());
        let w_mandatory = wc_fs + 1 + w_size + 1 + w_free + 1 + w_mount_point;
        let mut e_dsk = false;
        let mut e_type = false;
        let mut e_use_bar = false;
        let mut e_use_share = false;
        let mut e_use = false;
        if w_mandatory + 1 < width {
            let mut rem = width - w_mandatory - 1;
            if rem > w_use {
                rem -= w_use + 1;
                e_use = true;
            }
            if e_use && rem > w_use_share {
                rem -= w_use_share; // no separation with use
                e_use_share = true;
                wc_use += w_use_share;
            }
            if rem > w_dsk {
                rem -= w_dsk + 1;
                e_dsk = true;
            }
            if e_use && rem > w_use_bar {
                rem -= w_use_bar + 1;
                e_use_bar = true;
                wc_use += w_use_bar + 1;
            }
            if rem > w_type {
                rem -= w_type + 1;
                e_type = true;
            }
            if e_use_bar && rem > 0 {
                let incr = rem.min(9);
                w_use_bar += incr;
                wc_use += incr;
            }
        }
        //- titles
        w.queue(cursor::MoveTo(area.left, area.top))?;
        let mut cw = CropWriter::new(w, width);
        cw.queue_g_string(&styles.default, format!("{:wc_fs$}", "filesystem"))?;
        cw.queue_char(border_style, '│')?;
        if e_dsk {
            cw.queue_g_string(&styles.default, "disk ".to_string())?;
            cw.queue_char(border_style, '│')?;
        }
        if e_type {
            cw.queue_g_string(&styles.default, format!("{:^w_type$}", "type"))?;
            cw.queue_char(border_style, '│')?;
        }
        if e_use {
            cw.queue_g_string(&styles.default, format!(
                "{:^width$}", if wc_use > 4 { "usage" } else { "use" }, width = wc_use
            ))?;
            cw.queue_char(border_style, '│')?;
        }
        cw.queue_g_string(&styles.default, "free".to_string())?;
        cw.queue_char(border_style, '│')?;
        cw.queue_g_string(&styles.default, "size".to_string())?;
        cw.queue_char(border_style, '│')?;
        cw.queue_g_string(&styles.default, "mount point".to_string())?;
        cw.fill(border_style, &SPACE_FILLING)?;
        //- horizontal line
        w.queue(cursor::MoveTo(area.left, 1 + area.top))?;
        let mut cw = CropWriter::new(w, width);
        cw.queue_g_string(border_style, format!("{:─>width$}", '┼', width = wc_fs + 1))?;
        if e_dsk {
            cw.queue_g_string(border_style, format!("{:─>width$}", '┼', width = w_dsk + 1))?;
        }
        if e_type {
            cw.queue_g_string(border_style, format!("{:─>width$}", '┼', width = w_type+1))?;
        }
        cw.queue_g_string(border_style, format!("{:─>width$}", '┼', width = w_size+1))?;
        if e_use {
            cw.queue_g_string(border_style, format!("{:─>width$}", '┼', width = wc_use+1))?;
        }
        cw.queue_g_string(border_style, format!("{:─>width$}", '┼', width = w_free+1))?;
        cw.fill(border_style, &BRANCH_FILLING)?;
        //- content
        let mut idx = self.scroll as usize;
        for y in 2..area.height {
            w.queue(cursor::MoveTo(area.left, y + area.top))?;
            let selected = selection_idx == idx;
            let mut cw = CropWriter::new(w, width - 1); // -1 for scrollbar
            let txt_style = if selected { &styles.selected_line } else { &styles.default };
            if let Some(mount) = mounts.get(idx) {
                let match_style = if selected { &selected_match_style } else { match_style };
                let border_style = if selected { &selected_border_style } else { border_style };
                if con.show_selection_mark {
                    cw.queue_char(txt_style, if selected { '▶' } else { ' ' })?;
                }
                // fs
                let s = &mount.info.fs;
                let mut matched_string = MatchedString::new(
                    self.filtered.as_ref().and_then(|f| f.pattern.search_string(s)),
                    s,
                    txt_style,
                    match_style,
                );
                matched_string.fill(w_fs, Alignment::Left);
                matched_string.queue_on(&mut cw)?;
                cw.queue_char(border_style, '│')?;
                // dsk
                if e_dsk {
                    if let Some(disk) = mount.disk.as_ref() {
                        let s = disk.disk_type();
                        let mut matched_string = MatchedString::new(
                            self.filtered.as_ref().and_then(|f| f.pattern.search_string(s)),
                            s,
                            txt_style,
                            match_style,
                        );
                        matched_string.fill(5, Alignment::Center);
                        matched_string.queue_on(&mut cw)?;
                    } else {
                        cw.queue_g_string(txt_style, "     ".to_string())?;
                    }
                    cw.queue_char(border_style, '│')?;
                }
                // type
                if e_type {
                    let s = &mount.info.fs_type;
                    let mut matched_string = MatchedString::new(
                        self.filtered.as_ref().and_then(|f| f.pattern.search_string(s)),
                        s,
                        txt_style,
                        match_style,
                    );
                    matched_string.fill(w_type, Alignment::Center);
                    matched_string.queue_on(&mut cw)?;
                    cw.queue_char(border_style, '│')?;
                }
                // size, used, free
                if let Some(stats) = mount.stats().filter(|s| s.size() > 0) {
                    let share_color = super::share_color(stats.use_share());
                    // used
                    if e_use {
                        cw.queue_g_string(txt_style, format!("{:>4}", file_size::fit_4(stats.used())))?;
                        if e_use_share {
                            cw.queue_g_string(txt_style, format!("{:>3.0}%", 100.0*stats.use_share()))?;
                        }
                        if e_use_bar {
                            cw.queue_char(txt_style, ' ')?;
                            let pb = ProgressBar::new(stats.use_share() as f32, w_use_bar);
                            let mut bar_style = styles.default.clone();
                            bar_style.set_bg(share_color);
                            cw.queue_g_string(&bar_style, format!("{:<width$}", pb, width=w_use_bar))?;
                        }
                        cw.queue_char(border_style, '│')?;
                    }
                    // free
                    let mut share_style = txt_style.clone();
                    share_style.set_fg(share_color);
                    cw.queue_g_string(&share_style, format!("{:>4}", file_size::fit_4(stats.available())))?;
                    cw.queue_char(border_style, '│')?;
                    // size
                    if let Some(stats) = mount.stats() {
                        cw.queue_g_string(txt_style, format!("{:>4}", file_size::fit_4(stats.size())))?;
                    } else {
                        cw.repeat(txt_style, &SPACE_FILLING, 4)?;
                    }
                    cw.queue_char(border_style, '│')?;
                } else {
                    // used
                    if e_use {
                        cw.repeat(txt_style, &SPACE_FILLING, wc_use)?;
                        cw.queue_char(border_style, '│')?;
                    }
                    // free
                    cw.repeat(txt_style, &SPACE_FILLING, w_free)?;
                    cw.queue_char(border_style, '│')?;
                    // size
                    cw.repeat(txt_style, &SPACE_FILLING, w_size)?;
                    cw.queue_char(border_style, '│')?;
                }
                // mount point
                let s = &mount.info.mount_point.to_string_lossy();
                let matched_string = MatchedString::new(
                    self.filtered.as_ref().and_then(|f| f.pattern.search_string(s)),
                    s,
                    txt_style,
                    match_style,
                );
                matched_string.queue_on(&mut cw)?;
                idx += 1;
            }
            cw.fill(txt_style, &SPACE_FILLING)?;
            let scrollbar_style = if ScrollCommand::is_thumb(y, scrollbar) {
                &styles.scrollbar_thumb
            } else {
                &styles.scrollbar_track
            };
            scrollbar_style.queue_str(w, "▐")?;
        }
        Ok(())
    }

find the content to show next to the name of the file when the search involved a content filtering

Examples found in repository?
src/pattern/composite_pattern.rs (line 120)
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    pub fn search_content(
        &self,
        candidate: &Path,
        desired_len: usize, // available space for content match display
    ) -> Option<ContentMatch> {
        use PatternOperator::*;
        let composite_result: Option<Option<ContentMatch>> = self.expr.eval(
            // score evaluation
            |pat| pat.search_content(candidate, desired_len),
            // operator
            |op, a, b| match (op, a, b) {
                (Not, Some(_), _) => None,
                (_, Some(ma), _) => Some(ma),
                (_, None, Some(omb)) => omb,
                _ => None,
            },
            |op, a| match (op, a) {
                (Or, Some(_)) => true,
                _ => false,
            },
        );
        composite_result
            .unwrap_or_else(||{
                warn!("unexpectedly missing result ");
                None
            })
    }
More examples
Hide additional examples
src/display/displayable_tree.rs (line 609)
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
    pub fn write_on<W: Write>(&self, f: &mut W) -> Result<(), ProgramError> {
        #[cfg(not(any(target_family = "windows", target_os = "android")))]
        let perm_writer = super::PermWriter::for_tree(self.skin, self.tree);

        let tree = self.tree;
        let total_size = tree.total_sum();
        let scrollbar = if self.in_app {
            termimad::compute_scrollbar(
                tree.scroll,
                tree.lines.len() - 1, // the root line isn't scrolled
                self.area.height - 1, // the scrollbar doesn't cover the first line
                self.area.top + 1,
            )
        } else {
            None
        };
        if self.in_app {
            f.queue(cursor::MoveTo(self.area.left, self.area.top))?;
        }
        let mut cw = CropWriter::new(f, self.area.width as usize);
        let pattern_object = tree.options.pattern.pattern.object();
        self.write_root_line(&mut cw, self.in_app && tree.selection == 0)?;
        self.skin.queue_reset(f)?;

        let visible_cols: Vec<Col> = tree
            .options
            .cols_order
            .iter()
            .filter(|col| col.is_visible(tree, self.app_state))
            .cloned()
            .collect();

        // if necessary we compute the width of the count column
        let count_len = if tree.options.show_counts {
            tree.lines.iter()
                .skip(1) // we don't show the counts of the root
                .map(|l| l.sum.map_or(0, |s| s.to_count()))
                .max()
                .map(|c| format_count(c).len())
                .unwrap_or(0)
        } else {
            0
        };

        // we compute the length of the dates, depending on the format
        let date_len = if tree.options.show_dates {
            let date_time: DateTime<Local> = Local::now();
            date_time.format(tree.options.date_time_format).to_string().len()
        } else {
            0 // we don't care
        };

        for y in 1..self.area.height {
            if self.in_app {
                f.queue(cursor::MoveTo(self.area.left, y + self.area.top))?;
            } else {
                write!(f, "\r\n")?;
            }
            let mut line_index = y as usize;
            if line_index > 0 {
                line_index += tree.scroll as usize;
            }
            let mut selected = false;
            let mut cw = CropWriter::new(f, self.area.width as usize);
            let cw = &mut cw;
            if line_index < tree.lines.len() {
                let line = &tree.lines[line_index];
                selected = self.in_app && line_index == tree.selection;
                let label_style = self.label_style(line, selected);
                let mut in_branch = false;
                let space_style = if selected {
                    &self.skin.selected_line
                } else {
                    &self.skin.default
                };
                if visible_cols[0].needs_left_margin() {
                    cw.queue_char(space_style, ' ')?;
                }
                let staged = self.app_state
                    .map_or(false, |a| a.stage.contains(&line.path));
                for col in &visible_cols {
                    let void_len = match col {

                        Col::Mark => {
                            self.write_line_selection_mark(cw, &label_style, selected)?
                        }

                        Col::Git => {
                            self.write_line_git_status(cw, line, selected)?
                        }

                        Col::Branch => {
                            in_branch = true;
                            self.write_branch(cw, line_index, line, selected, staged)?
                        }

                        Col::DeviceId => {
                            #[cfg(not(unix))]
                            { 0 }

                            #[cfg(unix)]
                            self.write_line_device_id(cw, line, selected)?
                        }

                        Col::Permission => {
                            #[cfg(any(target_family = "windows", target_os = "android"))]
                            { 0 }

                            #[cfg(not(any(target_family = "windows", target_os = "android")))]
                            perm_writer.write_permissions(cw, line, selected)?
                        }

                        Col::Date => {
                            if let Some(seconds) = line.sum.and_then(|sum| sum.to_valid_seconds()) {
                                self.write_date(cw, seconds, selected)?
                            } else {
                                date_len + 1
                            }
                        }

                        Col::Size => {
                            if tree.options.sort.prevent_deep_display() {
                                // as soon as there's only one level displayed we can show the size bars
                                self.write_line_size_with_bar(cw, line, &label_style, total_size, selected)?
                            } else {
                                self.write_line_size(cw, line, &label_style, selected)?
                            }
                        }

                        Col::Count => {
                            self.write_line_count(cw, line, count_len, selected)?
                        }

                        Col::Staged => {
                            self.write_line_stage_mark(cw, &label_style, staged)?
                        }

                        Col::Name => {
                            in_branch = false;
                            self.write_line_label(cw, line, &label_style, pattern_object, selected)?
                        }

                    };
                    // void: intercol & replacing missing cells
                    if in_branch && void_len > 2 {
                        cond_bg!(void_style, self, selected, self.skin.tree);
                        cw.repeat(void_style, &BRANCH_FILLING, void_len)?;
                    } else {
                        cond_bg!(void_style, self, selected, self.skin.default);
                        cw.repeat(void_style, &SPACE_FILLING, void_len)?;
                    }
                }

                if cw.allowed > 8 && pattern_object.content {
                    let extract = tree.options.pattern.pattern
                        .search_content(&line.path, cw.allowed - 2);
                    if let Some(extract) = extract {
                        self.write_content_extract(cw, extract, selected)?;
                    }
                }
            }
            self.extend_line_bg(cw, selected)?;
            self.skin.queue_reset(f)?;
            if self.in_app {
                if let Some((sctop, scbottom)) = scrollbar {
                    f.queue(cursor::MoveTo(self.area.left + self.area.width - 1, y))?;
                    let style = if sctop <= y && y <= scbottom {
                        &self.skin.scrollbar_thumb
                    } else {
                        &self.skin.scrollbar_track
                    };
                    style.queue_str(f, "▐")?;
                }
            }
        }
        if !self.in_app {
            write!(f, "\r\n")?;
        }
        Ok(())
    }

get the line of the first match, if any

Examples found in repository?
src/browser/browser_state.rs (line 230)
226
227
228
229
230
231
232
233
    fn selection(&self) -> Option<Selection<'_>> {
        let tree = self.displayed_tree();
        let mut selection = tree.selected_line().as_selection();
        selection.line = tree.options.pattern.pattern
            .get_match_line_count(selection.path)
            .unwrap_or(0);
        Some(selection)
    }
More examples
Hide additional examples
src/pattern/composite_pattern.rs (line 147)
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    pub fn get_match_line_count(
        &self,
        candidate: &Path,
    ) -> Option<usize> {
        use PatternOperator::*;
        let composite_result: Option<Option<usize>> = self.expr.eval(
            // score evaluation
            |pat| pat.get_match_line_count(candidate),
            // operator
            |op, a, b| match (op, a, b) {
                (Not, Some(_), _) => None,
                (_, Some(ma), _) => Some(ma),
                (_, None, Some(omb)) => omb,
                _ => None,
            },
            |op, a| match (op, a) {
                (Or, Some(_)) => true,
                _ => false,
            },
        );
        composite_result
            .unwrap_or_else(||{
                warn!("unexpectedly missing result ");
                None
            })
    }
Examples found in repository?
src/pattern/composite_pattern.rs (line 57)
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    pub fn score_of(&self, candidate: Candidate) -> Option<i32> {
        use PatternOperator::*;
        let composite_result: Option<Option<i32>> = self.expr.eval(
            // score evaluation
            |pat| pat.score_of(candidate),
            // operator
            |op, a, b| {
                match (op, a, b) {
                    (And, None, _) => None, // normally not called due to short-circuit
                    (And, Some(sa), Some(Some(sb))) => Some(sa + sb),
                    (Or, None, Some(Some(sb))) => Some(sb),
                    (Or, Some(sa), Some(None)) => Some(sa),
                    (Or, Some(sa), Some(Some(sb))) => Some(sa + sb),
                    (Not, Some(_), _) => None,
                    (Not, None, _) => Some(1),
                    _ => None,
                }
            },
            // short-circuit. We don't short circuit on 'or' because
            // we want to use both scores
            |op, a| match (op, a) {
                (And, None) => true,
                _ => false,
            },
        );
        composite_result
            .unwrap_or_else(||{
                warn!("unexpectedly missing result ");
                None
            })
    }
More examples
Hide additional examples
src/stage/filtered_stage.rs (line 45)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
    fn compute(&mut self, stage: &Stage) {
        if self.pattern.is_none() {
            self.paths_idx = stage.paths().iter()
                .enumerate()
                .map(|(idx, _)| idx)
                .collect();
        } else {
            let mut best_score = None;
            self.paths_idx.clear();
            for (idx, path) in stage.paths().iter().enumerate() {
                if let Some(file_name) = path.file_name() {
                    let subpath = path.to_string_lossy().to_string();
                    let name = file_name.to_string_lossy().to_string();
                    let regular_file = path.is_file();
                    let candidate = Candidate {
                        path,
                        subpath: &subpath,
                        name: &name,
                        regular_file,
                    };
                    if let Some(score) = self.pattern.pattern.score_of(candidate) {
                        let is_best = match best_score {
                            Some(old_score) if old_score < score => true,
                            None => true,
                            _ => false,
                        };
                        if is_best {
                            self.selection = Some(self.paths_idx.len());
                            best_score = Some(score);
                        }
                        self.paths_idx.push(idx);
                    }
                }
            }
        }
    }
src/tree_build/builder.rs (line 155)
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    fn make_line(
        &mut self,
        parent_id: BId,
        e: &fs::DirEntry,
        depth: u16,
    ) -> Option<BLine> {
        let name = e.file_name();
        if name.is_empty() {
            self.report.error_count += 1;
            return None;
        }
        if !self.options.show_hidden && name.as_bytes()[0] == b'.' {
            self.report.hidden_count += 1;
            return None;
        }
        let name = name.to_string_lossy();
        let mut has_match = true;
        let mut score = 10000 - i32::from(depth); // we dope less deep entries
        let path = e.path();
        let file_type = match e.file_type() {
            Ok(ft) => ft,
            Err(_) => {
                self.report.error_count += 1;
                return None;
            }
        };
        let parent_subpath = &self.blines[parent_id].subpath;
        let subpath = if !parent_subpath.is_empty() {
            format!("{}/{}", parent_subpath, &name)
        } else {
            name.to_string()
        };
        let candidate = Candidate {
            name: &name,
            subpath: &subpath,
            path: &path,
            regular_file: file_type.is_file(),
        };
        let direct_match = if let Some(pattern_score) = self.options.pattern.pattern.score_of(candidate) {
            // we dope direct matches to compensate for depth doping of parent folders
            score += pattern_score + 10;
            true
        } else {
            has_match = false;
            false
        };
        let name = name.to_string();
        if has_match && self.options.filter_by_git_status {
            if let Some(line_status_computer) = &self.line_status_computer {
                if !line_status_computer.is_interesting(&path) {
                    has_match = false;
                }
            }
        }
        if file_type.is_file() {
            if !has_match {
                return None;
            }
            if self.options.only_folders {
                return None;
            }
        }
        let special_handling = self.con.special_paths.find(&path);
        if special_handling == SpecialHandling::Hide {
            return None;
        }
        if self.options.respect_git_ignore {
            let parent_chain = &self.blines[parent_id].git_ignore_chain;
            if !self
                .git_ignorer
                .accepts(parent_chain, &path, &name, file_type.is_dir())
            {
                return None;
            }
        };
        Some(BLine {
            parent_id: Some(parent_id),
            path,
            depth,
            subpath,
            name,
            file_type,
            children: None,
            next_child_idx: 0,
            has_error: false,
            has_match,
            direct_match,
            score,
            nb_kept_children: 0,
            git_ignore_chain: GitIgnoreChain::default(),
            special_handling,
        })
    }
Examples found in repository?
src/filesystems/filesystems_state.rs (line 210)
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    fn on_pattern(
        &mut self,
        pattern: InputPattern,
        _app_state: &AppState,
        _con: &AppContext,
    ) -> Result<CmdResult, ProgramError> {
        if pattern.is_none() {
            self.filtered = None;
        } else {
            let mut selection_idx = 0;
            let mut mounts = Vec::new();
            let pattern = pattern.pattern;
            for (idx, mount) in self.mounts.iter().enumerate() {
                if pattern.score_of_string(&mount.info.fs).is_none()
                    && mount.disk.as_ref().and_then(|d| pattern.score_of_string(d.disk_type())).is_none()
                    && pattern.score_of_string(&mount.info.fs_type).is_none()
                    && pattern.score_of_string(&mount.info.mount_point.to_string_lossy()).is_none()
                { continue; }
                if idx <= self.selection_idx {
                    selection_idx = mounts.len();
                }
                mounts.push(mount.clone());
            }
            self.filtered = Some(FilteredContent {
                pattern,
                mounts,
                selection_idx,
            });
        }
        Ok(CmdResult::Keep)
    }
More examples
Hide additional examples
src/pattern/composite_pattern.rs (line 25)
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    pub fn score_of_string(&self, candidate: &str) -> Option<i32> {
        use PatternOperator::*;
        let composite_result: Option<Option<i32>> = self.expr.eval(
            // score evaluation
            |pat| pat.score_of_string(candidate),
            // operator
            |op, a, b| {
                match (op, a, b) {
                    (And, None, _) => None, // normally not called due to short-circuit
                    (And, Some(sa), Some(Some(sb))) => Some(sa + sb),
                    (Or, None, Some(Some(sb))) => Some(sb),
                    (Or, Some(sa), Some(None)) => Some(sa),
                    (Or, Some(sa), Some(Some(sb))) => Some(sa + sb),
                    (Not, Some(_), _) => None,
                    (Not, None, _) => Some(1),
                    _ => None,
                }
            },
            // short-circuit. We don't short circuit on 'or' because
            // we want to use both scores
            |op, a| match (op, a) {
                (And, None) => true,
                _ => false,
            },
        );
        composite_result
            .unwrap_or_else(||{
                warn!("unexpectedly missing result ");
                None
            })
    }
src/syntactic/syntactic_view.rs (line 149)
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    fn read_lines(
        &mut self,
        dam: &mut Dam,
        con: &AppContext,
        no_style: bool,
    ) -> Result<bool, ProgramError> {
        let f = File::open(&self.path)?;
        {
            // if we detect the file isn't mappable, we'll
            // let the ZeroLenFilePreview try to read it
            let mmap = unsafe { Mmap::map(&f) };
            if mmap.is_err() {
                return Err(ProgramError::UnmappableFile);
            }
        }
        let md = f.metadata()?;
        if md.len() == 0 {
            return Err(ProgramError::ZeroLenFile);
        }
        let with_style = !no_style && md.len() < MAX_SIZE_FOR_STYLING;
        let mut reader = BufReader::new(f);
        self.lines.clear();
        let mut line = String::new();
        self.total_lines_count = 0;
        let mut offset = 0;
        let mut number = 0;
        static SYNTAXER: Lazy<Syntaxer> = Lazy::new(Syntaxer::default);
        let mut highlighter = if with_style {
            SYNTAXER.highlighter_for(&self.path, con)
        } else {
            None
        };
        let pattern = &self.pattern.pattern;
        while reader.read_line(&mut line)? > 0 {
            number += 1;
            self.total_lines_count += 1;
            let start = offset;
            offset += line.len();
            for c in line.chars() {
                if !is_char_printable(c) {
                    debug!("unprintable char: {:?}", c);
                    return Err(ProgramError::UnprintableFile);
                }
            }
            // We don't remove '\n' or '\r' at this point because some syntax sets
            // need them for correct detection of comments. See #477
            // Those chars are removed on printing
            if pattern.is_empty() || pattern.score_of_string(&line).is_some() {
                let name_match = pattern.search_string(&line);
                let regions = if let Some(highlighter) = highlighter.as_mut() {
                    highlighter
                        .highlight(&line, &SYNTAXER.syntax_set)
                        .map_err(|e| ProgramError::SyntectCrashed { details: e.to_string() })?
                        .iter()
                        .map(Region::from_syntect)
                        .collect()
                } else {
                    Vec::new()
                };
                self.lines.push(Line {
                    regions,
                    start,
                    len: line.len(),
                    name_match,
                    number,
                });
            }
            line.clear();
            if dam.has_event() {
                info!("event interrupted preview filtering");
                return Ok(false);
            }
        }
        Ok(true)
    }
Examples found in repository?
src/pattern/input_pattern.rs (line 46)
45
46
47
    pub fn is_some(&self) -> bool {
        self.pattern.is_some()
    }
More examples
Hide additional examples
src/pattern/composite_pattern.rs (line 177)
175
176
177
178
179
    pub fn is_empty(&self) -> bool {
        let is_not_empty = self.expr.iter_atoms()
            .any(|p| p.is_some());
        !is_not_empty
    }
src/help/help_verbs.rs (line 53)
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
pub fn matching_verb_rows<'v>(
    pat: &Pattern,
    con: &'v AppContext,
) -> Vec<MatchingVerbRow<'v>> {
    let mut rows = Vec::new();
    for verb in &con.verb_store.verbs {
        if !verb.show_in_doc {
            continue;
        }
        let mut name = None;
        let mut shortcut = None;
        if pat.is_some() {
            let mut ok = false;
            name = verb.names.get(0).and_then(|s| {
                pat.search_string(s).map(|nm| {
                    ok = true;
                    nm.wrap(s, "**", "**")
                })
            });
            shortcut = verb.names.get(1).and_then(|s| {
                pat.search_string(s).map(|nm| {
                    ok = true;
                    nm.wrap(s, "**", "**")
                })
            });
            if !ok {
                continue;
            }
        }
        rows.push(MatchingVerbRow {
            name,
            shortcut,
            verb,
        });
    }
    rows
}
src/help/help_state.rs (line 214)
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    fn on_internal(
        &mut self,
        w: &mut W,
        internal_exec: &InternalExecution,
        input_invocation: Option<&VerbInvocation>,
        trigger_type: TriggerType,
        app_state: &mut AppState,
        cc: &CmdContext,
    ) -> Result<CmdResult, ProgramError> {
        use Internal::*;
        Ok(match internal_exec.internal {
            Internal::back => {
                if self.pattern.is_some() {
                    self.pattern = Pattern::None;
                    CmdResult::Keep
                } else {
                    CmdResult::PopState
                }
            }
            help => CmdResult::Keep,
            line_down | line_down_no_cycle => {
                self.scroll += get_arg(input_invocation, internal_exec, 1);
                CmdResult::Keep
            }
            line_up | line_up_no_cycle => {
                let dy = get_arg(input_invocation, internal_exec, 1);
                self.scroll = if self.scroll > dy {
                    self.scroll - dy
                } else {
                    0
                };
                CmdResult::Keep
            }
            open_stay => match opener::open(&Conf::default_location()) {
                Ok(exit_status) => {
                    info!("open returned with exit_status {:?}", exit_status);
                    CmdResult::Keep
                }
                Err(e) => CmdResult::DisplayError(format!("{:?}", e)),
            },
            // FIXME check we can't use the generic one
            open_leave => {
                CmdResult::from(Launchable::opener(
                    Conf::default_location()
                ))
            }
            page_down => {
                self.scroll += self.text_area.height as usize;
                CmdResult::Keep
            }
            page_up => {
                let height = self.text_area.height as usize;
                self.scroll = if self.scroll > height {
                    self.scroll - self.text_area.height as usize
                } else {
                    0
                };
                CmdResult::Keep
            }
            _ => self.on_internal_generic(
                w,
                internal_exec,
                input_invocation,
                trigger_type,
                app_state,
                cc,
            )?,
        })
    }

an empty pattern is one which doesn’t discriminate (it accepts everything)

Examples found in repository?
src/pattern/pattern.rs (line 194)
193
194
195
    pub fn is_some(&self) -> bool {
        !self.is_empty()
    }
More examples
Hide additional examples
src/pattern/input_pattern.rs (line 43)
42
43
44
    pub fn is_none(&self) -> bool {
        self.pattern.is_empty()
    }
src/syntactic/syntactic_view.rs (line 149)
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    fn read_lines(
        &mut self,
        dam: &mut Dam,
        con: &AppContext,
        no_style: bool,
    ) -> Result<bool, ProgramError> {
        let f = File::open(&self.path)?;
        {
            // if we detect the file isn't mappable, we'll
            // let the ZeroLenFilePreview try to read it
            let mmap = unsafe { Mmap::map(&f) };
            if mmap.is_err() {
                return Err(ProgramError::UnmappableFile);
            }
        }
        let md = f.metadata()?;
        if md.len() == 0 {
            return Err(ProgramError::ZeroLenFile);
        }
        let with_style = !no_style && md.len() < MAX_SIZE_FOR_STYLING;
        let mut reader = BufReader::new(f);
        self.lines.clear();
        let mut line = String::new();
        self.total_lines_count = 0;
        let mut offset = 0;
        let mut number = 0;
        static SYNTAXER: Lazy<Syntaxer> = Lazy::new(Syntaxer::default);
        let mut highlighter = if with_style {
            SYNTAXER.highlighter_for(&self.path, con)
        } else {
            None
        };
        let pattern = &self.pattern.pattern;
        while reader.read_line(&mut line)? > 0 {
            number += 1;
            self.total_lines_count += 1;
            let start = offset;
            offset += line.len();
            for c in line.chars() {
                if !is_char_printable(c) {
                    debug!("unprintable char: {:?}", c);
                    return Err(ProgramError::UnprintableFile);
                }
            }
            // We don't remove '\n' or '\r' at this point because some syntax sets
            // need them for correct detection of comments. See #477
            // Those chars are removed on printing
            if pattern.is_empty() || pattern.score_of_string(&line).is_some() {
                let name_match = pattern.search_string(&line);
                let regions = if let Some(highlighter) = highlighter.as_mut() {
                    highlighter
                        .highlight(&line, &SYNTAXER.syntax_set)
                        .map_err(|e| ProgramError::SyntectCrashed { details: e.to_string() })?
                        .iter()
                        .map(Region::from_syntect)
                        .collect()
                } else {
                    Vec::new()
                };
                self.lines.push(Line {
                    regions,
                    start,
                    len: line.len(),
                    name_match,
                    number,
                });
            }
            line.clear();
            if dam.has_event() {
                info!("event interrupted preview filtering");
                return Ok(false);
            }
        }
        Ok(true)
    }

whether the scores are more than just 0 or 1. When it’s the case, the tree builder will look for more matching results in order to select the best ones.

Examples found in repository?
src/tree_build/builder.rs (line 279)
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    fn gather_lines(&mut self, total_search: bool, dam: &Dam) -> Result<Vec<BId>, TreeBuildError> {
        let start = Instant::now();
        let mut out_blines: Vec<BId> = Vec::new(); // the blines we want to display
        let optimal_size = if self.options.pattern.pattern.has_real_scores() {
            10 * self.targeted_size
        } else {
            self.targeted_size
        };
        out_blines.push(self.root_id);
        let mut nb_lines_ok = 1; // in out_blines
        let mut open_dirs: VecDeque<BId> = VecDeque::new();
        let mut next_level_dirs: Vec<BId> = Vec::new();
        self.load_children(self.root_id);
        open_dirs.push_back(self.root_id);
        loop {
            if !total_search && (
                (nb_lines_ok > optimal_size)
                || (nb_lines_ok >= self.targeted_size && start.elapsed() > NOT_LONG)
            ) {
                self.total_search = false;
                break;
            }
            if let Some(max) = self.matches_max {
                if nb_lines_ok > max {
                    return Err(TreeBuildError::TooManyMatches{max});
                }
            }
            if let Some(open_dir_id) = open_dirs.pop_front() {
                if let Some(child_id) = self.next_child(open_dir_id) {
                    open_dirs.push_back(open_dir_id);
                    let child = &self.blines[child_id];
                    if child.has_match {
                        nb_lines_ok += 1;
                    }
                    if child.can_enter() {
                        next_level_dirs.push(child_id);
                    }
                    out_blines.push(child_id);
                }
            } else {
                // this depth is finished, we must go deeper
                if self.options.sort.prevent_deep_display() {
                    // in sort mode, only one level is displayed
                    break;
                }
                if next_level_dirs.is_empty() {
                    // except there's nothing deeper
                    break;
                }
                for next_level_dir_id in &next_level_dirs {
                    if dam.has_event() {
                        info!("task expired (core build - inner loop)");
                        return Err(TreeBuildError::Interrupted);
                    }
                    let has_child_match = self.load_children(*next_level_dir_id);
                    if has_child_match {
                        // we must ensure the ancestors are made Ok
                        let mut id = *next_level_dir_id;
                        loop {
                            let mut bline = &mut self.blines[id];
                            if !bline.has_match {
                                bline.has_match = true;
                                nb_lines_ok += 1;
                            }
                            if let Some(pid) = bline.parent_id {
                                id = pid;
                            } else {
                                break;
                            }
                        }
                    }
                    open_dirs.push_back(*next_level_dir_id);
                }
                next_level_dirs.clear();
            }
        }
        if let Some(max) = self.matches_max {
            if nb_lines_ok > max {
                return Err(TreeBuildError::TooManyMatches{max});
            }
        }
        if !self.trim_root {
            // if the root directory isn't totally read, we finished it even
            // it it goes past the bottom of the screen
            while let Some(child_id) = self.next_child(self.root_id) {
                out_blines.push(child_id);
            }
        }
        Ok(out_blines)
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.