1

In my line of work, I often have one document containing questions and another document containing answers. How can I merge these documents in the form of Question/Answer.

BUFFER #1:

Q1:  Do you like green eggs and ham?
Q2:  Would you like them here or there?
Q3:  Would you like them in a house?

BUFFER #2:

A1:  I do not like them, Sam-I-am.
A2:  I would not like them here or there.
A3:  I do not like them in a house.

DESIRED RESULT -- BUFFER #3:

Q1:  Do you like green eggs and ham?
A1:  I do not like them, Sam-I-am.
Q2:  Would you like them here or there?
A2:  I would not like them here or there.
Q3:  Would you like them in a house?
A3:  I do not like them in a house.
2

If I would do that, copy&paste both Q&As into a new buffer (#3) then

Q1:  Do you like green eggs and ham?
Q2:  Would you like them here or there?
Q3:  Would you like them in a house?
A1:  I do not like them, Sam-I-am.
A2:  I would not like them here or there.
A3:  I do not like them in a house.

do the following:

beginning-of-buffer (M-<)
kmacro-start-macro (f3)
    next-line x3 (3 C-n)
    kill-whole-line (C-S-BS)
    previous-line x2 (2 C-p)
    yank (C-y)
kmacro-end-macro (f4)
kmacro-call-macro x2 (2 f4)

If you often need to do this then to implement a function may be an option:

(defun foo ()
  (let ((Qs (with-current-buffer "#1" (split-string (buffer-string) "\n")))
        (As (with-current-buffer "#2" (split-string (buffer-string) "\n"))))
    (with-current-buffer (get-buffer-create "#3")
      (dolist (Q Qs)
        (insert Q "\n")
        (insert (pop As) "\n")))))
  • I tried foo and it works well. I'll leave the question open for another day or so to see if there are any other interesting answers, and I'll need a cup of coffee to wrap my head around foo. I'm not sure why it's a bit of a brain-twister for me; but I'm sure some coffee after a good night sleep will help. Thank you for posting an answer -- greatly appreciated. – lawlist Sep 29 '16 at 3:40
  • +1. A classic use-case for keyboard macros -- but why bother copying and pasting all the text into the new buffer first? You can do your buffer switching within the macro definition! (Using keyboard macros to read and manipulate text across multiple buffers is an amazingly powerful paradigm. Slightly easier to mess up in the recording phase, admittedly, but well worth being familiar with.) – phils Sep 29 '16 at 5:08
  • Exactly! Seems good to remember > You can do your buffer switching within the macro definition – zk_phi Sep 29 '16 at 5:44

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.