will not be shortened.
@end defun
-@defun string-limit string length
-Return a string that's shorter than @var{length}. If @var{string} is
-shorter than @var{length}, @var{string} is returned as is. If
-@var{length} is positive, return a substring of @var{string}
-consisting of the first @var{length} characters. If @var{length} is
-negative, return a string of the @var{-length} last characters
-instead.
+@defun string-limit string length &optional end
+If @var{string} is shorter than @var{length}, @var{string} is returned
+as is. Otherwise, return a substring of @var{string} consisting of
+the first @var{length} characters. If the optional @var{end}
+parameter is given, return a string of the @var{length} last
+characters instead.
@end defun
@defun string-lines string &optional omit-nulls
:eval (substring "foobar" 3))
(string-limit
:eval (string-limit "foobar" 3)
- :eval (string-limit "foobar" -3)
+ :eval (string-limit "foobar" 3 t)
:eval (string-limit "foobar" 10))
(split-string
:eval (split-string "foo bar")
(fill-region (point-min) (point-max)))
(buffer-string)))
-(defun string-limit (string length)
+(defun string-limit (string length &optional end)
"Return (up to) a LENGTH substring of STRING.
If STRING is shorter than or equal to LENGTH, the entire string
-is returned unchanged. If STRING is longer than LENGTH, and
-LENGTH is a positive number, return a substring consisting of the
-first LENGTH characters of STRING. If LENGTH is negative, return
-a substring consisting of the last LENGTH characters of STRING."
+is returned unchanged.
+
+If STRING is longer than LENGTH, return a substring consisting of
+the first LENGTH characters of STRING. If END is non-nil, return
+the last LENTGH characters instead."
+ (unless (natnump length)
+ (signal 'wrong-type-argument (list 'natnump length)))
(cond
- ((<= (length string) (abs length)) string)
- ((>= length 0) (substring string 0 length))
- ((substring string length))))
+ ((<= (length string) length) string)
+ (end (substring string (- (length string) length)))
+ (t (substring string 0 length))))
(defun string-lines (string &optional omit-nulls)
"Split STRING into a list of lines.
(ert-deftest subr-string-limit ()
(should (equal (string-limit "foo" 10) "foo"))
(should (equal (string-limit "foo" 2) "fo"))
- (should (equal (string-limit "foo" -2) "oo"))
- (should (equal (string-limit "abc" -10) "abc"))
- (should (equal (string-limit "foo" 0) "")))
+ (should (equal (string-limit "foo" 2 t) "oo"))
+ (should (equal (string-limit "abc" 10 t) "abc"))
+ (should (equal (string-limit "foo" 0) ""))
+ (should-error (string-limit "foo" -1)))
(ert-deftest subr-string-lines ()
(should (equal (string-lines "foo") '("foo")))