Skip to content

Commit 73687e8

Browse files
committed
Fix issue #83 (from Formatting.jl), handle precision argument for Python format string
1 parent 030352b commit 73687e8

File tree

3 files changed

+44
-15
lines changed

3 files changed

+44
-15
lines changed

Project.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ keywords = ["Strings", "Formatting"]
2323
license = "MIT"
2424
name = "Format"
2525
uuid = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8"
26-
version = "1.3.3"
26+
version = "1.3.4"
2727

2828
[deps]
2929

src/fmtcore.jl

+33-14
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,43 @@ function _repprint(out::IO, c::AbstractChar, n::Int)
1313
end
1414
end
1515

16-
1716
### print string or char
1817

18+
function _truncstr(s::AbstractString, slen, prec)
19+
prec == 0 && return ("", 0)
20+
i, n = 0, 1
21+
siz = ncodeunits(s)
22+
while n <= siz
23+
(prec -= textwidth(s[n])) < 0 && break
24+
i = n
25+
n = nextind(s, i)
26+
end
27+
str = SubString(s, 1, i)
28+
return (str, textwidth(str))
29+
end
30+
31+
_truncstr(s::AbstractChar, slen, prec) = ("", 0)
32+
1933
function _pfmt_s(out::IO, fs::FormatSpec, s::Union{AbstractString,AbstractChar})
20-
pad = fs.width - textwidth(s)
21-
if pad <= 0
22-
print(out, s)
23-
elseif fs.align == '<'
24-
print(out, s)
25-
_repprint(out, fs.fill, pad)
26-
elseif fs.align == '^'
27-
_repprint(out, fs.fill, pad>>1)
28-
print(out, s)
29-
_repprint(out, fs.fill, (pad+1)>>1)
30-
else
31-
_repprint(out, fs.fill, pad)
32-
print(out, s)
34+
slen = textwidth(s)
35+
str, slen = 0 <= fs.prec < slen ? _truncstr(s, slen, fs.prec) : (s, slen)
36+
prepad = postpad = 0
37+
pad = fs.width - slen
38+
if pad > 0
39+
if fs.align == '<'
40+
postpad = pad
41+
elseif fs.align == '^'
42+
prepad, postpad = pad>>1, (pad+1)>>1
43+
else
44+
prepad = pad
45+
end
3346
end
47+
# left padding
48+
prepad == 0 || _repprint(out, fs.fill, prepad)
49+
# print string
50+
print(out, str)
51+
# right padding
52+
postpad == 0 || _repprint(out, fs.fill, postpad)
3453
end
3554

3655
_unsigned_abs(x::Signed) = unsigned(abs(x))

test/fmtspec.jl

+10
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ end
5454
@test pyfmt("#b", 6) == "0b110"
5555
@test pyfmt("#o", 6) == "0o6"
5656
@test pyfmt("#x", 6) == "0x6"
57+
@test pyfmt("#X", 10) == "0XA"
5758
end
5859

5960
@testset "Format string" begin
@@ -75,6 +76,15 @@ end
7576
@test pyfmt("⋆^5s", "αβγ") == "⋆αβγ⋆"
7677
@test pyfmt("*<5s", "abc") == "abc**"
7778
@test pyfmt("⋆<5s", "αβγ") == "αβγ⋆⋆"
79+
80+
# Issue #83 (in Formatting.jl)
81+
@test pyfmt(".3s", "\U1f595\U1f596") == "🖕"
82+
@test pyfmt(".4s", "\U1f595\U1f596") == "🖕🖖"
83+
@test pyfmt(".5s", "\U1f595\U1f596") == "🖕🖖"
84+
85+
@test pyfmt("6.3s", "\U1f595\U1f596") == "🖕 "
86+
@test pyfmt("6.4s", "\U1f595\U1f596") == "🖕🖖 "
87+
@test pyfmt("6.5s", "\U1f595\U1f596") == "🖕🖖 "
7888
end
7989

8090
@testset "Format Symbol" begin

0 commit comments

Comments
 (0)