2014-06-28 27 views
3

作爲一名測試工程師,我經常像下面一些意大利麪條代碼:如何將emacs C++模式中的代碼對齊到「;」要麼 」,」?

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

爲了美觀,我想將它們對齊由定義的列「;」,如下圖所示:

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

emacs有沒有辦法做到這一點? (我知道M-X對準但像期望它是不是做一個整潔的工作。) 希望的方法也應該一起工作「」太。

回答

2

在這種特殊情況下,你可以在assert對齊,而該區域是活躍:

M-x align-regexp assert RET 

在一般情況下,這裏的答案是類似的my answer to your other question第一部分:

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

將變成

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

變成

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

同樣的技術可以被用來在逗號對齊。只需用,替換正則表達式中的;即可。

+0

似乎是一個很好的通用技術。讓我有一點時間玩和驗證它。 – modeller

+0

@ user3701346,當您想要在匹配的東西之前調整空格*時,最容易使用,例如在這種情況下用'assert'。當你想調整*之後的空白*時,這很棘手,就像上面的通用解決方案一樣,匹配';'。這只是因爲'align-regexp'的默認交互行爲會自動將您的模式前面的空格視爲要修改的內容。 – Chris

+0

我忽略了這個答案。現在我接受並投票表決。 – modeller

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

只要M-x align的作品,如果你寫這個代碼。

+0

不錯的解決方案,我從來沒有定製'align-rules-list'。 – Chris