How to align codes in emacs C++ mode to “;” or “,”?

匿名 (未验证) 提交于 2019-12-03 08:51:18

问题:

As a test engineer, I often have some spaghetti code like below:

  int *const cpe = &n; assert(42 == *cpe);   int *const cpf = &cn; assert(42 == *cpf);   int *const cpg = pcn; assert(42 == *cpg);   int *const cph = cpcn; assert(42 == *cph); 

For aesthetics, I would like to align them in columns defined by ";", like below:

  int *const cpe = &n;   assert(42 == *cpe);   int *const cpf = &cn;  assert(42 == *cpf);   int *const cpg = pcn;  assert(42 == *cpg);   int *const cph = cpcn; assert(42 == *cph); 

Is there a way in emacs to do this? (I know M-x align but it is not doing a neat job like desired.) Hopefully the method should also work with "," too.

回答1:

In this particular case, you can just align on assert while the region is active:

M-x align-regexp assert RET 

In general, the answer here is similar to the first part of my answer to your other question:

C-u M-x align-regexp RET ;\(\s-*\) RET RET RET n 

will turn

  int *const cpe = &n; assert(42 == *cpe);   int *const cpf = &cn; assert(42 == *cpf);   int *const cpg = pcn; assert(42 == *cpg);   int *const cph = cpcn; assert(42 == *cph); 

into

  int *const cpe = &n;   assert(42 == *cpe);   int *const cpf = &cn;  assert(42 == *cpf);   int *const cpg = pcn;  assert(42 == *cpg);   int *const cph = cpcn; assert(42 == *cph); 

The same technique can be used to align on commas. Just replace the ; in the regular expression with ,.



回答2:

(add-to-list 'align-rules-list              '(c-assignment1                (regexp . "[=;]\\(\\s-*\\)")                (mode   . '(c-mode))                (repeat . t))) 

Simply M-x align works too, if you write this code.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!