我经常发现自己像这样转换代码:
before do
:something
end至
before { :something }有没有办法在emacs中自动执行这项任务?我使用ruby-mode和rinary,但它们在这里没有太大帮助。
发布于 2012-09-19 06:38:44
Emacs24.3和更高版本中的ruby-mode具有命令ruby-toggle-block。
默认绑定是C-c {。
发布于 2011-07-21 06:46:11
我相信它可以变得更短更好,但目前我有以下几点:
(defun ruby-get-containing-block ()
(let ((pos (point))
(block nil))
(save-match-data
(save-excursion
(catch 'break
;; If in the middle of or at end of do, go back until at start
(while (and (not (looking-at "do"))
(string-equal (word-at-point) "do"))
(backward-char 1))
;; Keep searching for the containing block (i.e. the block that begins
;; before our point, and ends after it)
(while (not block)
(if (looking-at "do\\|{")
(let ((start (point)))
(ruby-forward-sexp)
(if (> (point) pos)
(setq block (cons start (point)))
(goto-char start))))
(if (not (search-backward-regexp "do\\|{" (point-min) t))
(throw 'break nil))))))
block))
(defun ruby-goto-containing-block-start ()
(interactive)
(let ((block (ruby-get-containing-block)))
(if block
(goto-char (car block)))))
(defun ruby-flip-containing-block-type ()
(interactive)
(save-excursion
(let ((block (ruby-get-containing-block)))
(goto-char (car block))
(save-match-data
(let ((strings (if (looking-at "do")
(cons
(if (= 3 (count-lines (car block) (cdr block)))
"do\\( *|[^|]+|\\)? *\n *\\(.*?\\) *\n *end"
"do\\( *|[^|]+|\\)? *\\(\\(.*\n?\\)+\\) *end")
"{\\1 \\2 }")
(cons
"{\\( *|[^|]+|\\)? *\\(\\(.*\n?\\)+\\) *}"
(if (= 1 (count-lines (car block) (cdr block)))
"do\\1\n\\2\nend"
"do\\1\\2end")))))
(when (re-search-forward (car strings) (cdr block) t)
(replace-match (cdr strings) t)
(delete-trailing-whitespace (match-beginning 0) (match-end 0))
(indent-region (match-beginning 0) (match-end 0))))))))有两个函数要绑定到键:ruby-goto-containing-block-start和ruby-flip-containing-block-type。
这两个命令都可以在块中的任何地方工作,并且希望它们可以跳过应该跳过的块-尽管如果您正在转换为短的块格式,这应该不是问题。
ruby-flip-containing-block-type折叠三行做..将块结束为单行{},反之亦然。如果这些块不是精确的3行和1行长,它应该不去管它们。
我现在正在我的ruby设置上使用它,所以我希望能有所改进。
发布于 2011-07-16 03:24:13
您可以使用跨越换行符的正则表达式。
/do(C-q C-j\?)*(.*)(C-q C-j\?)*end/
并替换为
{\2 } 像这样的东西可能行得通。然后你可以定制它,直到它做你需要的事情,并将它绑定到一个宏上,这样你就可以在任何时候把它拿出来,给你的朋友留下深刻的印象!
我在vi (我选择的编辑器)中测试了上述正则表达式,它们正常工作。因此,一些类似的东西应该对你有效。
有关更多信息,请务必查看emacs wiki!
https://stackoverflow.com/questions/6712076
复制相似问题