1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
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
79
80
81
82
83
84
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
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
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
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
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
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
// src/history.rs
use std::collections::{HashMap, HashSet};
use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Clone, Debug)]
pub struct HistoryEntry {
pub command: String,
pub weight: u32,
pub last_path: String,
pub last_order: u64,
pub is_multi_dir: bool, // 是否在多个目录下运行过
pub is_temp: bool,
}
impl HistoryEntry {
fn new(command: String, path: String, order: u64) -> Self {
Self {
command,
weight: 1,
last_path: path,
last_order: order,
is_multi_dir: false,
is_temp: false,
}
}
}
pub struct History {
entries: Vec<HistoryEntry>, // 按时间顺序(用于 Up/Down 导航)
max_entries: usize,
global_order: u64,
log_path: Option<String>,
current_dir: String, // 当前目录缓存,供搜索和 add 使用
// ── 导航状态 ──
index: Option<usize>,
saved_line: String,
// ── 搜索状态 ──
// search_query: String,
// search_matches: Vec<usize>,
// search_index: usize,
}
impl Default for History {
fn default() -> Self {
Self::new()
}
}
impl History {
pub fn new() -> Self {
Self {
entries: Vec::new(),
max_entries: 1000,
global_order: 0,
log_path: None,
current_dir: String::new(),
index: None,
saved_line: String::new(),
// search_query: String::new(),
// search_matches: Vec::new(),
// search_index: 0,
}
}
/// 更新当前目录缓存。
/// 在每次命令执行后(parse_and_eval 之后)调用,确保 add 使用最新路径。
pub fn set_current_dir(&mut self, path: String) {
self.current_dir = path;
}
#[inline]
pub fn current_dir(&self) -> &str {
&self.current_dir
}
pub fn add_tmp(&mut self, entry: String) {
if entry.trim().is_empty() {
return;
}
self.global_order += 1;
let order = self.global_order;
let path = self.current_dir.clone();
self.entries.push(HistoryEntry {
command: entry,
weight: 1,
last_order: order,
last_path: path,
is_multi_dir: false,
is_temp: true,
});
}
/// 添加一条历史记录,使用 self.current_dir 作为执行路径。
/// 调用前须先调用 set_current_dir。
pub fn add(&mut self, entry: String) {
if entry.trim().is_empty() {
return;
}
self.global_order += 1;
let order = self.global_order;
let path = self.current_dir.clone();
// 1. 追加到日志文件(崩溃安全)
if self.log_path.is_some() {
if let Err(e) = self.append_log_entry(&entry, &path, order) {
eprintln!("Failed to append history log: {e}");
}
}
// 2. 更新内存索引
if let Some(pos) = self.entries.iter().position(|e| e.command == entry) {
let mut e = self.entries.remove(pos);
e.weight += 1;
if path != e.last_path {
e.is_multi_dir = true; // 路径变化:标记为多目录命令
}
e.last_path = path;
e.last_order = order;
self.entries.push(e);
} else {
self.entries.push(HistoryEntry::new(entry, path, order));
}
if self.entries.len() > self.max_entries {
self.entries.remove(0);
}
self.index = None;
self.saved_line.clear();
}
fn append_log_entry(&self, cmd: &str, path: &str, order: u64) -> io::Result<()> {
let log_path = self.log_path.as_ref().unwrap();
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(log_path)?;
writeln!(
file,
"{}\t{}\t{}\t{}",
order,
ts,
escape_field(path),
escape_field(cmd)
)?;
Ok(())
}
// ── 复合评分(用于多结果排序)────────────────────────────────
/// 本目录专属命令获得 1_000_000 加权,使其排在全局命令之前。
fn dir_score(&self, entry: &HistoryEntry) -> u64 {
let local_boost = if !entry.is_multi_dir && entry.last_path == self.current_dir {
1_000_000u64
} else {
0u64
};
local_boost + entry.weight as u64
}
// ── 导航(按时间顺序,不受权重影响)──────────────────────────
#[inline]
pub fn previous(&mut self, current_line: &str) -> Option<&str> {
if self.entries.is_empty() {
return None;
}
match self.index {
None => {
self.saved_line = current_line.to_string();
self.index = Some(self.entries.len() - 1);
}
Some(i) if i > 0 => {
self.index = Some(i - 1);
}
_ => return None,
}
self.index.map(|i| self.entries[i].command.as_str())
}
#[inline]
pub fn next(&mut self, _current_line: &str) -> Option<&str> {
match self.index {
Some(i) if i + 1 < self.entries.len() => {
self.index = Some(i + 1);
Some(self.entries[i + 1].command.as_str())
}
Some(_) => {
self.index = None;
self.as_ref_saved()
}
None => None,
}
}
fn as_ref_saved(&self) -> Option<&str> {
if self.saved_line.is_empty() {
None
} else {
Some(&self.saved_line)
}
}
pub fn cancel_navigation(&mut self) -> Option<String> {
let saved = self.saved_line.clone();
self.index = None;
self.saved_line.clear();
if saved.is_empty() { None } else { Some(saved) }
}
#[inline]
pub fn is_navigating(&self) -> bool {
self.index.is_some()
}
// ── Hint(两阶段:本目录专属优先,再全局)───────────────────
pub fn search_hint(&self, current_line: &str) -> Option<String> {
if current_line.is_empty() {
return None;
}
// 阶段1:本目录专属命令(!is_multi_dir && last_path == current_dir)
let local = self
.entries
.iter()
.filter(|e| {
!e.is_multi_dir
&& e.last_path == self.current_dir
&& e.command.starts_with(current_line)
})
.max_by_key(|e| e.weight);
// only return first line to prevent screen over take.
if let Some(e) = local {
return Some(
e.command
.trim_start_matches(current_line)
.lines()
.next()
.unwrap_or_default()
.to_string(),
);
}
// 阶段2:全局命令(按权重)
self.entries
.iter()
.filter(|e| e.is_multi_dir && e.command.starts_with(current_line))
.max_by_key(|e| e.weight)
.map(|e| {
e.command
.trim_start_matches(current_line)
.lines()
.next()
.unwrap_or_default()
.to_string()
})
}
// ── Fuzzy 搜索(两阶段:本目录专属优先,再全局)─────────────
pub fn search_fuzzy_one_cd(&self, query: &str) -> Option<String> {
self.entries
.iter()
.filter_map(|e| {
if let Some(p) = e.command.strip_prefix("cd ")
&& p.trim_end_matches('/') != self.current_dir.trim_end_matches('/')
{
// 只保留匹配成功的条目,并附带其匹配分数
fuzzy_match_score(query, p).map(|score| (score, e.weight, e))
} else {
None
}
})
// 先比匹配分数,分数相同再比历史权重
.max_by_key(|(score, weight, _)| (*score, *weight))
.map(|(_, _, e)| e.command.lines().next().unwrap_or_default().to_string())
}
// pub fn search_fuzzy_one(&self, query: &str) -> Option<String> {
// // 阶段1:本目录专属命令
// let local = self
// .entries
// .iter()
// .filter(|e| {
// !e.is_multi_dir && e.last_path == self.current_dir && fuzzy_match(query, &e.command)
// })
// .max_by_key(|e| e.weight)
// .map(|e| e.command.clone());
// if local.is_some() {
// return local;
// }
// // 阶段2:全局命令
// self.entries
// .iter()
// .filter(|e| e.is_multi_dir && fuzzy_match(query, &e.command))
// .max_by_key(|e| e.weight)
// .map(|e| e.command.clone())
// }
/// 多结果 本目录专属命令 prefix搜索
pub fn search_local_startswith(&self, prefix: &str) -> Vec<String> {
let mut matched: Vec<&HistoryEntry> = self
.entries
.iter()
.filter(|e| {
!e.is_multi_dir
&& e.last_path == self.current_dir
&& (prefix.is_empty() || e.command.starts_with(prefix))
&& !e.command.contains("\n")
})
.collect();
matched.sort_by_key(|e| e.weight);
matched.into_iter().map(|e| e.command.clone()).collect()
}
/// 多结果 多目录适用命令 prefix搜索
pub fn search_multidir_startswith(&self, prefix: &str) -> Vec<String> {
let mut matched: Vec<&HistoryEntry> = self
.entries
.iter()
.filter(|e| {
e.is_multi_dir
&& (prefix.is_empty() || e.command.starts_with(prefix))
&& !e.command.contains("\n")
})
.collect();
matched.sort_by_key(|e| e.weight);
matched.into_iter().map(|e| e.command.clone()).collect()
}
/// 多结果 本目录适用命令 prefix搜索
pub fn search_startswith(&self, prefix: &str) -> Vec<String> {
let mut matched: Vec<&HistoryEntry> = self
.entries
.iter()
.filter(|e| {
((!e.is_multi_dir && e.last_path == self.current_dir) || e.is_multi_dir)
&& (prefix.is_empty() || e.command.starts_with(prefix))
&& !e.command.contains("\n")
})
.collect();
matched.sort_by_key(|e| e.weight);
matched.into_iter().map(|e| e.command.clone()).collect()
}
/// 多结果 fuzzy 搜索:使用 dir_score 排序(本目录专属命令排前)
// pub fn search_fuzzy(&self, query: &str) -> Vec<String> {
// let mut matched: Vec<&HistoryEntry> = self
// .entries
// .iter()
// .filter(|e| fuzzy_match(query, &e.command))
// .collect();
// matched.sort_by(|a, b| self.dir_score(b).cmp(&self.dir_score(a)));
// matched.into_iter().map(|e| e.command.clone()).collect()
// }
// ── Ctrl+R 搜索(按 dir_score 排序)─────────────────────────
// fn build_matches(&self, query: &str) -> Vec<usize> {
// let mut matches: Vec<usize> = self
// .entries
// .iter()
// .enumerate()
// .filter(|(_, e)| e.command.contains(query))
// .map(|(i, _)| i)
// .collect();
// matches.sort_by(|&a, &b| {
// self.dir_score(&self.entries[b])
// .cmp(&self.dir_score(&self.entries[a]))
// .then(b.cmp(&a))
// });
// matches
// }
// pub fn start_search(&mut self, current_line: &str) {
// self.saved_line = current_line.to_string();
// self.search_query = current_line.to_string();
// if self.search_query.is_empty() {
// self.search_matches.clear();
// self.search_index = 0;
// return;
// }
// self.search_matches = self.build_matches(&self.search_query);
// self.search_index = 0;
// }
// pub fn search_current_match(&self) -> Option<&str> {
// self.search_matches
// .get(self.search_index)
// .map(|&i| self.entries[i].command.as_str())
// }
// pub fn search_append(&mut self, c: char) -> Option<&str> {
// self.search_query.push(c);
// self.search_matches = self.build_matches(&self.search_query);
// self.search_index = 0;
// if let Some(&i) = self.search_matches.first() {
// self.index = Some(i);
// Some(self.entries[i].command.as_str())
// } else {
// self.index = None;
// None
// }
// }
// pub fn search_backspace(&mut self) -> Option<&str> {
// self.search_query.pop();
// if self.search_query.is_empty() {
// self.search_matches.clear();
// self.search_index = 0;
// self.index = None;
// return self.as_ref_saved();
// }
// self.search_matches = self.build_matches(&self.search_query);
// self.search_index = 0;
// if let Some(&i) = self.search_matches.first() {
// self.index = Some(i);
// Some(self.entries[i].command.as_str())
// } else {
// self.index = None;
// None
// }
// }
// pub fn search_next(&mut self) -> Option<&str> {
// if self.search_matches.is_empty() || self.search_index + 1 >= self.search_matches.len() {
// return None;
// }
// self.search_index += 1;
// let i = self.search_matches[self.search_index];
// self.index = Some(i);
// Some(self.entries[i].command.as_str())
// }
// pub fn search_prev(&mut self) -> Option<&str> {
// if self.search_matches.is_empty() || self.search_index == 0 {
// return None;
// }
// self.search_index -= 1;
// let i = self.search_matches[self.search_index];
// self.index = Some(i);
// Some(self.entries[i].command.as_str())
// }
// pub fn cancel_search(&mut self) -> Option<String> {
// let saved = self.saved_line.clone();
// self.search_query.clear();
// self.search_matches.clear();
// self.search_index = 0;
// self.index = None;
// self.saved_line.clear();
// if saved.is_empty() { None } else { Some(saved) }
// }
// pub fn accept_search(&mut self) -> Option<String> {
// let result = self.index.map(|i| self.entries[i].command.clone());
// self.search_query.clear();
// self.search_matches.clear();
// self.search_index = 0;
// self.index = None;
// self.saved_line.clear();
// result
// }
// pub fn search_query(&self) -> &str {
// &self.search_query
// }
// pub fn search_match_count(&self) -> usize {
// self.search_matches.len()
// }
// pub fn search_match_index(&self) -> usize {
// self.search_index
// }
// pub fn search_entries(&self) -> Vec<String> {
// self.search_matches
// .iter()
// .map(|&i| self.entries[i].command.clone())
// .collect()
// }
// pub fn is_searching(&self) -> bool {
// !self.search_query.is_empty() || !self.saved_line.is_empty()
// }
// ── 文件 I/O ──────────────────────────────────────────────────
/// 保存索引文件(退出时调用)。
/// 格式:`weight\torder\tpath\tmulti\tcommand`
pub fn save_to_file(&self, path: &str) -> io::Result<()> {
let mut file = File::create(path)?;
for entry in &self.entries {
if !entry.is_temp {
writeln!(
file,
"{}\t{}\t{}\t{}\t{}",
entry.weight,
entry.last_order,
escape_field(&entry.last_path),
if entry.is_multi_dir { 1 } else { 0 },
escape_field(&entry.command)
)?;
}
}
Ok(())
}
/// 加载历史记录(启动时调用)。
/// 日志文件路径自动派生为 `{path}.log`。
/// 调用后建议立即调用 set_current_dir 初始化当前目录。
pub fn load_from_file(&mut self, path: &str) -> io::Result<()> {
let log_path = format!("{}.log", path);
self.log_path = Some(log_path.clone());
if Path::new(path).exists() {
self.load_index(path)?;
} else if Path::new(&log_path).exists() {
self.rebuild_from_log(&log_path)?;
} else {
File::create(&log_path)?;
}
Ok(())
}
/// 从索引文件加载。
/// 支持新格式(5字段)、旧4字段格式、旧2字段格式、纯命令格式。
fn load_index(&mut self, path: &str) -> io::Result<()> {
let file = File::open(path)?;
let reader = BufReader::new(file);
self.entries.clear();
self.global_order = 0;
for line in reader.lines() {
let line = line?;
if line.is_empty() {
continue;
}
// splitn(5) 确保 command 字段中的 \t 不被分割
let parts: Vec<&str> = line.splitn(5, '\t').collect();
let entry = match parts.as_slice() {
// 新格式:weight\torder\tpath\tmulti\tcommand
[w, o, p, m, cmd] => HistoryEntry {
command: unescape_field(cmd),
weight: w.parse().unwrap_or(1),
last_order: o.parse().unwrap_or(0),
last_path: unescape_field(p),
is_multi_dir: *m == "1",
is_temp: false,
},
// 旧4字段格式:weight\torder\tpath\tcommand
// [w, o, p, cmd] => HistoryEntry {
// command: unescape_field(cmd),
// weight: w.parse().unwrap_or(1),
// last_order: o.parse().unwrap_or(0),
// last_path: unescape_field(p),
// is_multi_dir: false,
// },
// // 旧2字段格式:weight\tcommand
// [w, cmd] => HistoryEntry {
// command: unescape_field(cmd),
// weight: w.parse().unwrap_or(1),
// last_order: 0,
// last_path: String::new(),
// is_multi_dir: false,
// },
// // 纯命令格式
// [cmd] => HistoryEntry {
// command: unescape_field(cmd),
// weight: 1,
// last_order: 0,
// last_path: String::new(),
// is_multi_dir: false,
// },
_ => continue,
};
if entry.last_order > self.global_order {
self.global_order = entry.last_order;
}
self.entries.push(entry);
}
Ok(())
}
/// 从日志文件重建索引(索引丢失时的恢复路径)。
/// 日志格式:`order\ttimestamp\tpath\tcommand`
fn rebuild_from_log(&mut self, log_path: &str) -> io::Result<()> {
let file = File::open(log_path)?;
let reader = BufReader::new(file);
self.entries.clear();
self.global_order = 0;
let mut agg: HashMap<String, (u32, String, u64)> = HashMap::new();
let mut path_sets: HashMap<String, HashSet<String>> = HashMap::new();
let mut ordered_cmds: Vec<String> = Vec::new();
for line in reader.lines() {
let line = line?;
if line.is_empty() {
continue;
}
let parts: Vec<&str> = line.splitn(4, '\t').collect();
if parts.len() < 4 {
continue;
}
let order = parts[0].parse::<u64>().unwrap_or(0);
let path = unescape_field(parts[2]);
let cmd = unescape_field(parts[3]);
if order > self.global_order {
self.global_order = order;
}
// 记录该命令出现过的所有目录(用于计算 is_multi_dir)
path_sets
.entry(cmd.clone())
.or_default()
.insert(path.clone());
if let Some(e) = agg.get_mut(&cmd) {
e.0 += 1;
e.1 = path;
e.2 = order;
} else {
ordered_cmds.push(cmd.clone());
agg.insert(cmd, (1, path, order));
}
}
for cmd in ordered_cmds {
if let Some((weight, last_path, last_order)) = agg.remove(&cmd) {
let is_multi_dir = path_sets.get(&cmd).map_or(false, |s| s.len() > 1);
self.entries.push(HistoryEntry {
command: cmd,
weight,
last_path,
last_order,
is_multi_dir,
is_temp: false,
});
}
}
if self.entries.len() > self.max_entries {
let drain = self.entries.len() - self.max_entries;
self.entries.drain(0..drain);
}
Ok(())
}
// ── 公共访问器 ────────────────────────────────────────────────
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &str> {
self.entries.iter().map(|e| e.command.as_str())
}
pub fn get(&self, i: usize) -> Option<&str> {
self.entries.get(i).map(|e| e.command.as_str())
}
pub fn entries(&self) -> Vec<String> {
self.entries.iter().map(|e| e.command.clone()).collect()
}
pub fn cmdstr_by_weight(&self) -> Vec<String> {
let mut sorted: Vec<&HistoryEntry> = self.entries.iter().collect();
sorted.sort_by(|a, b| {
self.dir_score(b)
.cmp(&self.dir_score(a))
.then(a.command.cmp(&b.command))
});
sorted.iter().map(|e| e.command.clone()).collect()
}
pub fn entries_by_weight(&self) -> Vec<&HistoryEntry> {
let mut sorted: Vec<&HistoryEntry> = self.entries.iter().collect();
sorted.sort_by(|a, b| {
self.dir_score(b)
.cmp(&self.dir_score(a))
.then(a.command.cmp(&b.command))
});
sorted
}
pub fn global_order(&self) -> u64 {
self.global_order
}
}
// ── 字段转义(制表符分隔格式)────────────────────────────────────
#[inline]
fn escape_field(s: &str) -> String {
s.replace('\\', "\\\\")
.replace('\n', "\\n")
.replace('\t', "\\t")
}
fn unescape_field(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\\' {
match chars.next() {
Some('n') => result.push('\n'),
Some('t') => result.push('\t'),
Some('\\') => result.push('\\'),
Some(c) => {
result.push('\\');
result.push(c);
}
None => result.push('\\'),
}
} else {
result.push(c);
}
}
result
}
/// 模糊匹配打分:要求 query 的字符必须按顺序出现在 target 中(可不连续)。
/// 匹配失败返回 None;匹配成功返回一个分数,分数越大表示匹配质量越高。
///
/// 打分规则:
/// - 每匹配一个字符得基础分 1
/// - 连续匹配(上一个匹配字符紧挨着当前字符)额外加分,鼓励连续子串
/// - 匹配起始位置越靠前,额外加分(鼓励前缀式匹配)
/// - 大小写不敏感
fn fuzzy_match_score(query: &str, target: &str) -> Option<i64> {
if query.is_empty() {
return Some(0);
}
if target.is_empty() {
return None;
}
// 大小写归一化后再比较,避免因大小写不同而漏匹配
let query_lower: Vec<char> = query.to_lowercase().chars().collect();
let target_lower: Vec<char> = target.to_lowercase().chars().collect();
let mut score: i64 = 0;
let mut t_idx = 0usize; // target 游标
let mut last_match_idx: Option<usize> = None; // 上一次成功匹配的位置,用于判断是否连续
let mut first_match_idx: Option<usize> = None; // 第一次匹配位置,用于前缀加分
for &q in &query_lower {
// 从当前游标开始,在 target 中寻找下一个等于 q 的字符
let found = target_lower[t_idx..]
.iter()
.position(|&c| c == q)
.map(|rel| t_idx + rel);
let idx = match found {
Some(idx) => idx,
None => return None, // 找不到,说明不满足按序子序列匹配
};
if first_match_idx.is_none() {
first_match_idx = Some(idx);
}
// 基础分
score += 1;
// 连续匹配加分:与上一个匹配字符紧挨着,说明是连续子串,质量更高
if let Some(last) = last_match_idx
&& idx == last + 1
{
score += 3;
}
last_match_idx = Some(idx);
t_idx = idx + 1;
}
// 起始位置越靠前,加分越多(鼓励前缀式/开头命中)
if let Some(first) = first_match_idx {
let prefix_bonus = (target_lower.len().saturating_sub(first)) as i64;
score += prefix_bonus / target_lower.len().max(1) as i64 * 2;
}
Some(score)
}