on edd0945 help sign in
vty/src/Graphics/Text/Width.hs
63 lines 1.9 kB history raw
1-- Copyright 2009 Corey O'Connor
2{-# OPTIONS_GHC -D_XOPEN_SOURCE #-}
3{-# LANGUAGE ForeignFunctionInterface #-}
4module Graphics.Text.Width
5 ( wcwidth
6 , wcswidth
7 , wctwidth
8 , wctlwidth
9 , safeWcwidth
10 , safeWcswidth
11 , safeWctwidth
12 , safeWctlwidth
13 )
14where
16import Data.List (foldl')
17import qualified Data.Text as T
18import qualified Data.Text.Lazy as TL
20foreign import ccall unsafe "vty_mk_wcwidth" wcwidth :: Char -> Int
22wcswidth :: String -> Int
23wcswidth = foldl' (\l c -> wcwidth c + l) 0
24{-# INLINE [1] wcswidth #-}
26wctwidth :: T.Text -> Int
27wctwidth = T.foldl' (\l c -> wcwidth c + l) 0
29wctlwidth :: TL.Text -> Int
30wctlwidth = TL.foldl' (\l c -> wcwidth c + l) 0
32{-# RULES
33"wcswidth/unpack" forall x. wcswidth (T.unpack x) = wctwidth x
34"wcswidth/lazy-unpack" forall x. wcswidth (TL.unpack x) = wctlwidth x
35 #-}
37-- XXX: Characters with unknown widths occupy 1 column?
38--
39-- Not sure if this is actually correct. I presume there is a
40-- replacement character that is output by the terminal instead of the
41-- character and this replacement character is 1 column wide. If this is
42-- not true for all terminals then a per-terminal replacement character
43-- width needs to be implemented.
45-- | Returns the display width of a character. Assumes all characters
46-- with unknown widths are 0 width.
47safeWcwidth :: Char -> Int
48safeWcwidth = max 0 . wcwidth
50-- | Returns the display width of a string. Assumes all characters with
51-- unknown widths are 0 width.
52safeWcswidth :: String -> Int
53safeWcswidth = foldl' (\l c -> safeWcwidth c + l) 0
55-- | Returns the display width of a text. Assumes all characters with
56-- unknown widths are 0 width.
57safeWctwidth :: T.Text -> Int
58safeWctwidth = T.foldl' (\l c -> safeWcwidth c + l) 0
60-- | Returns the display width of a lazy text. Assumes all characters
61-- with unknown widths are 0 width.
62safeWctlwidth :: TL.Text -> Int
63safeWctlwidth = TL.foldl' (\l c -> safeWcwidth c + l) 0