]> git.eshelyaron.com Git - emacs.git/commitdiff
Fix off-by-one error in string-truncate-left
authorLars Ingebrigtsen <larsi@gnus.org>
Sat, 23 Jul 2022 06:55:20 +0000 (08:55 +0200)
committerLars Ingebrigtsen <larsi@gnus.org>
Sat, 23 Jul 2022 06:58:53 +0000 (08:58 +0200)
* lisp/emacs-lisp/subr-x.el (string-truncate-left): Fix off-by-one
error (bug#56685).

lisp/emacs-lisp/subr-x.el
test/lisp/emacs-lisp/subr-x-tests.el

index 5037ae47e83d69a71553a697baed173710a9bc9a..d5d7bfeb6f5f174f46e98a057aa72fae26ad41ae 100644 (file)
@@ -107,12 +107,16 @@ characters; nil stands for the empty string."
 
 ;;;###autoload
 (defun string-truncate-left (string length)
-  "Truncate STRING to LENGTH, replacing initial surplus with \"...\"."
+  "If STRING is longer than LENGTH, return a truncated version.
+When truncating, \"...\" is always prepended to the string, so
+the resulting string may be longer than the original if LENGTH is
+3 or smaller."
   (let ((strlen (length string)))
     (if (<= strlen length)
        string
       (setq length (max 0 (- length 3)))
-      (concat "..." (substring string (max 0 (- strlen 1 length)))))))
+      (concat "..." (substring string (min (1- strlen)
+                                           (max 0 (- strlen length))))))))
 
 (defsubst string-blank-p (string)
   "Check whether STRING is either empty or only whitespace.
index 99c0e8221557c6a6c5f7dbca21190d55f279b9ad..7a3efe9db626b00b07c198d1e65efef59f6781d8 100644 (file)
     (should (equal (sort (hash-table-keys h) #'string<) '(a b c)))
     (should (equal (sort (hash-table-values h) #'<) '(1 2 3)))))
 
+(ert-deftest test-string-truncate-left ()
+  (should (equal (string-truncate-left "band" 3) "...d"))
+  (should (equal (string-truncate-left "band" 2) "...d"))
+  (should (equal (string-truncate-left "longstring" 8) "...tring")))
+
 (provide 'subr-x-tests)
 ;;; subr-x-tests.el ends here