0

To clarify this is what I'd like to do:

Text Before:

key: foo
key: bar
key: baz

Text After:

key: foo bar baz

Wondering if anyone has a good technique for this type of operation (simpler the better). Suspect it might be possible with replace-regexp and some back reference trickery - been trying to figure out a way but no inspiration has hit yet :)

  • What would you do manually? Just do that, recording what you do as a keyboard macro. – Drew Dec 2 '18 at 23:28
  • Manually, just replace <newline>key: with an empty string? – phils Dec 2 '18 at 23:43
  • The problem with the manual methods is that I have a large number of these - - with different keys and number of entries. I was looking for a more programmatic option like the function suggested by xuchunyang@. Agree though for quick edits these work too – Anntoin Wilkinson Dec 3 '18 at 0:06
  • I suggest that the question text be edited to provide these clarifications. – phils Dec 3 '18 at 2:26
2

Here is a command to merge two lines, if these two lines share a common prefix, don't duplicate it

(defun my-merge-two-lines ()
  "Merge the next line into the current line."
  (interactive)
  (save-excursion
    (let (current-line next-line prefix)
      (setq current-line
            (buffer-substring (line-beginning-position) (line-end-position)))
      (kill-whole-line)
      (setq next-line
            (buffer-substring (line-beginning-position) (line-end-position)))
      (kill-whole-line)
      (setq prefix (fill-common-string-prefix current-line next-line))
      (insert
       (concat current-line " " (substring next-line (length prefix)) "\n")))))

For example, assuming the point is on the first line

key: foo
key: bar
key: baz

run the above command twice, the text becomes

key: foo bar baz

If you like the idea, you can simply use the builtin M-^ (delete-indentation/join-line), note that you need manually set the prefix to "key: " via C-x . (set-fill-prefix).

  • Thanks for the two excellent suggestions! – Anntoin Wilkinson Dec 2 '18 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.