Emacs,ruby:将结束块转换为花括号,反之亦然

我经常发现自己转换代码如下:

before do :something end 

 before { :something } 

有没有办法在emacs中自动执行此任务? 我使用ruby-mode和rinary,但它们在这里不太有用。

Emacs 24.3中的ruby-mode和更新的命令ruby-toggle-block

默认绑定是Cc {

我相信它可以做得更短更好,但现在我有以下几点:

 (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 (ie 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-startruby-flip-containing-block-type

这两个命令都可以在块内的任何地方工作,并且希望它们可以跳过应该跳过的块 – 尽管如果要转换为短块格式,这应该不是问题。

ruby-flip-containing-block-type三行do .. end block折叠为单行{},反之亦然。 如果块不是正好3行而是1行长,那么它应该不管它们。

我现在在我的ruby设置上使用它,所以我希望改进。

您可以使用跨越换行符的正则表达式。

/ do(Cq Cj \?)*(。*)(Cq Cj \?)* end /

并替换为

 {\2 } 

这样的事情可行。 然后,您可以自定义它,直到它完全符合您的需要并将其绑定到宏,以便您可以随时将其甩出并给您的朋友留下深刻印象!

我在vi(我选择的编辑器)中测试了上面的正则表达式并且他们工作了。 所以类似的东西应该适合你。

有关更多信息,请务必查看emacs wiki !

这是一个function。 我是一名elisp初学者。 它只走一条路; 从do到{。 请让我知道这对你有没有用。