0

the code block I copy outside emacs, which is not auto-indent when yanking in org

type org-return-indent -> yank code block -> indent manually:


*** headline
    |


v



*** headline
    {
    code block
}



v



*** headline
    {
      code block
    }

expecting the yank and indent in a one step

  • 1
    AFAIK code blocks are delimited by #+BEGIN_SRC and #+END_SRC in org-mode. I.e., you would type <s and press the tabulator key to get a source code template and then paste your source text into this template. Could you please change your example to a minimal working example. Thanks in advance. – Tobias Mar 23 '17 at 15:26
  • personally not use #+BEGIN_SRC and #+END_SRC due to the running speed – yuanlai Mar 24 '17 at 1:27
2

Here is a elisp function that should do what you want

(defun yank-with-indent ()
  (interactive)
  (let ((indent
         (buffer-substring-no-properties (line-beginning-position) (line-end-position))))
    (message indent)
    (yank)
    (narrow-to-region (mark t) (point))
    (pop-to-mark-command)
    (replace-string "\n" (concat "\n" indent))
    (widen)))
  • yes, very nice work! if can add a conditional judgment, which do not indent if the line have no character – yuanlai Mar 25 '17 at 2:00
1

@native-human congratulations for this very useful snippet! But after using it I found that it removes narrow-to-region and so breaks my org workflow. To fix it I added a few lines to preserve narrowing:

  (defun yank-with-indent ()
(interactive)
(let ((indent
       (buffer-substring-no-properties (line-beginning-position) (line-end-position))))
  (message indent)
  (yank)
  (save-excursion
    (save-restriction
      (narrow-to-region (mark t) (point))
      (pop-to-mark-command)
      (replace-string "\n" (concat "\n" indent))
      (widen)))))

(define-key org-mode-map (kbd "C-c y") 'yank-with-indent)

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.