@@ -109,7 +109,7 @@ impl<'a> MatchedString<'a> {
109109 self . name_match = self
110110 . name_match
111111 . take ( )
112- . map ( |mut nm| nm. cut_after ( removed_char_count - 1 ) ) ;
112+ . map ( |mut nm| nm. cut_after ( removed_char_count) ) ;
113113 }
114114 removed_char_count
115115 }
@@ -178,3 +178,70 @@ impl<'a> MatchedString<'a> {
178178 Ok ( ( ) )
179179 }
180180}
181+
182+ #[ cfg( test) ]
183+ mod matched_string_tests {
184+ use {
185+ super :: MatchedString ,
186+ crate :: pattern:: NameMatch ,
187+ smallvec:: smallvec,
188+ termimad:: CompoundStyle ,
189+ } ;
190+
191+ /// Cutting chars from the left to fit a width reindexes every surviving
192+ /// match position by the number of removed chars: original index `rcc`
193+ /// becomes display index `0`, so a match at original `p` lands at `p - rcc`.
194+ #[ test]
195+ fn cut_left_to_fit_reindexes_match_positions ( ) {
196+ let base_style = CompoundStyle :: default ( ) ;
197+ let match_style = CompoundStyle :: default ( ) ;
198+ // "abcdef" (width 6) is matched on 'e', 'f' (positions 4, 5).
199+ let mut matched_string = MatchedString :: new (
200+ Some ( NameMatch {
201+ score : 1 ,
202+ pos : smallvec ! [ 4 , 5 ] ,
203+ } ) ,
204+ "abcdef" ,
205+ & base_style,
206+ & match_style,
207+ ) ;
208+ // Fitting to width 4 removes the 2 leftmost chars -> visible "cdef".
209+ let removed = matched_string. cut_left_to_fit ( 4 ) ;
210+ assert_eq ! ( removed, 2 ) ;
211+ assert_eq ! ( matched_string. string, "cdef" ) ;
212+ // 'e', 'f' are now at display positions 2, 3.
213+ let expected: & [ usize ] = & [ 2 , 3 ] ;
214+ assert_eq ! (
215+ matched_string. name_match. as_ref( ) . unwrap( ) . pos. as_slice( ) ,
216+ expected,
217+ ) ;
218+ }
219+
220+ /// When the last removed char was itself matched, that match must be
221+ /// dropped instead of leaving a phantom highlight on the first visible char.
222+ #[ test]
223+ fn cut_left_to_fit_drops_match_on_last_removed_char ( ) {
224+ let base_style = CompoundStyle :: default ( ) ;
225+ let match_style = CompoundStyle :: default ( ) ;
226+ // "wxyzab" (width 6) is matched on 'x', 'y' (positions 1, 2).
227+ let mut matched_string = MatchedString :: new (
228+ Some ( NameMatch {
229+ score : 1 ,
230+ pos : smallvec ! [ 1 , 2 ] ,
231+ } ) ,
232+ "wxyzab" ,
233+ & base_style,
234+ & match_style,
235+ ) ;
236+ // Fitting to width 4 removes 'w', 'x' -> visible "yzab". 'x' (the last
237+ // removed char) was matched but is gone; only 'y' survives, at index 0.
238+ let removed = matched_string. cut_left_to_fit ( 4 ) ;
239+ assert_eq ! ( removed, 2 ) ;
240+ assert_eq ! ( matched_string. string, "yzab" ) ;
241+ let expected: & [ usize ] = & [ 0 ] ;
242+ assert_eq ! (
243+ matched_string. name_match. as_ref( ) . unwrap( ) . pos. as_slice( ) ,
244+ expected,
245+ ) ;
246+ }
247+ }
0 commit comments