1

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

ccd
  • 259
  • 2
  • 11

3 Answers3

2

@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)

alex_koval
  • 184
  • 5
1

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 – ccd Mar 25 '17 at 02:00
1

Here is a different approach, maybe someone will find this useful. This is a minor mode that patches get-text-property to fake the property 'yank-handler, which indicates which function to use for inserting. Then I use insert-rectangle for that. That way, this also works with helm-ring.

(defvar my/is-rectangle-yanking nil)

(defun my/insert-rectangle-split (string)
  (let ((rows (split-string string "\n"))
        (my/is-rectangle-yanking t))
    (save-excursion (insert (make-string (length rows) ?\n)))
    (insert-rectangle rows)
    (delete-char 1)))

(defun my/get-text-property-rectangle-yank (fun pos prop &optional object)
  (let ((propv (funcall fun pos prop object)))
    (if propv propv
      (when (and (eq prop 'yank-handler) (stringp object) (not my/is-rectangle-yanking))
        '(my/insert-rectangle-split)))))

(define-global-minor-mode my/yank-as-rectangle
  "Minor mode to yank as rectangle.  This patches `get-text-property'
to put `insert-rectangle' as the insert function (`yank-handler')."
  :init-value nil  :lighter " Rec"
  (if (not my/yank-as-rectangle)
      (advice-remove 'get-text-property #'my/get-text-property-rectangle-yank)
    (advice-add 'get-text-property :around #'my/get-text-property-rectangle-yank)))
Michaël
  • 314
  • 1
  • 10