문제

나는 보았다 VIM에 대한 동일한 질문 그리고 그것은 나 자신도 Emacs에서 어떻게 해야 하는지 알고 싶었던 것이었습니다.ReSharper에서는 이 작업에 CTRL-D를 사용합니다.Emacs에서 이 작업을 수행하는 데 필요한 최소 명령 수는 몇 개입니까?

도움이 되었습니까?

해결책

나는 사용한다

C-a C-SPACE C-n M-w C-y

이는 다음과 같이 분해됩니다.

  • C-a:커서를 줄의 시작으로 이동
  • C-SPACE:선택 시작("표시 설정")
  • C-n:커서를 다음 줄로 이동
  • M-w:복사 영역
  • C-y:붙여넣기("햐크")

전술한

C-a C-k C-k C-y C-y

같은 것임 (TMTOWTDI)

  • C-a:커서를 줄의 시작으로 이동
  • C-k:줄을 자르다("죽이기")
  • C-k:줄 바꿈을 잘라
  • C-y:붙여넣기 ("yank") (원점으로 돌아왔습니다)
  • C-y:다시 붙여넣으세요(이제 해당 줄의 복사본이 두 개 생겼습니다).

이것들은 둘 다에 비해 당황스러울 정도로 장황하다. C-d 편집기에는 있지만 Emacs에는 항상 사용자 정의가 있습니다. C-d ~에 묶여 있다 delete-char 기본적으로는 어떻습니까? C-c C-d?다음을 추가하십시오. .emacs:

(global-set-key "\C-c\C-d" "\C-a\C- \C-n\M-w\C-y")

(@Nathan의 elisp 버전은 키 바인딩이 변경되어도 중단되지 않으므로 아마도 바람직할 것입니다.)

주의하세요:일부 Emacs 모드는 회수될 수 있습니다 C-c C-d 다른 일을 하려고요.

다른 팁

이전 답변 외에도 자신만의 함수를 정의하여 줄을 복제할 수도 있습니다.예를 들어, .emacs 파일에 다음을 넣으면 C-d가 현재 행을 복제하게 됩니다.

