@@ -9,12 +9,7 @@ use once_cell::sync::Lazy;
9
9
use crate :: term:: { wants_emoji, Term } ;
10
10
11
11
#[ cfg( feature = "ansi-parsing" ) ]
12
- use crate :: ansi:: { strip_ansi_codes, AnsiCodeIterator } ;
13
-
14
- #[ cfg( not( feature = "ansi-parsing" ) ) ]
15
- fn strip_ansi_codes ( s : & str ) -> & str {
16
- s
17
- }
12
+ use crate :: ansi:: AnsiCodeIterator ;
18
13
19
14
fn default_colors_enabled ( out : & Term ) -> bool {
20
15
( out. features ( ) . colors_supported ( )
@@ -71,7 +66,19 @@ pub fn set_colors_enabled_stderr(val: bool) {
71
66
72
67
/// Measure the width of a string in terminal characters.
73
68
pub fn measure_text_width ( s : & str ) -> usize {
74
- str_width ( & strip_ansi_codes ( s) )
69
+ #[ cfg( feature = "ansi-parsing" ) ]
70
+ {
71
+ AnsiCodeIterator :: new ( s)
72
+ . filter_map ( |( s, is_ansi) | match is_ansi {
73
+ false => Some ( str_width ( s) ) ,
74
+ true => None ,
75
+ } )
76
+ . sum ( )
77
+ }
78
+ #[ cfg( not( feature = "ansi-parsing" ) ) ]
79
+ {
80
+ str_width ( s)
81
+ }
75
82
}
76
83
77
84
/// A terminal color.
@@ -937,16 +944,30 @@ fn test_text_width() {
937
944
. bold ( )
938
945
. force_styling ( true )
939
946
. to_string ( ) ;
947
+
940
948
assert_eq ! (
941
949
measure_text_width( & s) ,
942
950
if cfg!( feature = "ansi-parsing" ) {
943
951
3
944
- } else if cfg!( feature = "unicode-width" ) {
945
- 17
946
952
} else {
947
953
21
948
954
}
949
955
) ;
956
+
957
+ let s = style ( "🐶 <3" ) . red ( ) . force_styling ( true ) . to_string ( ) ;
958
+
959
+ assert_eq ! (
960
+ measure_text_width( & s) ,
961
+ match (
962
+ cfg!( feature = "ansi-parsing" ) ,
963
+ cfg!( feature = "unicode-width" )
964
+ ) {
965
+ ( true , true ) => 5 , // "🐶 <3"
966
+ ( true , false ) => 4 , // "🐶 <3", no unicode-aware width
967
+ ( false , true ) => 14 , // full string
968
+ ( false , false ) => 13 , // full string, no unicode-aware width
969
+ }
970
+ ) ;
950
971
}
951
972
952
973
#[ test]
0 commit comments