如何在 elisp 中将字符串居中?

发布于 2024-08-03 17:57:48 字数 710 浏览 4 评论 0原文

我想将给定的输入字符串居中对齐到给定的大小,以便生成一个在输入字符串的两侧(左侧和右侧)填充空格的字符串。

我必须执行此操作的代码:

(defun center-string (string size)
  (let* ((padding (/ (- size (length string)) 2))
         (lpad (+ (length string) padding))
         (lformat (format "%%%ds" lpad))
         (rformat (format "%%%ds" (- size))))
    (format rformat (format lformat string))))

以及一些测试用例:

(center-string "KJF" 10)
 => "   KJF    "
(center-string "KF" 10)
 => "    KF    "
(center-string "0123456789" 10)
 => "0123456789"
(center-string "0123456789" 5)
 => "0123456789"       ; Notice justifcation is ignored as input string too large.

是否有现有的 elisp 函数可以执行此操作或更好的方法?

I would like to center justify a given input string to a given size so that what is produced is a string with padded spaces either side (left and right) of the input string.

The code I have to do this:

(defun center-string (string size)
  (let* ((padding (/ (- size (length string)) 2))
         (lpad (+ (length string) padding))
         (lformat (format "%%%ds" lpad))
         (rformat (format "%%%ds" (- size))))
    (format rformat (format lformat string))))

And some test cases:

(center-string "KJF" 10)
 => "   KJF    "
(center-string "KF" 10)
 => "    KF    "
(center-string "0123456789" 10)
 => "0123456789"
(center-string "0123456789" 5)
 => "0123456789"       ; Notice justifcation is ignored as input string too large.

Is there an existing elisp function to do this or a better method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许仙没带伞 2024-08-10 17:57:49

有一个 center-line,它在缓冲区中工作(并使用缓冲区的 fill-column 值作为行长度),所以如果您的目标是产生一个很好的效果格式化文件,你可以这样做

(defun insert-centered (x)
  (insert "\n" x)
  (center-line)
  (insert "\n"))

There's a center-line, which works in a buffer (and uses the buffer's value of fill-column as the line length), so if your goal is to produce a nicely formatted file, you could do something like

(defun insert-centered (x)
  (insert "\n" x)
  (center-line)
  (insert "\n"))
衣神在巴黎 2024-08-10 17:57:49

不,没有现有的 emacs lisp 例程可以完成您想要的操作。 (通过 emacs lisp info 和 emacs info 的标准搜索支持这一点)。

No, there is not an existing emacs lisp routine that does what you want. (the standard search through emacs lisp info and emacs info supports this).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文