首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

跟小弟我学习GNU Emacs - 13

2012-09-08 
跟我学习GNU Emacs - 13 4.3.2 对代码的缩进样式进行定制C语言(或者其他程序设计语言)的编程风(coding sty

跟我学习GNU Emacs - 13

 

4.3.2 对代码的缩进样式进行定制

C语言(或者其他程序设计语言)的编程风格(coding style)是很个性化的。C程序员是通过各种书籍或者别人写的各种代码片断来学习这种语言的,但他们迟早会形成自己的风格,而这些个性化的风格不见得会与他们在学习时接触到的一模一样。

C模式的缩进行为恰恰是这种语言学习手段的体现,它还提供很多用来对其缩进行为进行定制的功能。在最简单的层次上,可以挑选一种现成的缩进样式来使用;然后,如果还不满意,就可以对挑选出来的样式进行定制。甚至可以从点滴开始创建自己的样式,后一种做法需要对Emacs LISP程序设计知识有比较深的掌握,还需要有一点勇敢精神。

“M-x c-set-style”命令的作用就是让从现成的缩进样式里挑出一个来使用。这个命令会提示用户输入自己想要的缩进样式的名称,此时最简单的方法是按下TAB键—Emacs的自动补足命令,它将打开一个“*Completions*”编辑缓冲区,那里面将列出所有的可选项。如果想选择某种缩进样式,输入它的名称再按下回车键即可。

Emacs已经为我们提前预备了一些缩进样式,它在默认情况下加载的缩进样式见表4-3

 

Table 4-4. Built-in cc-mode indentation styles

Style

Description

bsd

Style used in code for BSD-derived versions of Unix.

cc-mode

The default coding style, from which all others are derived .

ellemtel

Style used in C++ documentation from Ellemtel Telecommunication Systems Laboratories in Sweden .

gnu

Style used in C code for Emacs itself and other GNU-related programs .

java

Style used in Java code (the default for Java mode).

k&r

Style of the classic text on C, Kernighan and Ritchie's The C Programming Language .

linux

Style used in C code that is part of the Linux kernel.

python

Style used in python extensions.

stroustrup

C++ coding style of the standard reference work, Bjarne Stroustrup's The C++ Programming Language .

user

Customizations you make to .emacs or via Custom (see Chapter 10). All other styles inherit these customizations if you set them.

whitesmith

Style used in Whitesmith Ltd.'s documentation for their C and C++ compilers .

 

为了让大家对这些编程风格有一些了解,我们做如下演示:

 

int times (x, y)int x, y;{int i;int result = 0;for (i = 0; i < x; i++) {result += y;}}

如果把这段代码选取为一个文本块,并按下“C-M-\”组合键(命令名是indent-region),那么Emacs将按其默认的缩进样式,把这段代码重新排版为下面这个样子:

int times (x, y)    int x, y;{    int i;    int result = 0;    for (i = 0; i < x; i++)         {            result += y;        }}

 

    用“C-c”命令选择使用“K&R”风格,然后对段落进行重排,代码将排列为下面这个样子:

int times (x, y)int x, y;{     int i;     int result = 0;     for (i = 0; i < x; i++)     {          result += y;     }}

 

如果想切换到GNU分格的缩进样式,请在选中风格“GNU”后对代码块进行重排;结果将是:

int times (x, y)     int x, y;{  int i;  int result = 0;  for (i = 0; i < x; i++)    {      result += y;    }}

 

    选好编程风格之后,把下面这条语句添加到“.emacs”文件里就可以永久地设置它:

(add-hook 'c-mode-hook
 
       '(lambda ( )
 
         (c-set-style "stylename")))

 

别忘了在第2行的“(lambda”的前面加上一个单引号就可以了。

 

每种编程风格都有它自己的特点,而让Emacs把这些特点都实现出来,可并不是件轻而易举的事情。虽然Emacs的早期版本定义了几个用来控制缩进层次的变量,但数量并不是很多;他们不仅不容易使用,而且说老实话,也很难百分之百地从细节上区分出不同的编程风格。

换句话说,如今的C模式是靠把成组的变量,和它们的值分门别类地归纳进样式而实现出各种编程风格的。Emacs用了一个非常庞大的变量(他的名字是c-style-alist)来容纳全体缩进样式和他们的关联信息。各位可以通过修改现有缩进样式里的变量值。或者自行添加缩进样式这两种方法来对这个大家伙进行定制。具体细节请查阅自己系统得Emacs LISP目录里的cc-mode.el文件。

 

 

热点排行