(defun duplicate-line()
  (interactive)
  (move-beginning-of-line 1)
  (kill-line)
  (yank)
  (open-line 1)
  (next-line 1)
  (yank)
)
(global-set-key (kbd "C-d") 'duplicate-line)

라인에 커서를 놓고 시작 부분이 아닌 경우 다음을 수행하십시오. CTRL 키-, 그 다음에:

CTRL 키-케이

CTRL 키-케이

CTRL 키-와이

CTRL 키-와이

실행 취소에 잘 작동하고 커서 위치를 엉망으로 만들지 않는 줄을 복제하는 내 버전의 함수입니다.그것은 a의 결과였습니다. 1997년 11월 gnu.emacs.sources의 토론.

(defun duplicate-line (arg)
  "Duplicate current line, leaving point in lower line."
  (interactive "*p")

  ;; save the point for undo
  (setq buffer-undo-list (cons (point) buffer-undo-list))

  ;; local variables for start and end of line
  (let ((bol (save-excursion (beginning-of-line) (point)))
        eol)
    (save-excursion

      ;; don't use forward-line for this, because you would have
      ;; to check whether you are at the end of the buffer
      (end-of-line)
      (setq eol (point))

      ;; store the line and disable the recording of undo information
      (let ((line (buffer-substring bol eol))
            (buffer-undo-list t)
            (count arg))
        ;; insert the line arg times
        (while (> count 0)
          (newline)         ;; because there is no newline in 'line'
          (insert line)
          (setq count (1- count)))
        )

      ;; create the undo information
      (setq buffer-undo-list (cons (cons eol (point)) buffer-undo-list)))
    ) ; end-of-let

  ;; put the point in the lowest line and return
  (next-line arg))

그런 다음 CTRL-D를 정의하여 이 함수를 호출할 수 있습니다.

(global-set-key (kbd "C-d") 'duplicate-line)

대신에 kill-line (C-k) 에서와 같이 C-a C-k C-k C-y C-y 사용 kill-whole-line 명령:

C-S-Backspace
C-y
C-y

이상의 장점 C-k 점이 선의 어디에 있는지는 중요하지 않다는 점을 포함합니다(예: C-k 줄의 시작 부분에 있어야 함) 그리고 개행 문자도 죽입니다(다시 말하지만 뭔가 C-k 하지 않습니다).

이 작업을 수행하는 또 다른 기능이 있습니다.내 버전은 킬 링을 건드리지 않으며 커서는 원본에 있던 새 줄에서 끝납니다.활성화된 경우(일시적 표시 모드) 영역을 복제하고, 그렇지 않은 경우 기본적으로 선을 복제합니다.또한 접두사 arg가 주어지면 여러 복사본을 만들고 음수 접두사 arg가 주어지면 원래 줄을 주석 처리합니다(이것은 이전 버전을 유지하면서 명령/문의 다른 버전을 테스트하는 데 유용합니다).

(defun duplicate-line-or-region (&optional n)
  "Duplicate current line, or region if active.
With argument N, make N copies.
With negative N, comment out original line and use the absolute value."
  (interactive "*p")
  (let ((use-region (use-region-p)))
    (save-excursion
      (let ((text (if use-region        ;Get region if active, otherwise line
                      (buffer-substring (region-beginning) (region-end))
                    (prog1 (thing-at-point 'line)
                      (end-of-line)
                      (if (< 0 (forward-line 1)) ;Go to beginning of next line, or make a new one
                          (newline))))))
        (dotimes (i (abs (or n 1)))     ;Insert N times, or once if not specified
          (insert text))))
    (if use-region nil                  ;Only if we're working with a line (not a region)
      (let ((pos (- (point) (line-beginning-position)))) ;Save column
        (if (> 0 n)                             ;Comment out original with negative arg
            (comment-region (line-beginning-position) (line-end-position)))
        (forward-line 1)
        (forward-char pos)))))

나는 그것을 바인딩했다 C-c d:

(global-set-key [?\C-c ?d] 'duplicate-line-or-region)

이는 모드 등으로 다시 할당되어서는 안 됩니다. C-c 그 뒤에 단일(수정되지 않은) 문자가 오는 것은 사용자 바인딩을 위해 예약되어 있습니다.

.emacs 파일에 Nathan을 추가하는 것이 좋은 방법이지만 교체하여 약간 단순화할 수 있습니다.

  (open-line 1)
  (next-line 1)

~와 함께

  (newline)

굽힐 수 있는

(defun duplicate-line()
  (interactive)
  (move-beginning-of-line 1)
  (kill-line)
  (yank)
  (newline)
  (yank)
)
(global-set-key (kbd "C-d") 'duplicate-line)

다른 곳에서는 줄 복제가 어떻게 작동하는지 잘 기억이 나지 않지만, 예전 SciTE 사용자로서 SciTE 방식에 대해 한 가지 마음에 들었던 점은 다음과 같습니다.커서 위치에 닿지 않습니다!위의 모든 레시피는 제게는 충분하지 않았습니다. 제 히피 버전은 다음과 같습니다.

(defun duplicate-line ()
    "Clone line at cursor, leaving the latter intact."
    (interactive)
    (save-excursion
        (let ((kill-read-only-ok t) deactivate-mark)
            (toggle-read-only 1)
            (kill-whole-line)
            (toggle-read-only 0)
            (yank))))

표시와 현재 선택은 그대로 유지되므로 프로세스 중에 실제로 종료되는 것은 없습니다.

그런데, 왜 이렇게 멋지고 깔끔한 전체 줄 삭제 기능(C-S-백스페이스)이 있는데 커서를 움직이는 걸 그렇게 좋아하시나요?

melpa에서 중복 항목을 설치하십시오.

M-x 패키지 설치 RET 중복 항목

이 키 바인딩을 초기화 파일 :

(글로벌 세트 키(kbd "M-c") '중복된 것)

모르기 때문에 이번 골프 라운드는 슬로우볼로 시작하겠습니다.

Ctrl-K, y, y

' 나는 내 자신의 버전을 썼다 duplicate-line, 왜냐하면 나는 킬링 링을 망치고 싶지 않기 때문입니다.

  (defun jr-duplicate-line ()
    "EASY"
    (interactive)
    (save-excursion
      (let ((line-text (buffer-substring-no-properties
                        (line-beginning-position)
                        (line-end-position))))
        (move-end-of-line 1)
        (newline)
        (insert line-text))))
  (global-set-key "\C-cd" 'jr-duplicate-line)

나는 가지고있다 copy-from-above-command 키에 바인딩하여 사용하세요.XEmacs와 함께 제공되지만 GNU Emacs에 대해서는 모르겠습니다.

``Copy-Above-Command ''는 대화식 컴파일 된 LISP 기능입니다
-"/usr/share/xemacs/21.4.15/lisp/misc.elc"에서로드

선적 서류 비치: 이전 비 블랭크 라인에서 문자를 복사하십시오, 포인트 바로 위로 시작합니다.Arg 문자를 복사하지만 해당 줄의 끝을 지나치지는 않습니다.논쟁이 주어지지 않으면 나머지 라인 전체를 복사하십시오.복사 된 문자는 포인트 전에 버퍼에 삽입됩니다.

C-a C-k C-k C-y C-y

.emacs에 갖고 싶은 것은 다음과 같습니다.

(setq kill-whole-line t)

기본적으로 kill-line을 호출할 때마다 전체 줄과 개행 문자를 삭제합니다(예:C-k를 통해).그런 다음 추가 코드 없이 C-a C-k C-y C-y를 수행하여 라인을 복제할 수 있습니다.그것은 분해된다

C-a go to beginning of line
C-k kill-line (i.e. cut the line into clipboard)
C-y yank (i.e. paste); the first time you get the killed line back; 
    second time gives the duplicated line.

그러나 이것을 자주 사용하는 경우 전용 키 바인딩이 더 나은 아이디어일 수도 있지만 C-a C-k C-y C-y를 사용하는 것의 장점은 현재 줄 바로 아래가 아닌 다른 곳에 줄을 복제할 수 있다는 것입니다.

기본값은 이것에 대해 끔찍합니다.그러나 SlickEdit 및 TextMate처럼 작동하도록 Emacs를 확장할 수 있습니다. 즉, 선택된 텍스트가 없을 때 현재 줄을 복사/잘라낼 수 있습니다.

(transient-mark-mode t)
(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)))))

위 내용을 넣어주세요 .emacs.그런 다음 한 줄을 복사하려면 M-w.라인을 삭제하려면, C-w.라인을 복제하려면, C-a M-w C-y C-y C-y ....

나는 두 가지를 제외하고는 FraGGod의 버전을 좋아했습니다:(1) 버퍼가 이미 읽기 전용인지 여부는 확인하지 않습니다. (interactive "*"), (2) 마지막 줄이 비어 있으면(이 경우 줄을 삭제할 수 없기 때문에) 버퍼의 마지막 줄에서 실패하고 버퍼는 읽기 전용으로 유지됩니다.

이 문제를 해결하기 위해 다음과 같이 변경했습니다.

(defun duplicate-line ()
  "Clone line at cursor, leaving the latter intact."
  (interactive "*")
  (save-excursion
    ;; The last line of the buffer cannot be killed
    ;; if it is empty. Instead, simply add a new line.
    (if (and (eobp) (bolp))
        (newline)
      ;; Otherwise kill the whole line, and yank it back.
      (let ((kill-read-only-ok t)
            deactivate-mark)
        (toggle-read-only 1)
        (kill-whole-line)
        (toggle-read-only 0)
        (yank)))))

최근 Emacs에서는 줄의 어느 곳에서나 M-w를 사용하여 복사할 수 있습니다.그래서 그것은 다음과 같습니다:

M-w C-a RET C-y

어쨌든 나는 매우 복잡한 해결책을 보았습니다 ...

(defun duplicate-line ()
  "Duplicate current line"
  (interactive)
  (kill-whole-line)
  (yank)
  (yank))
(global-set-key (kbd "C-x M-d") 'duplicate-line)

라는 패키지가 있습니다 에이비 avy-copy-line 명령이 있습니다.해당 명령을 사용하면 창의 모든 줄에 문자 조합이 표시됩니다.그런 다음 조합을 입력하면 해당 줄이 표시됩니다.이는 지역에도 적용됩니다.그런 다음 두 가지 조합을 입력하면 됩니다.

여기에서 인터페이스를 볼 수 있습니다.

http://i68.tinypic.com/24fk5eu.png

@[케빈 코너]:내가 아는 한 꽤 가깝습니다.고려해야 할 유일한 다른 사항은 전원을 켜는 것입니다. kill-whole-line C-k에 개행 문자를 포함합니다.

활성 영역 없이 대화식으로 호출하는 경우 대신 한 줄을 COPY(M-w)하십시오.

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

활성 영역 없이 대화식으로 호출되면 대신 한 줄을 KILL(C-w)합니다.

(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))
     (message "Killed line")
     (list (line-beginning-position)
           (line-beginning-position 2)))))

