【问题标题】:Paste text aligned to cursor in emacs在emacs中粘贴与光标对齐的文本
【发布时间】:2021-08-14 10:45:42
【问题描述】:

有没有办法从剪贴板粘贴与光标位置对齐的文本:

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

默认情况下我得到:

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

但我也希望看到最后两行与两个空格对齐。 (当然,我可以选择文本并按制表符对齐,但这是附加操作)

【问题讨论】:

    标签: emacs clipboard indentation


    【解决方案1】:

    自己实现了所需的解决方案(对于丑陋的 lisp 感到抱歉)。关键是粘贴文本没有对齐,而只是由原始请求中描述的光标列空间打算的

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

    【讨论】:

      【解决方案2】:

      基本上,您需要对新粘贴的代码进行缩进。我多年来一直使用以下代码:

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

      此代码扩展了绑定到C-y 的标准yank 命令,如果当前模式在yank-indent-modes 中定义的模式列表中,那么它将在粘贴的sn-p 上执行indent-region .

      附:您可能还需要在yank-pop 命令上添加相同的defadvice

      【讨论】:

        猜你喜欢
        • 2011-10-29
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        • 1970-01-01
        • 2011-04-26
        • 1970-01-01
        • 2011-07-29
        • 1970-01-01
        相关资源
        最近更新 更多