[PATCH 4 of 5] templater: make pad() compute actual width

Yuya Nishihara yuya at tcha.org
Sat Mar 18 10:12:14 EDT 2017


# HG changeset patch
# User Yuya Nishihara <yuya at tcha.org>
# Date 1489837815 -32400
#      Sat Mar 18 20:50:15 2017 +0900
# Node ID 6b73f4d9380f6fc57cdbdfb42add4822a94f3960
# Parent  b05bfb90f25a8dfc720ae5f6b869c0e05f1c1ab1
templater: make pad() compute actual width

str.ljust() and .rjust() are based on byte length, which are valid only for
ASCII characters.

diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -14,6 +14,7 @@ import types
 from .i18n import _
 from . import (
     config,
+    encoding,
     error,
     minirst,
     parser,
@@ -581,10 +582,13 @@ def pad(context, mapping, args):
     if len(args) > 3:
         left = evalboolean(context, mapping, args[3])
 
+    fillwidth = width - encoding.colwidth(text)
+    if fillwidth <= 0:
+        return text
     if left:
-        return text.rjust(width, fillchar)
+        return fillchar * fillwidth + text
     else:
-        return text.ljust(width, fillchar)
+        return text + fillchar * fillwidth
 
 @templatefunc('indent(text, indentchars[, firstline])')
 def indent(context, mapping, args):
diff --git a/tests/test-command-template.t b/tests/test-command-template.t
--- a/tests/test-command-template.t
+++ b/tests/test-command-template.t
@@ -4115,6 +4115,11 @@ utf8 filter:
   abort: template filter 'utf8' is not compatible with keyword 'rev'
   [255]
 
+pad width:
+
+  $ HGENCODING=utf-8 hg debugtemplate "{pad('`cat utf-8`', 2, '-')}\n"
+  \xc3\xa9- (esc)
+
   $ cd ..
 
 Test that template function in extension is registered as expected


More information about the Mercurial-devel mailing list