How do I duplicate a whole line in Emacs?

前端 未结 30 1087
时光取名叫无心
时光取名叫无心 2020-12-04 05:20

I saw this same question for VIM and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least num

30条回答
  •  死守一世寂寞
    2020-12-04 05:30

    With prefix arguments, and what is (I hope) intuitive behaviour:

    (defun duplicate-line (&optional arg)
      "Duplicate it. With prefix ARG, duplicate ARG times."
      (interactive "p")
      (next-line 
       (save-excursion 
         (let ((beg (line-beginning-position))
               (end (line-end-position)))
           (copy-region-as-kill beg end)
           (dotimes (num arg arg)
             (end-of-line) (newline)
             (yank))))))
    

    The cursor will remain on the last line. Alternatively, you might want to specify a prefix to duplicate the next few lines at once:

    (defun duplicate-line (&optional arg)
      "Duplicate it. With prefix ARG, duplicate ARG times."
      (interactive "p")
      (save-excursion 
        (let ((beg (line-beginning-position))
              (end 
               (progn (forward-line (1- arg)) (line-end-position))))
          (copy-region-as-kill beg end)
          (end-of-line) (newline)
          (yank)))
      (next-line arg))
    

    I find myself using both often, using a wrapper function to switch the behavior of the prefix argument.

    And a keybinding: (global-set-key (kbd "C-S-d") 'duplicate-line)

提交回复
热议问题