Skip to content

Commit c15e834

Browse files
authored
Use grapheme's width to align a list of completions (#143)
* Use gsWidth to calculate the width of completions * Update variable names and comments to mention "width", not "length"
1 parent 5f16b76 commit c15e834

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

System/Console/Haskeline/Command/Completion.hs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ module System.Console.Haskeline.Command.Completion(
55
completionCmd
66
) where
77

8+
import System.Console.Haskeline.Backend.WCWidth (gsWidth)
89
import System.Console.Haskeline.Command
910
import System.Console.Haskeline.Command.Undo
1011
import System.Console.Haskeline.Key
@@ -120,27 +121,26 @@ makeLines :: [String] -> Layout -> [String]
120121
makeLines ws layout = let
121122
minColPad = 2
122123
printWidth = width layout
123-
maxLength = min printWidth (maximum (map length ws) + minColPad)
124-
numCols = printWidth `div` maxLength
125-
ls = if maxLength >= printWidth
124+
maxWidth = min printWidth (maximum (map (gsWidth . stringToGraphemes) ws) + minColPad)
125+
numCols = printWidth `div` maxWidth
126+
ls = if maxWidth >= printWidth
126127
then map (: []) ws
127128
else splitIntoGroups numCols ws
128-
in map (padWords maxLength) ls
129+
in map (padWords maxWidth) ls
129130

130-
-- Add spaces to the end of each word so that it takes up the given length.
131-
-- Don't padd the word in the last column, since printing a space in the last column
131+
-- Add spaces to the end of each word so that it takes up the given visual width.
132+
-- Don't pad the word in the last column, since printing a space in the last column
132133
-- causes a line wrap on some terminals.
133134
padWords :: Int -> [String] -> String
134135
padWords _ [x] = x
135136
padWords _ [] = ""
136-
padWords len (x:xs) = x ++ replicate (len - glength x) ' '
137-
++ padWords len xs
137+
padWords wid (x:xs) = x ++ replicate (wid - widthOf x) ' '
138+
++ padWords wid xs
138139
where
139-
-- kludge: compute the length in graphemes, not chars.
140-
-- but don't use graphemes for the max length, since I'm not convinced
141-
-- that would work correctly. (This way, the worst that can happen is
142-
-- that columns are longer than necessary.)
143-
glength = length . stringToGraphemes
140+
-- kludge: compute the width in graphemes, not chars.
141+
-- also use graphemes for the max width so that multi-width characters
142+
-- such as CJK letters are aligned correctly.
143+
widthOf = gsWidth . stringToGraphemes
144144

145145
-- Split xs into rows of length n,
146146
-- such that the list increases incrementally along the columns.

0 commit comments

Comments
 (0)