또한 관련 메모에서는 다음과 같습니다.

(defun move-line-up ()
  "Move up the current line."
  (interactive)
  (transpose-lines 1)
  (forward-line -2)
  (indent-according-to-mode))

(defun move-line-down ()
  "Move down the current line."
  (interactive)
  (forward-line 1)
  (transpose-lines 1)
  (forward-line -1)
  (indent-according-to-mode))

(global-set-key [(meta shift up)]  'move-line-up)
(global-set-key [(meta shift down)]  'move-line-down)

Ctrl 키-케이, Ctrl 키-케이, (새 위치로의 위치) Ctrl 키-와이

을 추가하다 Ctrl 키- 줄의 시작 부분에서 시작하지 않는 경우.그리고 2번째 Ctrl 키-케이 개행 문자를 잡는 것입니다.텍스트만 원할 경우 제거할 수 있습니다.

제 취향대로 하나 씁니다.

(defun duplicate-line ()
  "Duplicate current line."
  (interactive)
  (let ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
        (cur-col (current-column)))
    (end-of-line) (insert "\n" text)
    (beginning-of-line) (right-char cur-col)))
(global-set-key (kbd "C-c d l") 'duplicate-line)

그러나 현재 행에 멀티바이트 문자(예:CJK 문자).이 문제가 발생하면 대신 다음을 시도해 보십시오.

(defun duplicate-line ()
  "Duplicate current line."
  (interactive)
  (let* ((text (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
         (cur-col (length (buffer-substring-no-properties (point-at-bol) (point)))))
    (end-of-line) (insert "\n" text)
    (beginning-of-line) (right-char cur-col)))
(global-set-key (kbd "C-c d l") 'duplicate-line)

이 기능은 라인 또는 지역별로 복제한 다음 포인트 및/또는 활성 지역을 예상대로 남겨둔다는 점에서 JetBrains의 구현과 일치해야 합니다.

대화형 양식을 둘러싸는 래퍼입니다.

(defun wrx/duplicate-line-or-region (beg end)
  "Implements functionality of JetBrains' `Command-d' shortcut for `duplicate-line'.
   BEG & END correspond point & mark, smaller first
   `use-region-p' explained: 
   http://emacs.stackexchange.com/questions/12334/elisp-for-applying-command-to-only-the-selected-region#answer-12335"
  (interactive "r")
  (if (use-region-p)
      (wrx/duplicate-region-in-buffer beg end)
    (wrx/duplicate-line-in-buffer)))

이것을 부르는 것은,

(defun wrx/duplicate-region-in-buffer (beg end)
  "copy and duplicate context of current active region
   |------------------------+----------------------------|
   |        before          |           after            |
   |------------------------+----------------------------|
   | first <MARK>line here  | first line here            |
   | second item<POINT> now | second item<MARK>line here |
   |                        | second item<POINT> now     |
   |------------------------+----------------------------|
   TODO: Acts funky when point < mark"
  (set-mark-command nil)
  (insert (buffer-substring beg end))
  (setq deactivate-mark nil))

아니면 이거

(defun wrx/duplicate-line-in-buffer ()
  "Duplicate current line, maintaining column position.
   |--------------------------+--------------------------|
   |          before          |          after           |
   |--------------------------+--------------------------|
   | lorem ipsum<POINT> dolor | lorem ipsum dolor        |
   |                          | lorem ipsum<POINT> dolor |
   |--------------------------+--------------------------|
   TODO: Save history for `Cmd-Z'
   Context: 
   http://stackoverflow.com/questions/88399/how-do-i-duplicate-a-whole-line-in-emacs#answer-551053"
  (setq columns-over (current-column))
  (save-excursion
    (kill-whole-line)
    (yank)
    (yank))
  (let (v)
    (dotimes (n columns-over v)
      (right-char)
      (setq v (cons n v))))
  (next-line))

그리고 나는 이것을 Meta+Shift+D에 묶었습니다.

(global-set-key (kbd "M-D") 'wrx/duplicate-line-or-region)

접두사 인수를 사용하고 직관적인 동작은 무엇입니까?

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

커서는 마지막 줄에 유지됩니다.또는 다음 몇 줄을 한 번에 복제하기 위해 접두사를 지정할 수도 있습니다.

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

나는 접두사 인수의 동작을 전환하기 위해 래퍼 함수를 ​​사용하여 두 가지를 자주 사용하고 있습니다.

그리고 키 바인딩:(global-set-key (kbd "C-S-d") 'duplicate-line)

;; 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.

위의 elisp를 init.el에 추가하면 이제 전체 줄 잘라내기/복사 기능을 사용할 수 있습니다. 그런 다음 F3 F4를 사용하여 한 줄을 복제할 수 있습니다.

가장 간단한 방법은 Chris Conway의 방법입니다.

C-a C-SPACE C-n M-w C-y

이것이 EMACS에서 요구하는 기본 방식입니다.제 생각에는 표준을 사용하는 것이 더 좋습니다.나는 EMACS에서 자신만의 키 바인딩을 사용자 정의하는 데 항상 주의를 기울입니다.EMACS는 이미 충분히 강력하므로 자체 키 바인딩에 적응하기 위해 최선을 다해야 한다고 생각합니다.

조금 길긴 하지만 익숙해지면 빨리 할 수 ​​있고 재미있을 것 같아요!

현재 라인을 복제하는 기능은 다음과 같습니다.접두사 인수를 사용하면 줄이 여러 번 복제됩니다.예: C-3 C-S-o 현재 줄을 세 번 복제합니다.킬링은 바뀌지 않습니다.

(defun duplicate-lines (arg)
  (interactive "P")
  (let* ((arg (if arg arg 1))
         (beg (save-excursion (beginning-of-line) (point)))
         (end (save-excursion (end-of-line) (point)))
         (line (buffer-substring-no-properties beg end)))
    (save-excursion
      (end-of-line)
      (open-line arg)
      (setq num 0)
      (while (< num arg)
        (setq num (1+ num))
        (forward-line 1)
        (insert-string line))
      )))

(global-set-key (kbd "C-S-o") 'duplicate-lines)

나는 이 모든 복잡한 해결책을 믿을 수 없습니다.이는 두 가지 키 입력입니다.

<C-S-backspace> kill-whole-line 명령을 실행합니다.

C-/ 실행 취소 명령을 실행합니다.

그래서 <C-S-backspace> C-/ 전체 줄을 "복사"합니다(종료 및 실행 취소).

물론 이것을 숫자 및 음수 인수와 결합하여 앞으로 또는 뒤로 여러 줄을 삭제할 수 있습니다.

Chris Conway가 선택한 답변과 관련하여 이것이 더 자연스럽게 느껴집니다.

(글로벌 세트 키 "\C-c\C-d" "\C-a\C-\C-n\M-w\C-y\C-p\C-e")

이를 통해 간단히 \C-c\C-d 키 입력을 반복하여 라인을 여러 번 복제할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top