Replace one space by two after sentences in Emacs

烂漫一生 提交于 2020-01-06 18:23:13

问题


I have a document with paragraphs where some sentences end with a dot and one space (". Nextline"), while others end with a dot and two spaces (". Nextline"). I want to replace replace dot and one space to dot and two spaces but without increasing existing dot and two spaces to dot and three spaces.

The sentences of paragraph are not ending with newline or "\n", except the last one. There will be a newline character at the end of the paragraph. I want to start each sentence with 2 spaces, neither 1 nor 3 or more. If I use search and replace from the menu, sentences starting with 2 spaces increase to 3 spaces at their start.

How can I do that? I tried following but it increases two spaces to three:

(defun space12 ()
    (interactive)
    (while (re-search-forward "\\. ?" nil t)
        (replace-match ".  ")))

Where is the problem and how can I correct it.

Sample input text:

This is first sentence (I called it line earlier). This sentence has one space at start.  This has two. And this again has one space at start.

回答1:


You can use C-M-% (M-x query-replace-regexp) with search string \. \([^ ]\) and replacement string . \1.

When you want to put \ in a string remember that you have to escape it with another \. For example:

(defun space12 ()
  (interactive)
  (while (re-search-forward "\\. \\([^ ]\\)" nil t)
    (replace-match ".  \\1" t)))

To get this “well behaved” I'd make it always process the whole buffer and go back to the original position after:

(defun space12 ()
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (while (re-search-forward "\\. \\([^ ]\\)" nil t)
      (replace-match ".  \\1" t))))


来源:https://stackoverflow.com/questions/43409778/replace-one-space-by-two-after-sentences-in-emacs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!