2

emacs n00b 在这里。

我每周至少遇到一次这个问题,我有一个函数调用,每行一个参数,但我想重新格式化,使所有参数都放在一行,即我想从:

f(
  x,
  y,
  z
);

至:

f(x, y, z);

最好的方法是什么?

4

2 回答 2

6

In general, a simple approach to custom reformatting requirements is to create a keyboard macro which does the required editing in a generic way.

Abilities like moving across sexps & balanced expressions, searching and replacing within regions, and narrowing and widening the buffer all make this sort of thing pretty straightforward.

You can then give the macro a name, output its definition into your init file, and bind it to a key for future usage, all with no elisp knowledge required.

C-hig (emacs) Keyboard Macros RET

Edit: (for "Emacs n00bs" everywhere).

DO learn how to use keyboard macros. The learning curve is pretty shallow1, and they will pay amazing dividends in the long term.

Once you've learned how they work, force yourself to use them: Whenever you encounter a problem, say to yourself "Can I do this with a keyboard macro?" and if you think the answer is yes, then give it a try.

If you don't make yourself use them to begin with, you probably won't often think about them when use-cases crop up; but once they're a familiar part of your tool kit you'll find yourself using them very regularly.

1 Shallow, but probably longer than you expect, as you gradually come to realise just how much you can actually accomplish with the things. My own moment of clarity came when it occurred to me that I wasn't restricted to a single buffer, and correlating/extracting/transforming data from multiple buffers was something I could automate easily.

And of course macros can do anything that you can do, so their power grows with your own knowledge of Emacs.

于 2013-05-29T23:00:51.917 回答
2

好吧,我怀疑这是最好的方法,但我还是写了一个函数。所以这里是:

(defun format-args-column-to-inline()
  "Takes a c-style function whose arguments listed one per line and puts them inline."
  (interactive)
  (beginning-of-line 1)
  (re-search-forward "(")
  (forward-char -1)
  (let ((start (point)))
    (save-restriction
      (save-excursion
        (forward-sexp 1)
        (narrow-to-region start (point)))
      (while (re-search-forward "$")
        (progn
          (delete-forward-char 1)
          (just-one-space 1))))))

将光标放在第一行的某处并调用该函数。

编辑:刚刚看到你想要一些稍微不同的东西。这个函数的输出是f( x, y, z );[注意参数列表的尾随和前导空格]。

于 2013-05-29T22:56:05.367 回答