开发者

Is there an Emacs function that copies a whole line including the newline?

开发者_如何学运维

I can't write emacs function, could anyone help me?.


Yes, there is. This code is borrowed from this blog entry:

(defadvice kill-ring-save (before slick-copy activate compile)
  "When called interactively with no active region, copy a single line instead."
  (interactive
    (if mark-active (list (region-beginning) (region-end))
      (message "Copied line")
      (list (line-beginning-position)
        (line-beginning-position 2)))))

(defadvice kill-region (before slick-cut activate compile)
  "When called interactively with no active region, kill a single line instead."
  (interactive
    (if mark-active (list (region-beginning) (region-end))
      (list (line-beginning-position)
        (line-beginning-position 2)))))


There are several ways to copy a line:

  1. The usual way: C-a C-SPC C-n M-w

  2. With the mouse: triple click on the line, type M-w

  3. Set (or customize) the variable kill-whole-line to t, then copy by killing and undoing: C-a C-k C-_

I don't find this a common enough operation that I'd want to assign it a key combination, but if you do then it's easy to write a function:

(defun kill-ring-save-line () 
  "Save the line containing point to the kill ring."
  (interactive)
  (kill-ring-save (line-beginning-position) 
                  (line-beginning-position 2)))


C-a C-k C-k C-y
or
C-a C-u 1 C-k C-y

Found via
C-h k C-k
and
C-h f kill-TAB

(defun copy-line ()
  (interactive)
  (beginning-of-line)
  (kill-line 1)
  (yank))


;; http://www.emacswiki.org/emacs/WholeLineOrRegion#toc2
;; cut, copy, yank
(defadvice kill-ring-save (around slick-copy activate)
  "When called interactively with no active region, copy a single line instead."
  (if (or (use-region-p) (not (called-interactively-p)))
      ad-do-it
    (kill-new (buffer-substring (line-beginning-position)
                                (line-beginning-position 2))
              nil '(yank-line))
    (message "Copied line")))
(defadvice kill-region (around slick-copy activate)
  "When called interactively with no active region, kill a single line instead."
  (if (or (use-region-p) (not (called-interactively-p)))
      ad-do-it
    (kill-new (filter-buffer-substring (line-beginning-position)
                                       (line-beginning-position 2) t)
              nil '(yank-line))))
(defun yank-line (string)
  "Insert STRING above the current line."
  (beginning-of-line)
  (unless (= (elt string (1- (length string))) ?\n)
    (save-excursion (insert "\n")))
  (insert string))

(global-set-key (kbd "<f2>") 'kill-region)    ; cut.
(global-set-key (kbd "<f3>") 'kill-ring-save) ; copy.
(global-set-key (kbd "<f4>") 'yank)           ; paste.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