【问题标题】:Elisp function to replace underscores for white spaces in the current line用于替换当前行中空格的下划线的 Elisp 函数
【发布时间】:2014-09-22 19:31:40
【问题描述】:

我正在尝试编写一个非常简单的函数来替换当前行中的所有下划线以替换白人步伐。 这就是我目前所拥有的

  (select-current-line)
  (exit-minibuffer)
  (query-replace "_" " " nil (if (and transient-mark-mode mark-active) (region-beginning)) (if (and transient-mark-mode mark-active) (region-end)))

但我收到以下消息:

No catch for tag: exit, nil

我不太相信在活动选择中使用查询替换是最好的方法,但我根本不是 elisp 程序员。

有什么想法吗?

谢谢

更新:

根据下面的答案,这是我最终使用的代码:

  (let ((end (copy-marker (line-end-position))))
    (while (re-search-forward "_" end t)
      (replace-match " " nil nil)))

【问题讨论】:

    标签: elisp


    【解决方案1】:

    C-h f query-replace RET 没有说出我想引用的内容,但C-h f perform-replace RET 做到了:

    Don't use this in your own program unless you want to query and set the mark
    just as `query-replace' does.  Instead, write a simple loop like this:
    
      (while (re-search-forward \"foo[ \\t]+bar\" nil t)
        (replace-match \"foobar\" nil nil))
    

    至于限制在当前行,最好的办法是使用re-search-forward的第二个arg:

    (let ((end (copy-marker (line-end-position))))
      (while (re-search-forward \"foo[ \\t]+bar\" end t)
        (replace-match \"foobar\" nil nil)))
    

    注意copy-marker 的使用,因为行尾的位置会随着您修改行而不断变化,因此您不想将位置保留为纯整数而是作为标记(即绑定到文本中的某个位置)。 一个常见的替代方法是倒退(因为插入/删除只影响更改后的位置):

    (end-of-line)
    (let ((beg (line-beginning-position)))
      (while (re-search-backward \"foo[ \\t]+bar\" beg t)
        (replace-match \"foobar\" nil nil)))
    

    【讨论】:

      猜你喜欢
      • 2011-07-12
      • 2017-04-14
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多