Paste text aligned to cursor in emacs

Viewed 100

Is there a way to paste a text from clipboard aligned with cursor position:

function myFunction() {
  console.log('a');
  <<PASTING HERE>>
}

By default I get:

function myFunction() {
  console.log('a');
  console.log('b');
console.log('c');
console.log('d');
}

But I want to see the last two lines aligned with two spaces too. (OF course, I can select text and align it by tab but it's additional action)

2 Answers

Basically you need to do the indent on the freshly pasted code. I'm using following code for years:

(defvar yank-indent-modes '(emacs-lisp-mode lisp-mode
                            c-mode c++-mode js2-mode
                            tcl-mode sql-mode
                            perl-mode cperl-mode
                            java-mode jde-mode
                            lisp-interaction-mode
                            LaTeX-mode TeX-mode
                go-mode cuda-mode
                            scheme-mode clojure-mode)
  "Modes in which to indent regions that are yanked (or yank-popped)")

(defadvice yank (after indent-region activate)
  "If current mode is one of 'yank-indent-modes, indent yanked text (with prefix arg don't indent)."
  (if (member major-mode yank-indent-modes)
      (let ((mark-even-if-inactive t))
        (indent-region (region-beginning) (region-end) nil))))

This code extends standard yank command that is bound to C-y, and if the current mode is in the list of modes defined in the yank-indent-modes, then it will execute indent-region on the pasted snippet.

P.S. You may also need to add the same defadvice on the yank-pop command.

Implemented the desired solution myself (sorry for the ugly lisp). The key thing is that pasting text is NOT aligned but simply intended by cursor column spaces as described at the original request

(defun clipboard-yank-my (&rest args)
  """ wrapper: yank with shifting yanked text to current cursor column """
  ;; wrapping: https://emacs.stackexchange.com/questions/19215/how-to-write-a-transparent-pass-through-function-wrapper#comment55216_19242)
  (interactive (advice-eval-interactive-spec
                (cadr (interactive-form #'clipboard-yank))))
  
  (setq point1 (point))
  (beginning-of-line)
  (setq pointStart (point))
  (setq currentColumn (- point1 (point)))

  ;; ORIGINAL 
  (apply #'clipboard-yank args)

  (newline)
  ;; (print col)
  (set-mark-command nil)
  (goto-char pointStart)
  (indent-rigidly
   (region-beginning)
   (region-end)
   currentColumn)
  (goto-char point1) 
  ;; (setq deactivate-mark nil)
  )
Related