https://wiki.archlinux.org/api.php?action=feedcontributions&user=Jaurung&feedformat=atomArchWiki - User contributions [en]2024-03-19T02:27:58ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=239408Emacs (简体中文)2012-12-08T07:08:02Z<p>Jaurung: translate parts of "fast start"</p>
<hr />
<div>[[Category:Text editors (简体中文)]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{TranslationStatus (简体中文)|Emacs|2012-10-17|229169}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]]是一个可扩展,可自定制,自带文档的实时显示编辑器。Emacs的核心构建在[[Wikipedia:Emacs Lisp|Emacs Lisp]]解释器之上,其中Emacs Lisp是大部分Emacs的内建函数和拓展模块的实现语言。尽管Emacs在命令行界面下(CLI)工作良好,但还是将GTK作为GNU Emacs22的默认X工具包。在文本编辑能力上,Emacs常常拿来和[[vim]]比较。<br />
<br />
== 安装 ==<br />
Emacs有众多变体发行版本(有时候称作''emacsen''). 最常见的莫过于 [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, 在[[Official Repositories]]可以找到.<br />
<br />
另外一个常见的变体就是{{Pkg|xemacs}}.<br />
<br />
== 快速入门 ==<br />
尽管Emacs十分的复杂, 但了解下完全自定义和高扩展带来的好处并花不了多少时间. 另外, 多种多样的拓展模块让Emacs可以为任何文本编辑的需求配置强大的环境.<br />
<br />
Emacs自带一个很优秀的入门教程,你可以点击欢迎界面上的第一个链接来打开它; 或者从菜单栏中选择''Help->Emacs Tutorial'',或者按'F1'键然后按't'. 我们设计这篇文章来为你在Emacs入门学习中提供额外的资源.<br />
<br />
Emacs也包括一系列引用链接,既有适合初学者的内容,也有骨灰级玩家所喜爱的.参见{{ic|/usr/share/emacs/<version>/etc/refcards/}} (将<version>换成你的emacs版本).<br />
<br />
===运行Emacs===<br />
====常见方式====<br />
打开Emacs:<br />
<br />
$ emacs<br />
<br />
从终端中使用:<br />
<br />
$ emacs -nw<br />
<br />
也可以马上打开一篇文章:<br />
<br />
$ emacs filename.txt<br />
<br />
====作为守护进程====<br />
Emacs由于每次启动都需要加载.emacs配置文件,所以打开时候比较慢. 从Emacs23开始, Emacs可以以守护进程的形式运行,这样每个用户都可以链接到Emacs. 以守护进程运行Emacs:<br />
<br />
$ emacs --daemon<br />
<br />
你可能在启动时打开一个守护进程,然后再将守护进程链接到窗口.另外,也可以将图形和终端客户端同时链接到守护进程上,这样启动通行界面速度就很快了.<br />
<br />
如果你仅仅想链接到守护进程,用下面的命令(注意在图形这个命令会打开一个图形客户端note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===基本术语和约定===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===移动===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===文件和缓冲区===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===编辑===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===移除,召回和区域===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===查找和替换===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===缩进和前缀参数===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===窗口和外框架===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===获得帮助===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===模式===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==提示和技巧==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===键盘宏和寄存器===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===正则表达式===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===定制===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== 拓展模块 ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== 问题的解决方法 ==<br />
<br />
===彩色输出的问题===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===菜单显示为空===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== X 窗口下的字符显示问题 ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== 启动速度慢 ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====错误的网络配置====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====初始化文件加载慢====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== 不能打开文件: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== 替代方案 ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== 资源 ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=239405Emacs (简体中文)2012-12-08T06:40:56Z<p>Jaurung: </p>
<hr />
<div>[[Category:Text editors (简体中文)]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{TranslationStatus (简体中文)|Emacs|2012-10-17|229169}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]]是一个可扩展,可自定制,自带文档的实时显示编辑器。Emacs的核心构建在[[Wikipedia:Emacs Lisp|Emacs Lisp]]解释器之上,其中Emacs Lisp是大部分Emacs的内建函数和拓展模块的实现语言。尽管Emacs在命令行界面下(CLI)工作良好,但还是将GTK作为GNU Emacs22的默认X工具包。在文本编辑能力上,Emacs常常拿来和[[vim]]比较。<br />
<br />
== 安装 ==<br />
Emacs有众多变体发行版本(有时候称作''emacsen''). 最常见的莫过于 [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, 在[[Official Repositories]]可以找到.<br />
<br />
另外一个常见的变体就是{{Pkg|xemacs}}.<br />
<br />
== 快速入门 ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===运行Emacs===<br />
====常见方式====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====作为守护进程====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===基本术语和约定===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===移动===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===文件和缓冲区===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===编辑===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===移除,召回和区域===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===查找和替换===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===缩进和前缀参数===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===窗口和外框架===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===获得帮助===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===模式===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==提示和技巧==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===键盘宏和寄存器===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===正则表达式===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===定制===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== 拓展模块 ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== 问题的解决方法 ==<br />
<br />
===彩色输出的问题===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===菜单显示为空===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== X 窗口下的字符显示问题 ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== 启动速度慢 ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====错误的网络配置====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====初始化文件加载慢====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== 不能打开文件: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== 替代方案 ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== 资源 ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=239404Emacs (简体中文)2012-12-08T06:40:29Z<p>Jaurung: /* 安装 */</p>
<hr />
<div>[[Category:Text editors (简体中文)]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{TranslationStatus (简体中文)|Emacs|2012-10-17|229169}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]]是一个可拓展,可自定制,自带文档的实时显示编辑器。Emacs的核心构建在[[Wikipedia:Emacs Lisp|Emacs Lisp]]解释器之上,其中Emacs Lisp是大部分Emacs的内建函数和拓展模块的实现语言。尽管Emacs在命令行界面下(CLI)工作良好,但还是将GTK作为GNU Emacs22的默认X工具包。在文本编辑能力上,Emacs常常拿来和[[vim]]比较。<br />
<br />
== 安装 ==<br />
Emacs有众多变体发行版本(有时候称作''emacsen''). 最常见的莫过于 [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, 在[[Official Repositories]]可以找到.<br />
<br />
另外一个常见的变体就是{{Pkg|xemacs}}.<br />
<br />
== 快速入门 ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===运行Emacs===<br />
====常见方式====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====作为守护进程====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===基本术语和约定===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===移动===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===文件和缓冲区===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===编辑===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===移除,召回和区域===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===查找和替换===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===缩进和前缀参数===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===窗口和外框架===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===获得帮助===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===模式===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==提示和技巧==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===键盘宏和寄存器===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===正则表达式===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===定制===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== 拓展模块 ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== 问题的解决方法 ==<br />
<br />
===彩色输出的问题===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===菜单显示为空===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== X 窗口下的字符显示问题 ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== 启动速度慢 ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====错误的网络配置====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====初始化文件加载慢====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== 不能打开文件: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== 替代方案 ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== 资源 ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=239403Emacs (简体中文)2012-12-08T06:39:45Z<p>Jaurung: translate the section of "Installation"</p>
<hr />
<div>[[Category:Text editors (简体中文)]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{TranslationStatus (简体中文)|Emacs|2012-10-17|229169}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]]是一个可拓展,可自定制,自带文档的实时显示编辑器。Emacs的核心构建在[[Wikipedia:Emacs Lisp|Emacs Lisp]]解释器之上,其中Emacs Lisp是大部分Emacs的内建函数和拓展模块的实现语言。尽管Emacs在命令行界面下(CLI)工作良好,但还是将GTK作为GNU Emacs22的默认X工具包。在文本编辑能力上,Emacs常常拿来和[[vim]]比较。<br />
<br />
== 安装 ==<br />
Emacs有众多变体发行版本 (有时候称作 ''emacsen''). 最常见的莫过于 [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, 在 [[Official Repositories]] 可以找到.<br />
<br />
另外一个常见的变体就是 {{Pkg|xemacs}}.<br />
<br />
== 快速入门 ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===运行Emacs===<br />
====常见方式====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====作为守护进程====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===基本术语和约定===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===移动===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===文件和缓冲区===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===编辑===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===移除,召回和区域===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===查找和替换===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===缩进和前缀参数===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===窗口和外框架===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===获得帮助===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===模式===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==提示和技巧==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===键盘宏和寄存器===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===正则表达式===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===定制===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== 拓展模块 ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== 问题的解决方法 ==<br />
<br />
===彩色输出的问题===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===菜单显示为空===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== X 窗口下的字符显示问题 ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== 启动速度慢 ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====错误的网络配置====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====初始化文件加载慢====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== 不能打开文件: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== 替代方案 ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== 资源 ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=239402Font configuration (简体中文)2012-12-08T06:35:05Z<p>Jaurung: /* 字节码解释器(BCI) */</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{TranslationStatus (简体中文)|Font_Configuration|2012-10-20|229345}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#补丁包]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==字体路径==<br />
<br />
由于应用程序需要知道它们所使用的字体的位置,所以必须对字体做良好的编目,以便于应用程序更好更快的访问它们。<br />
<br />
Fontconfig包含的字体路径是{{ic|/usr/share/fonts/}}和{{ic|~/.fonts/}}(Fontconfig会递归访问刚刚提到的目录)。为了简化管理和安装过程,当需要[[Fonts#Installation|添加字体]]时,推荐使用之前提到的路径。<br />
<br />
查看Fontconfig所包含的字体:<br />
$ fc-list : file<br />
<br />
参见{{ic|man fc-list}}以获得更多输出格式方面的信息。<br />
<br />
通过考察Xorg的log文件来检查Xorg包含的字体路径:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{小贴士|你也可以通过命令{{ic|xset q}}检查Xorg包含的字体路径。}}<br />
<br />
需要明确的是,Xorg不会像Fontconfig一样递归搜索{{ic|/usr/share/fonts/}}目录。如果要增加一个目录,必须使用一个完整目录:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
如果你想把字体路径设置到每一位用户,你可以通过添加下面的配置代码到文件{{ic|~/.xinitrc}},这样可以将字体路径添加进或者移除出默认的路径中:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
如果要查看Xorg包含的字体,可以使用这个命令{{ic|xlsfonts}}, 这个命令来自包{{Pkg|xorg-xlsfonts}}。<br />
<br />
==Fontconfig配置==<br />
<br />
Fontconfig的文档在[http://fontconfig.org/fontconfig-user.html fonts.conf]man页面中。<br />
<br />
通过对{{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}的修改可以完成对某个用户的配置, 而对{{ic|/etc/fonts/local.conf}}的修改则可以完成对每一位用户的配置. 如果用户的单独配置和全局配置不同,系统优先使用前者. 这些文件共用相同的语法.<br />
{{Note|配置文件和目录: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} 和 {{ic|~/.fontconfig/*.cache-*}} 从fontconfig 2.10.1开始已经被废弃([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) 未来的版本也不会默认读取这些文件当作配置依据. 分别用 {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} 和{{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} 来代替.}}<br />
<br />
Fontconfig 把所有的配置都放在一个中心文件中 ({{ic|/etc/fonts/fonts.conf}}). 这个文件会在fontconfig更新时被替换,注意你不应该编辑这个文件. 字体设置重要的程序会引用这个文件以获得当前字体配置和渲染配置.这个文件是一系列配置规则的集合包括全局配置文件({{ic|/etc/fonts/local.conf}}), 预设的配置 {{ic|/etc/fonts/conf.d/}}, 和用户的配置文件 ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|有一些桌面环境 (比如说 [[GNOME]] 和 [[KDE]]) 使用 ''Font Control Panel'' 会自动生成和重写用户字体配置文件. 对于这些桌面环境, 最好配合已定义的字体配置来得到需要的显示效果.}}<br />
<br />
配置文件使用[[Wikipedia:XML|XML]]格式并且需要一些格式头:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
文中的配置示例省略了这些标签.<br />
<br />
===预设===<br />
<br />
预设配置放在目录{ic|/etc/fonts/conf.avail}}中. 当给它们创建了[[Wikipedia:Symbolic link|符号链接]], 这些配置就被激活了.不管是对某一个用户还是全局配置, 这一规则是相同的.在{{ic|/etc/fonts/conf.d/README}}中有描述. 这些预设会通过匹配它们原先它们的单独设置文件来覆盖配置.<br />
<br />
举个例子,为了打开全局亚像素RGB渲染:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
为单个独立用户配置:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===反走样===<br />
<br />
[[Wikipedia:Font rasterization|字体光栅化]] 将矢量字体数据转化为位图数据以显示在屏幕上. 最后的效果可能由于[[Wikipedia:Aliasing|走样]]会出现锯齿. [[Wikipedia:Anti-aliasing|反走样]]默认被打开,这样可以增加字体边缘的分辨率.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===微调===<br />
<br />
[[Wikipedia:Font hinting|字体微调]] (这称作instructing) 是利于精确的指令来调整字体显示的轮廓,这样就可以用离散的网格来显示我需要的线条, 比如说像素网格.字体在[[Wikipedia:Dots per inch|DPI]]达到300之前不可能正确的显示.我们有两种hingting可以用.<br />
<br />
====字节码解释器(BCI)====<br />
使用normal hinting, TrueType 的hinting指令被freetype的字节码解释器所翻译解释. 这在hinting指令很好的字体上工作的很好.<br />
<br />
打开normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====自动微调器====<br />
从hinting中自动发现. 在hinting指令很好的字体上变现不如字节码解释器, 但是在hinting指令一般的字体上变现不错. autohinter和subpixel渲染当初设计时没有考虑它们协同工作的情形,所以不应该将它们放在一起使用.<br />
<br />
打开自动微调(auto-hinting):<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====微调字体====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===亚像素渲染===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD滤光器====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====高级LCD滤光器说明====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===取消粗体字的自动微调功能===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
===只对较大的字体打开反锯齿功能===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===替换字体===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===禁用点阵字型===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===为不完善的字体构建粗体风格和意大利体风格===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===改变规则重定义机制===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===fontconfig配置的例子===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==补丁包==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [https://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===恢复到未打补丁的包===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==没有fontconfig支持的应用程序==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==字体问题解决方法==<br />
<br />
===字体扭曲===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===较旧的GTK和QT应用程序===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==资源==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=239401Font configuration (简体中文)2012-12-08T06:34:10Z<p>Jaurung: translate parts of "Fontconfig configuration"</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{TranslationStatus (简体中文)|Font_Configuration|2012-10-20|229345}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#补丁包]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==字体路径==<br />
<br />
由于应用程序需要知道它们所使用的字体的位置,所以必须对字体做良好的编目,以便于应用程序更好更快的访问它们。<br />
<br />
Fontconfig包含的字体路径是{{ic|/usr/share/fonts/}}和{{ic|~/.fonts/}}(Fontconfig会递归访问刚刚提到的目录)。为了简化管理和安装过程,当需要[[Fonts#Installation|添加字体]]时,推荐使用之前提到的路径。<br />
<br />
查看Fontconfig所包含的字体:<br />
$ fc-list : file<br />
<br />
参见{{ic|man fc-list}}以获得更多输出格式方面的信息。<br />
<br />
通过考察Xorg的log文件来检查Xorg包含的字体路径:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{小贴士|你也可以通过命令{{ic|xset q}}检查Xorg包含的字体路径。}}<br />
<br />
需要明确的是,Xorg不会像Fontconfig一样递归搜索{{ic|/usr/share/fonts/}}目录。如果要增加一个目录,必须使用一个完整目录:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
如果你想把字体路径设置到每一位用户,你可以通过添加下面的配置代码到文件{{ic|~/.xinitrc}},这样可以将字体路径添加进或者移除出默认的路径中:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
如果要查看Xorg包含的字体,可以使用这个命令{{ic|xlsfonts}}, 这个命令来自包{{Pkg|xorg-xlsfonts}}。<br />
<br />
==Fontconfig配置==<br />
<br />
Fontconfig的文档在[http://fontconfig.org/fontconfig-user.html fonts.conf]man页面中。<br />
<br />
通过对{{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}的修改可以完成对某个用户的配置, 而对{{ic|/etc/fonts/local.conf}}的修改则可以完成对每一位用户的配置. 如果用户的单独配置和全局配置不同,系统优先使用前者. 这些文件共用相同的语法.<br />
{{Note|配置文件和目录: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} 和 {{ic|~/.fontconfig/*.cache-*}} 从fontconfig 2.10.1开始已经被废弃([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) 未来的版本也不会默认读取这些文件当作配置依据. 分别用 {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} 和{{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} 来代替.}}<br />
<br />
Fontconfig 把所有的配置都放在一个中心文件中 ({{ic|/etc/fonts/fonts.conf}}). 这个文件会在fontconfig更新时被替换,注意你不应该编辑这个文件. 字体设置重要的程序会引用这个文件以获得当前字体配置和渲染配置.这个文件是一系列配置规则的集合包括全局配置文件({{ic|/etc/fonts/local.conf}}), 预设的配置 {{ic|/etc/fonts/conf.d/}}, 和用户的配置文件 ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|有一些桌面环境 (比如说 [[GNOME]] 和 [[KDE]]) 使用 ''Font Control Panel'' 会自动生成和重写用户字体配置文件. 对于这些桌面环境, 最好配合已定义的字体配置来得到需要的显示效果.}}<br />
<br />
配置文件使用[[Wikipedia:XML|XML]]格式并且需要一些格式头:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
文中的配置示例省略了这些标签.<br />
<br />
===预设===<br />
<br />
预设配置放在目录{ic|/etc/fonts/conf.avail}}中. 当给它们创建了[[Wikipedia:Symbolic link|符号链接]], 这些配置就被激活了.不管是对某一个用户还是全局配置, 这一规则是相同的.在{{ic|/etc/fonts/conf.d/README}}中有描述. 这些预设会通过匹配它们原先它们的单独设置文件来覆盖配置.<br />
<br />
举个例子,为了打开全局亚像素RGB渲染:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
为单个独立用户配置:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===反走样===<br />
<br />
[[Wikipedia:Font rasterization|字体光栅化]] 将矢量字体数据转化为位图数据以显示在屏幕上. 最后的效果可能由于[[Wikipedia:Aliasing|走样]]会出现锯齿. [[Wikipedia:Anti-aliasing|反走样]]默认被打开,这样可以增加字体边缘的分辨率.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===微调===<br />
<br />
[[Wikipedia:Font hinting|字体微调]] (这称作instructing) 是利于精确的指令来调整字体显示的轮廓,这样就可以用离散的网格来显示我需要的线条, 比如说像素网格.字体在[[Wikipedia:Dots per inch|DPI]]达到300之前不可能正确的显示.我们有两种hingting可以用.<br />
<br />
====字节码解释器(BCI)====<br />
使用normal hinting, TrueType 的hinting指令被freetype的字节码解释器所翻译解释. 这在hinting指令很好的字体上工作的很好.<br />
<br />
为了打开normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====自动微调器====<br />
从hinting中自动发现. 在hinting指令很好的字体上变现不如字节码解释器, 但是在hinting指令一般的字体上变现不错. autohinter和subpixel渲染当初设计时没有考虑它们协同工作的情形,所以不应该将它们放在一起使用.<br />
<br />
打开自动微调(auto-hinting):<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====微调字体====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===亚像素渲染===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD滤光器====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====高级LCD滤光器说明====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===取消粗体字的自动微调功能===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
===只对较大的字体打开反锯齿功能===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===替换字体===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===禁用点阵字型===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===为不完善的字体构建粗体风格和意大利体风格===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===改变规则重定义机制===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===fontconfig配置的例子===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==补丁包==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [https://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===恢复到未打补丁的包===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==没有fontconfig支持的应用程序==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==字体问题解决方法==<br />
<br />
===字体扭曲===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===较旧的GTK和QT应用程序===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==资源==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=230669Font configuration (简体中文)2012-10-22T14:20:45Z<p>Jaurung: /* Fontconfig配置 */</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{TranslationStatus (简体中文)|Font_Configuration|2012-10-20|229345}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#补丁包]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==字体路径==<br />
<br />
由于应用程序需要知道它们所使用的字体的位置,所以必须对字体做良好的编目,以便于应用程序更好更快的访问它们。<br />
<br />
Fontconfig包含的字体路径是{{ic|/usr/share/fonts/}}和{{ic|~/.fonts/}}(Fontconfig会递归访问刚刚提到的目录)。为了简化管理和安装过程,当需要[[Fonts#Installation|添加字体]]时,推荐使用之前提到的路径。<br />
<br />
查看Fontconfig所包含的字体:<br />
$ fc-list : file<br />
<br />
参见{{ic|man fc-list}}以获得更多输出格式方面的信息。<br />
<br />
通过考察Xorg的log文件来检查Xorg包含的字体路径:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{小贴士|你也可以通过命令{{ic|xset q}}检查Xorg包含的字体路径。}}<br />
<br />
需要明确的是,Xorg不会像Fontconfig一样递归搜索{{ic|/usr/share/fonts/}}目录。如果要增加一个目录,必须使用一个完整目录:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
如果你想把字体路径设置到每一位用户,你可以通过添加下面的配置代码到文件{{ic|~/.xinitrc}},这样可以将字体路径添加进或者移除出默认的路径中:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
如果要查看Xorg包含的字体,可以使用这个命令{{ic|xlsfonts}}, 这个命令来自包{{Pkg|xorg-xlsfonts}}。<br />
<br />
==Fontconfig配置==<br />
<br />
Fontconfig的文档在[http://fontconfig.org/fontconfig-user.html fonts.conf]man页面中。<br />
<br />
Configuration can be done per-user through {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, and globally with {{ic|/etc/fonts/local.conf}}. The settings in the per-user configuration have precedence over the global configuration. Both these files use the same syntax.<br />
{{Note|Configuration files and directories: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} and {{ic|~/.fontconfig/*.cache-*}} are deprecated since fontconfig 2.10.1 ([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) and will not be read by default in the future versions of package. Use instead {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} and {{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} respectively.}}<br />
<br />
Fontconfig gathers all its configurations in a central file ({{ic|/etc/fonts/fonts.conf}}). This file is replaced during fontconfig updates and shouldn't be edited. Fontconfig-aware applications source this file to know available fonts and how they get rendered. This file is a conglomeration of rules from the global configuration ({{ic|/etc/fonts/local.conf}}), the configured presets in {{ic|/etc/fonts/conf.d/}}, and the user configuration file ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|For some desktop environments (such as [[GNOME]] and [[KDE]]) using the ''Font Control Panel'' will automatically create or overwrite the user font configuration file. For these desktop environments, it is best to match your already defined font configurations to get the expected behavior.}}<br />
<br />
Fontconfig configuration files use [[Wikipedia:XML|XML]] format and need these headers:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
The configuration examples in this article omit these tags.<br />
<br />
===预设===<br />
<br />
There are presets installed in the directory {{ic|/etc/fonts/conf.avail}}. They can be enabled by creating [[Wikipedia:Symbolic link|symbolic link]]s to them, both per-user and globally, as described in {{ic|/etc/fonts/conf.d/README}}. These presets will override matching settings in their respective configuration files.<br />
<br />
For example, to enable sub-pixel RGB rendering globally:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
To do the same but instead for a per-user configuration:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===反锯齿===<br />
<br />
[[Wikipedia:Font rasterization|Font rasterization]] converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to [[Wikipedia:Aliasing|aliasing]]. [[Wikipedia:Anti-aliasing|anti-aliasing]] is enabled by default and increases the apparent resolution of font edges.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===微调===<br />
<br />
[[Wikipedia:Font hinting|Font hinting]] (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, such as the pixel grid in a display. Fonts will not line up correctly without hinting until displays have 300 [[Wikipedia:Dots per inch|DPI]] or greater. Two types of hinting are available.<br />
<br />
====字节码解释器(BCI)====<br />
Using normal hinting, TrueType hinting instructions in the font are interpreted by freetype's Byte-Code Interpreter. This works best for fonts with good hinting instructions.<br />
<br />
To enable normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====自动微调器====<br />
Auto-discovery for hinting. This looks worse than normal hinting for fonts with good instructions, but better for those with poor or no instructions. The autohinter and subpixel rendering are not designed to work together and should not be used in combination.<br />
<br />
To enable auto-hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====微调字体====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===亚像素渲染===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD滤光器====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====高级LCD滤光器说明====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===取消粗体字的自动微调功能===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
===只对较大的字体打开反锯齿功能===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===替换字体===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===禁用点阵字型===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===为不完善的字体构建粗体风格和意大利体风格===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===改变规则重定义机制===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===fontconfig配置的例子===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==补丁包==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [http://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===恢复到未打补丁的包===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==没有fontconfig支持的应用程序==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==字体问题解决方法==<br />
<br />
===字体扭曲===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===较旧的GTK和QT应用程序===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==资源==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229399Font configuration (简体中文)2012-10-18T09:42:00Z<p>Jaurung: /* 字体路径 */</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[Category:简体中文]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{TranslationStatus (简体中文)|Font_Configuration|2012-10-17|222361}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#补丁包]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==字体路径==<br />
<br />
由于应用程序需要知道它们所使用的字体的位置,所以必须对字体做良好的编目,以便于应用程序更好更快的访问它们。<br />
<br />
Fontconfig包含的字体路径是{{ic|/usr/share/fonts/}}和{{ic|~/.fonts/}}(Fontconfig会递归访问刚刚提到的目录)。为了简化管理和安装过程,当需要[[Fonts#Installation|添加字体]]时,推荐使用之前提到的路径。<br />
<br />
查看Fontconfig所包含的字体:<br />
$ fc-list : file<br />
<br />
参见{{ic|man fc-list}}以获得更多输出格式方面的信息。<br />
<br />
通过考察Xorg的log文件来检查Xorg包含的字体路径:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{小贴士|你也可以通过命令{{ic|xset q}}检查Xorg包含的字体路径。}}<br />
<br />
需要明确的是,Xorg不会像Fontconfig一样递归搜索{{ic|/usr/share/fonts/}}目录。如果要增加一个目录,必须使用一个完整目录:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
如果你想把字体路径设置到每一位用户,你可以通过添加下面的配置代码到文件{{ic|~/.xinitrc}},这样可以将字体路径添加进或者移除出默认的路径中:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
如果要查看Xorg包含的字体,可以使用这个命令{{ic|xlsfonts}}, 这个命令来自包{{Pkg|xorg-xlsfonts}}。<br />
<br />
==Fontconfig配置==<br />
<br />
Fontconfig is documented in the [http://fontconfig.org/fontconfig-user.html fonts.conf] man page.<br />
<br />
Configuration can be done per-user through {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, and globally with {{ic|/etc/fonts/local.conf}}. The settings in the per-user configuration have precedence over the global configuration. Both these files use the same syntax.<br />
{{Note|Configuration files and directories: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} and {{ic|~/.fontconfig/*.cache-*}} are deprecated since fontconfig 2.10.1 ([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) and will not be read by default in the future versions of package. Use instead {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} and {{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} respectively.}}<br />
<br />
Fontconfig gathers all its configurations in a central file ({{ic|/etc/fonts/fonts.conf}}). This file is replaced during fontconfig updates and shouldn't be edited. Fontconfig-aware applications source this file to know available fonts and how they get rendered. This file is a conglomeration of rules from the global configuration ({{ic|/etc/fonts/local.conf}}), the configured presets in {{ic|/etc/fonts/conf.d/}}, and the user configuration file ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|For some desktop environments (such as [[GNOME]] and [[KDE]]) using the ''Font Control Panel'' will automatically create or overwrite the user font configuration file. For these desktop environments, it is best to match your already defined font configurations to get the expected behavior.}}<br />
<br />
Fontconfig configuration files use [[Wikipedia:XML|XML]] format and need these headers:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
The configuration examples in this article omit these tags.<br />
<br />
===预设===<br />
<br />
There are presets installed in the directory {{ic|/etc/fonts/conf.avail}}. They can be enabled by creating [[Wikipedia:Symbolic link|symbolic link]]s to them, both per-user and globally, as described in {{ic|/etc/fonts/conf.d/README}}. These presets will override matching settings in their respective configuration files.<br />
<br />
For example, to enable sub-pixel RGB rendering globally:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
To do the same but instead for a per-user configuration:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===反锯齿===<br />
<br />
[[Wikipedia:Font rasterization|Font rasterization]] converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to [[Wikipedia:Aliasing|aliasing]]. [[Wikipedia:Anti-aliasing|anti-aliasing]] is enabled by default and increases the apparent resolution of font edges.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===微调===<br />
<br />
[[Wikipedia:Font hinting|Font hinting]] (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, such as the pixel grid in a display. Fonts will not line up correctly without hinting until displays have 300 [[Wikipedia:Dots per inch|DPI]] or greater. Two types of hinting are available.<br />
<br />
====字节码解释器(BCI)====<br />
Using normal hinting, TrueType hinting instructions in the font are interpreted by freetype's Byte-Code Interpreter. This works best for fonts with good hinting instructions.<br />
<br />
To enable normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====自动微调器====<br />
Auto-discovery for hinting. This looks worse than normal hinting for fonts with good instructions, but better for those with poor or no instructions. The autohinter and subpixel rendering are not designed to work together and should not be used in combination.<br />
<br />
To enable auto-hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====微调字体====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===亚像素渲染===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD滤光器====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====高级LCD滤光器说明====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===取消粗体字的自动微调功能===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
===只对较大的字体打开反锯齿功能===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===替换字体===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===禁用点阵字型===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===为不完善的字体构建粗体风格和意大利体风格===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===改变规则重定义机制===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===fontconfig配置的例子===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==补丁包==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
=== ClearType包 ===<br />
<br />
These packages attempt to emulate ClearType, a type of font rendering that is used in Windows systems and is designed to work on both LCD and CRT monitors.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]]. Package names: {{AUR|freetype2-cleartype}} {{AUR|libxft-cleartype}} {{AUR|cairo-cleartype}}<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [http://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===恢复到未打补丁的包===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==没有fontconfig支持的应用程序==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==字体问题解决方法==<br />
<br />
===字体扭曲===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===较旧的GTK和QT应用程序===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==资源==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229398Font configuration (简体中文)2012-10-18T09:41:17Z<p>Jaurung: translate "font path"section</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[Category:简体中文]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{TranslationStatus (简体中文)|Font_Configuration|2012-10-17|222361}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#补丁包]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==字体路径==<br />
<br />
由于应用程序需要知道它们所使用的字体的位置,所以必须对字体做良好的编目,以便于应用程序更好更快的访问它们。<br />
<br />
Fontconfig包含的字体路径是{{ic|/usr/share/fonts/}}和{{ic|~/.fonts/}}(Fontconfig会递归访问刚刚提到的目录)。为了简化管理和安装过程,当需要[[Fonts#Installation|添加字体]]时,推荐使用之前提到的路径。<br />
<br />
浏览Fontconfig所包含的字体:<br />
$ fc-list : file<br />
<br />
参见{{ic|man fc-list}}以获得更多输出格式方面的信息。<br />
<br />
通过考察Xorg的log文件来检查Xorg包含的字体路径:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{小贴士|你也可以通过命令{{ic|xset q}}检查Xorg包含的字体路径。}}<br />
<br />
需要明确的是,Xorg不会像Fontconfig一样递归搜索{{ic|/usr/share/fonts/}}目录。如果要增加一个目录,必须使用一个完整目录:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
如果你想把字体路径设置到每一位用户,你可以通过添加下面的配置代码到文件{{ic|~/.xinitrc}},这样可以将字体路径添加进或者移除出默认的路径中:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
如果要查看Xorg包含的字体,可以使用这个命令{{ic|xlsfonts}}, 这个命令来自包{{Pkg|xorg-xlsfonts}}。<br />
<br />
==Fontconfig配置==<br />
<br />
Fontconfig is documented in the [http://fontconfig.org/fontconfig-user.html fonts.conf] man page.<br />
<br />
Configuration can be done per-user through {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, and globally with {{ic|/etc/fonts/local.conf}}. The settings in the per-user configuration have precedence over the global configuration. Both these files use the same syntax.<br />
{{Note|Configuration files and directories: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} and {{ic|~/.fontconfig/*.cache-*}} are deprecated since fontconfig 2.10.1 ([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) and will not be read by default in the future versions of package. Use instead {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} and {{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} respectively.}}<br />
<br />
Fontconfig gathers all its configurations in a central file ({{ic|/etc/fonts/fonts.conf}}). This file is replaced during fontconfig updates and shouldn't be edited. Fontconfig-aware applications source this file to know available fonts and how they get rendered. This file is a conglomeration of rules from the global configuration ({{ic|/etc/fonts/local.conf}}), the configured presets in {{ic|/etc/fonts/conf.d/}}, and the user configuration file ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|For some desktop environments (such as [[GNOME]] and [[KDE]]) using the ''Font Control Panel'' will automatically create or overwrite the user font configuration file. For these desktop environments, it is best to match your already defined font configurations to get the expected behavior.}}<br />
<br />
Fontconfig configuration files use [[Wikipedia:XML|XML]] format and need these headers:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
The configuration examples in this article omit these tags.<br />
<br />
===预设===<br />
<br />
There are presets installed in the directory {{ic|/etc/fonts/conf.avail}}. They can be enabled by creating [[Wikipedia:Symbolic link|symbolic link]]s to them, both per-user and globally, as described in {{ic|/etc/fonts/conf.d/README}}. These presets will override matching settings in their respective configuration files.<br />
<br />
For example, to enable sub-pixel RGB rendering globally:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
To do the same but instead for a per-user configuration:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===反锯齿===<br />
<br />
[[Wikipedia:Font rasterization|Font rasterization]] converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to [[Wikipedia:Aliasing|aliasing]]. [[Wikipedia:Anti-aliasing|anti-aliasing]] is enabled by default and increases the apparent resolution of font edges.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===微调===<br />
<br />
[[Wikipedia:Font hinting|Font hinting]] (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, such as the pixel grid in a display. Fonts will not line up correctly without hinting until displays have 300 [[Wikipedia:Dots per inch|DPI]] or greater. Two types of hinting are available.<br />
<br />
====字节码解释器(BCI)====<br />
Using normal hinting, TrueType hinting instructions in the font are interpreted by freetype's Byte-Code Interpreter. This works best for fonts with good hinting instructions.<br />
<br />
To enable normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====自动微调器====<br />
Auto-discovery for hinting. This looks worse than normal hinting for fonts with good instructions, but better for those with poor or no instructions. The autohinter and subpixel rendering are not designed to work together and should not be used in combination.<br />
<br />
To enable auto-hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====微调字体====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===亚像素渲染===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD滤光器====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====高级LCD滤光器说明====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===取消粗体字的自动微调功能===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
===只对较大的字体打开反锯齿功能===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===替换字体===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===禁用点阵字型===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===为不完善的字体构建粗体风格和意大利体风格===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===改变规则重定义机制===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===fontconfig配置的例子===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==补丁包==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
=== ClearType包 ===<br />
<br />
These packages attempt to emulate ClearType, a type of font rendering that is used in Windows systems and is designed to work on both LCD and CRT monitors.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]]. Package names: {{AUR|freetype2-cleartype}} {{AUR|libxft-cleartype}} {{AUR|cairo-cleartype}}<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [http://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===恢复到未打补丁的包===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==没有fontconfig支持的应用程序==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==字体问题解决方法==<br />
<br />
===字体扭曲===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===较旧的GTK和QT应用程序===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==资源==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Fengchao&diff=229194User talk:Fengchao2012-10-17T09:40:42Z<p>Jaurung: </p>
<hr />
<div>==关于Translation Status==<br />
请问如何添加Translation Status ? 格式是{{TranslationStatus (简体中文)|Xscreensaver|2012-10-04|226394}} ,这个最后一个是版本号吗?在哪儿找到的?<br />
: 看[[Template:TranslationStatus_(简体中文)]] 这个说明,参数是 oldid。我的浏览器在鼠标放到历史记录上之后,不点,也会显示oldid。 -- [[User:Fengchao|Fengchao]] ([[User talk:Fengchao|talk]]) 13:13, 3 October 2012 (UTC)<br />
==Translation Status中oldid的问题==<br />
你好,Fengchao,谢谢你对我在[[Bash_(简体中文)]]和[[Emacs_(简体中文)]]中所设置错误的oldid的修改,我之前阅读过[[Template:TranslationStatus_(简体中文)]] 的说明,上面写道'''在点击英文页面顶端的历史标签,在版本列表中点击翻译的版本,一般是最后一个''',我理解的最后一个是历史页面的最原始的一个,而你的意思是最新的一个,所以建议改为最新的一个版本。^_^ --[[User:Jaurung|Jaurung]] ([[User talk:Jaurung|talk]]) 17:39, 17 October 2012 (UTC)</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Fengchao&diff=229193User talk:Fengchao2012-10-17T09:40:08Z<p>Jaurung: </p>
<hr />
<div>==关于Translation Status==<br />
请问如何添加Translation Status ? 格式是{{TranslationStatus (简体中文)|Xscreensaver|2012-10-04|226394}} ,这个最后一个是版本号吗?在哪儿找到的?<br />
: 看[[Template:TranslationStatus_(简体中文)]] 这个说明,参数是 oldid。我的浏览器在鼠标放到历史记录上之后,不点,也会显示oldid。 -- [[User:Fengchao|Fengchao]] ([[User talk:Fengchao|talk]]) 13:13, 3 October 2012 (UTC)<br />
==Translation Status中oldid的问题==<br />
你好,Fengchao,谢谢你对我在[[Bash_(简体中文)]]和[[Emacs_(简体中文)]]中所设置错误的oldid的修改,我之前阅读过[[Template:TranslationStatus_(简体中文)]] 的说明,上面写道{{在点击英文页面顶端的历史标签,在版本列表中点击翻译的版本,一般是'''最后一个'''}},我理解的最后一个是历史页面的最原始的一个,而你的意思是最新的一个,所以建议改为最新的一个版本。^_^ --[[User:Jaurung|Jaurung]] ([[User talk:Jaurung|talk]]) 17:39, 17 October 2012 (UTC)</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Fengchao&diff=229192User talk:Fengchao2012-10-17T09:39:11Z<p>Jaurung: /* Translation Status中oldid的问题 */</p>
<hr />
<div>==关于Translation Status==<br />
请问如何添加Translation Status ? 格式是{{TranslationStatus (简体中文)|Xscreensaver|2012-10-04|226394}} ,这个最后一个是版本号吗?在哪儿找到的?<br />
: 看[[Template:TranslationStatus_(简体中文)]] 这个说明,参数是 oldid。我的浏览器在鼠标放到历史记录上之后,不点,也会显示oldid。 -- [[User:Fengchao|Fengchao]] ([[User talk:Fengchao|talk]]) 13:13, 3 October 2012 (UTC)<br />
==Translation Status中oldid的问题==<br />
你好,Fengchao,谢谢你对我在[[Bash_(简体中文)]]和[[Emacs_(简体中文)]]中所设置错误的oldid的修改,我之前阅读过[[Template:TranslationStatus_(简体中文)]] 的说明,上面写道'''在点击英文页面顶端的历史标签,在版本列表中点击翻译的版本,一般是最后一个''',我理解的最后一个是历史页面的最原始的一个,而你的意思是最新的一个,所以建议改为最新的一个版本。^_^ --[[User:Jaurung|Jaurung]] ([[User talk:Jaurung|talk]]) 17:39, 17 October 2012 (UTC)</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Fengchao&diff=229191User talk:Fengchao2012-10-17T09:38:39Z<p>Jaurung: /* Translation Status中oldid的问题 */</p>
<hr />
<div>==关于Translation Status==<br />
请问如何添加Translation Status ? 格式是{{TranslationStatus (简体中文)|Xscreensaver|2012-10-04|226394}} ,这个最后一个是版本号吗?在哪儿找到的?<br />
: 看[[Template:TranslationStatus_(简体中文)]] 这个说明,参数是 oldid。我的浏览器在鼠标放到历史记录上之后,不点,也会显示oldid。 -- [[User:Fengchao|Fengchao]] ([[User talk:Fengchao|talk]]) 13:13, 3 October 2012 (UTC)<br />
==Translation Status中oldid的问题==<br />
你好,Fengchao,谢谢你对我在[[Bash_(简体中文)]]和[[Emacs_(简体中文)]]中所设置错误的oldid的修改,我之前阅读过[[Template:TranslationStatus_(简体中文)]] 的说明,上面写道{{在点击英文页面顶端的历史标签,在版本列表中点击翻译的版本,一般是最后一个}},我理解的最后一个是历史页面的最原始的一个,而你的意思是最新的一个,所以建议改为最新的一个版本。^_^ --[[User:Jaurung|Jaurung]] ([[User talk:Jaurung|talk]]) 17:39, 17 October 2012 (UTC)</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Fengchao&diff=229190User talk:Fengchao2012-10-17T09:38:21Z<p>Jaurung: /* 关于Translation Status */</p>
<hr />
<div>==关于Translation Status==<br />
请问如何添加Translation Status ? 格式是{{TranslationStatus (简体中文)|Xscreensaver|2012-10-04|226394}} ,这个最后一个是版本号吗?在哪儿找到的?<br />
: 看[[Template:TranslationStatus_(简体中文)]] 这个说明,参数是 oldid。我的浏览器在鼠标放到历史记录上之后,不点,也会显示oldid。 -- [[User:Fengchao|Fengchao]] ([[User talk:Fengchao|talk]]) 13:13, 3 October 2012 (UTC)<br />
==Translation Status中oldid的问题==<br />
你好,Fengchao,谢谢你对我在[[Bash_(简体中文)]]和[[Emacs_(简体中文)]]中所设置错误的oldid的修改,我之前阅读过[[Template:TranslationStatus_(简体中文)]] 的说明,上面写道{{在点击英文页面顶端的历史标签,在版本列表中点击翻译的版本,一般是'''最后一个'''}},我理解的最后一个是历史页面的最原始的一个,而你的意思是最新的一个,所以建议改为最新的一个版本。^_^ --[[User:Jaurung|Jaurung]] ([[User talk:Jaurung|talk]]) 17:39, 17 October 2012 (UTC)</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229182Bash (简体中文)2012-10-17T09:09:24Z<p>Jaurung: </p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{TranslationStatus (简体中文)|Bash|2012-10-15|23776}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{注意|传统模式指以{{Ic|sh}}来调用}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常进入到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为需要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229179Emacs (简体中文)2012-10-17T09:05:44Z<p>Jaurung: add translation status</p>
<hr />
<div>[[Category:Text editors]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{TranslationStatus (简体中文)|Emacs|2012-10-17|23776}}<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]]是一个可拓展,可自定制,自带文档的实时显示编辑器。Emacs的核心构建在[[Wikipedia:Emacs Lisp|Emacs Lisp]]解释器之上,其中Emacs Lisp是大部分Emacs的内建函数和拓展模块的实现语言。尽管Emacs在命令行界面下(CLI)工作良好,但还是将GTK作为GNU Emacs22的默认X工具包。在文本编辑能力上,Emacs常常拿来和[[vim]]比较。<br />
<br />
== 安装 ==<br />
Emacs comes in several variants (sometimes referred to as ''emacsen''). The most common of these is [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, available in the [[Official Repositories]].<br />
<br />
Another common variant is {{Pkg|xemacs}}.<br />
<br />
== 快速入门 ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===运行Emacs===<br />
====常见方式====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====作为守护进程====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===基本术语和约定===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===移动===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===文件和缓冲区===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===编辑===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===移除,召回和区域===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===查找和替换===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===缩进和前缀参数===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===窗口和外框架===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===获得帮助===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===模式===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==提示和技巧==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===键盘宏和寄存器===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===正则表达式===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===定制===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== 拓展模块 ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== 问题的解决方法 ==<br />
<br />
===彩色输出的问题===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===菜单显示为空===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== X 窗口下的字符显示问题 ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== 启动速度慢 ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====错误的网络配置====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====初始化文件加载慢====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== 不能打开文件: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== 替代方案 ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== 资源 ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229178Emacs (简体中文)2012-10-17T09:01:10Z<p>Jaurung: </p>
<hr />
<div>[[Category:Text editors]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]]是一个可拓展,可自定制,自带文档的实时显示编辑器。Emacs的核心构建在[[Wikipedia:Emacs Lisp|Emacs Lisp]]解释器之上,其中Emacs Lisp是大部分Emacs的内建函数和拓展模块的实现语言。尽管Emacs在命令行界面下(CLI)工作良好,但还是将GTK作为GNU Emacs22的默认X工具包。在文本编辑能力上,Emacs常常拿来和[[vim]]比较。<br />
<br />
== 安装 ==<br />
Emacs comes in several variants (sometimes referred to as ''emacsen''). The most common of these is [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, available in the [[Official Repositories]].<br />
<br />
Another common variant is {{Pkg|xemacs}}.<br />
<br />
== 快速入门 ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===运行Emacs===<br />
====常见方式====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====作为守护进程====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===基本术语和约定===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===移动===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===文件和缓冲区===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===编辑===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===移除,召回和区域===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===查找和替换===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===缩进和前缀参数===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===窗口和外框架===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===获得帮助===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===模式===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==提示和技巧==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===键盘宏和寄存器===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===正则表达式===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===定制===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== 拓展模块 ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== 问题的解决方法 ==<br />
<br />
===彩色输出的问题===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===菜单显示为空===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== X 窗口下的字符显示问题 ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== 启动速度慢 ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====错误的网络配置====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====初始化文件加载慢====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== 不能打开文件: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== 替代方案 ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== 资源 ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229177Emacs (简体中文)2012-10-17T09:00:04Z<p>Jaurung: translate the headings</p>
<hr />
<div>[[Category:Text editors]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]]是一个可拓展,可自定制,自带文档的实时显示编辑器。Emacs的核心构建在[[Wikipedia:Emacs Lisp|Emacs Lisp]]解释器之上,其中Emacs Lisp是大部分Emacs的内建函数和拓展模块的实现语言。尽管Emacs在命令行界面下(CLI)工作良好,但还是将GTK作为GNU Emacs22的默认X工具包。在文本编辑能力上,Emacs常常拿来和[[vim]]比较。<br />
<br />
== 安装 ==<br />
Emacs comes in several variants (sometimes referred to as ''emacsen''). The most common of these is [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, available in the [[Official Repositories]].<br />
<br />
Another common variant is {{Pkg|xemacs}}.<br />
<br />
== 快速入门 ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===运行Emacs===<br />
====常见方式====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====作为守护进程====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===基本术语和约定===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===移动===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===文件和缓冲区===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===编辑===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===移除,召回,和区域===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===查找和替换===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===缩进和前缀参数===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===窗口和外框架===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===获得帮助===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===模式===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==提示和技巧==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===键盘宏和寄存器===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===正则表达式===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===定制===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== 拓展模块 ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== 问题的解决方法 ==<br />
<br />
===彩色输出的问题===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===菜单显示为空===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== X 窗口下的字符显示问题 ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== 启动速度慢 ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====错误的网络配置====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====初始化文件加载慢====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== 不能打开文件: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== 替代方案 ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== 资源 ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=ArchWiki:Translation_Team_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229173ArchWiki:Translation Team (简体中文)2012-10-17T08:41:55Z<p>Jaurung: /* 页面维护列表 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:ArchWiki (简体中文)]]<br />
[[en:ArchWiki Translation Team]]<br />
[[es:ArchWiki Translation Team]]<br />
[[hr:ArchWiki Translation Team]]<br />
[[it:ArchWiki Translation Team]]<br />
[[pl:ArchWiki Translation Team]]<br />
[[tr:ArchWiki_Çeviri_Ekibi]]<br />
Arch Wiki 上有许多中文页面,这些页面是无数中文志愿者劳动的结晶。随着时间推移,有些页面因为没有及时维护,内容严重过时。而目前的翻译工作缺少组织,效率偏低。所以参照西班牙和意大利翻译组的做法,添加这个页面。<br />
<br />
如果希望进行翻译和维护,只需要编辑下面的[[#页面维护列表]],将自己加为页面的维护者。如果列表中还没有要认领翻译的页面,请自行添加。如果因为时间原因无法再维护页面,请及时将自己从维护者列表中删除。<br />
<br />
== 创建翻译 ==<br />
{{注意|如果不准备翻译页面的大部分内容,请尽量不要新建简体中文页面。检查英文页面的更新需要花费不少精力,没有翻译的页面会增加维护负担。}}<br />
# 如果还不知道如何编辑 wiki,请阅读 [[Help:Editing (简体中文)|编辑帮助]]。<br />
# 阅读 [[Help:i18n (简体中文)|i18n帮助]],文章给出了 ArchWiki 国际化和本地化的指南。<br />
# [[Special:UserLogin |登录]] 以进行编辑。<br />
# 选择要翻译的页面,例如从 [[Special:Random|随机页面]] 或[[#页面维护列表 | 页面维护列表]] 中选择一个未翻译完成的页面。假设要翻译 [[Some Page]].<br />
# 进入选择的英文页面,点击页面顶部的 '''编辑'''。<br />
# 添加要翻译文件的语言间链接 (参见[[Help:i18n#Interlanguage links]])。<br />
# 复制所有页面代码。<br />
# 保存页面 (新加了语言链接)<br />
# 访问页面右边新添加的语言链接,应该会进到 [[Some Page (简体中文)]] : {{ic|<nowiki>https://wiki.archlinux.org/index.php/Some_Page_(</nowiki>''简体中文'')}}<br />
# 因为页面不存在,点击 '''创建'''。<br />
# 将显示一个编辑器 - 粘贴复制的英文页面。<br />
# 将文章分类修改为本地化版本,例如将 {{ic|<nowiki>[[Category:Internationalization]]</nowiki>}} 修改为 {{ic|<nowiki>[[Category:Internationalization (简体中文)]]</nowiki>}}<br />
# 修改语言间链接,指向英文页面(将 {{ic|zh-CN}} 修改为 {{ic|en}},并将英文页面移到文章顶部。<br />
# 翻译页面,进行保存。<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
# 更新所有其它语言页面,加入刚翻译文章的语言间链接。<br />
# (可选)创建一个简体中文名称的页面,指向新创建的页面:访问 {{ic|<nowiki>https://wiki.archlinux.org/index.php/</nowiki>''页面的中文名称''}}.<br />
# (可选)建立新页面,并加入:{{bc|<nowiki>#REDIRECT [[Some Page (简体中文)</nowiki>]]}}<br />
<br />
== 完善翻译 ==<br />
[https://wiki.archlinux.org/index.php?title=Special:WhatLinksHere/Template:Translateme_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&limit=100 这个页面] 包含了需要完善翻译的简体中文页面。完善翻译的基本步骤:<br />
# 选择自己比较熟悉的文章进行翻译<br />
# 先检查英文页面的对应段落,更新成最新的英文后再翻译,避免翻译过时的内容,减少信息遗漏。<br />
# 翻译完成后删除页面中的 <nowiki>{{translateme (简体中文)}}</nowiki> 标记<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
<br />
== 维护翻译 ==<br />
完成页面的翻译只是初步完成任务,即时同步英文页面改动、更新翻译是一个持续性的工作,可能会耗费更多的时间。<br />
<br />
=== 页面认领 ===<br />
所有人都可以认领页面。认领后的责任包括进行翻译,关注英文页面的改动,及时同步翻译。<br />
<br />
为了更好的跟踪英文页面的修改,请务必在设置中启用监视列表邮件通知,并监视对应的英文页面(从设置中找到监视列表,加入英文页面。或者直接到英文页面点击页面顶端的监视标签。这样只要有改动,就会收到邮件通知)。<br />
<br />
{{小贴士|如果收到邮件通知后没有访问页面或者访问了页面却没有登录用户,下次页面改动时就不会再发邮件通知。可以点击监视列表中的'''标记所有页面为已读'''再次获取更新。}}<br />
<br />
如果页面有维护者但长期得不到更新,将会在维护列表中删除维护者。<br />
<br />
=== 发现过期页面怎么办? === <br />
如果发现有 Wiki 页面过期或错误:<br />
* 小的改动,有时间可以立即进行修改同步,维护者并不控制页面的编辑权限,越多的人参与维护越好。如果改动较大,请先联系维护者,避免重复劳动。<br />
* 没有时间查看更改,请给页面加上 {{ic|<nowiki>{{out of date}}</nowiki>}} 模版,这样其他贡献者更容易发现需要更新的页面,而读者看到过期标记就可以直接查看英文页面,以免被错误内容误导,白白耽误时间。<br />
* 没有时间翻译,请将过期的中文部分删去,从英文页面中复制更改的部分到中文页面的相应部分,去掉{{ic|<nowiki>{{out of date}}</nowiki>}}模板(如果页面上有的话)并加上{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他贡献者就更容易发现需要翻译的页面,而读者也不会被过期的内容误导。<br />
如果发现有页面未翻译:<br />
* 有时间的话,请将页面中的英文部分翻译为中文,并去掉{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板。<br />
* 没有时间翻译,请为页面添加{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他的贡献者就能更容易发现需要翻译的页面。<br />
{{注意|在修改页面上的模板时,请同时更新页面维护列表的翻译状态。}}<br />
<br />
=== 翻译状态模板 ===<br />
Arch 作为滚动发行版,软件变化比较快,对应的文档变化也比较快。许多翻译的文章由于缺乏更新,会产生命令运行出错或不起作用等问题。而由于这些过期页面没有及时标记出来,所以用户无法及时获得更新。[[Template:TranslationStatus (简体中文)|翻译状态模板]]就是为了解决这个问题而创建。<br />
<br />
此模板可以起到如下作用:<br />
* 为用户提供翻译状况,包括翻译时间、英文页面的最后版本等<br />
* 用户可以点击查看翻译后,英文页面的改动,这样英文不是很好的用户可以只查看很小一部分英文内容,并判断出是否影响操作。<br />
* 翻译人员可以跟踪页面状况,通过[https://wiki.archlinux.org/index.php/Special:WhatLinksHere/Template:TranslationStatus_(简体中文) 模板的反向链接]可以查找到所有标记页面,查看需要更新翻译的部分。<br />
<br />
[[Template:TranslationStatus (简体中文)|模板页面]]有详细的使用方法。<br />
<br />
=== 页面维护列表 ===<br />
{{注意|请按照拉丁字母顺序添加页面。}}<br />
翻译状态说明:<br />
;过期:页面内容未与英文页面同步,对应{{ic|<nowiki>{{out of date}}</nowiki>}} 模版<br />
;未翻译:页面中含有英文内容,对应{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板<br />
;完成:页面已与英文页面同步<br />
{| class="wikitable sortable collapsible" border="1"<br />
|-<br />
! 页面<br />
! 翻译状态<br />
! 维护者<br />
! class="unsortable" width="30%" | 备注<br />
|-<br />
| [[acpid (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[ACPI hotkeys (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ACPI modules (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Activating Numlock on Bootup (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Ad-hoc networking (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Advanced Linux Sound Architecture (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AHCI (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Allow Users to Shutdown (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[aMule (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Android (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Apache, suEXEC and Virtual Hosts (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Based Distributions (Active) (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ArchWiki:About (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ATI (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AUR Helpers (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Avant Window Navigator (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[awesome (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无<br />
|-<br />
| [[Bash (简体中文)]]<br />
| 完成<br />
| Jaurung<br />
| 无<br />
|-<br />
| [[Bumblebee (简体中文)]]<br />
| 完成<br />
| Peter<br />
| 无<br />
|-<br />
| [[Common Applications (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Compiz (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Configuring Network (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Creating Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Disabling IPv6 (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Downgrading Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Emacs (简体中文)]]<br />
| 翻译中<br />
| Jaurung<br />
| 未完成<br />
|-<br />
|-<br />
| [[Font Configuration (简体中文)]]<br />
| 翻译中<br />
| Jaurung<br />
| 完善中<br />
|-<br />
| [[Fonts (简体中文)]]<br />
| 翻译中<br />
| zhangwen<br />
| 完善中<br />
|-<br />
| [[Fstab (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[GRUB (简体中文)]]<br />
| 翻译中<br />
| 无<br />
| 无<br />
|-<br />
| [[Help:Style (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[IBus (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Improve_Pacman_Performance_(简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation/Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Laptop Mode Tools (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[LibreOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Local Mirror (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Makepkg (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[mkinitcpio (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Network Time Protocol daemon (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Official Repositories (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Openbox (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[OpenOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman GUI Frontends (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[pacman Tips (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pidgin (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无 <br />
|- <br />
| [[Polipo (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无 <br />
|-<br />
| [[Python (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无 <br />
|-<br />
| [[Smart Common Input Method platform (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Common Applications/Science (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Secure Shell (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Systemd (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[TeXLive (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Vim (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[VMware (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Wine (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[Xscreensaver (简体中文)]]<br />
| 完成<br />
| liuyix<br />
| 无<br />
|-<br />
| [[Xmonad (简体中文)]]<br />
| 未翻译<br />
| Rns<br />
| 翻译中<br />
|}<br />
<br />
== 贡献列表 ==<br />
为翻译做出贡献的用户请加入列表,感谢所有人做出的贡献。<br />
* [[User:Fengchao|Fengchao]] &ndash; [[Special:Contributions/Fengchao|贡献]] &ndash; [[Special:EmailUser/Fengchao|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Skydiver|Skydiver]] &ndash; [[Special:Contributions/Skydiver|贡献]] &ndash; [[Special:EmailUser/Skydiver|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Alswl|Alswl]] &ndash; [[Special:Contributions/Alswl|贡献]] &ndash; [[Special:EmailUser/Alswl|Send Email]]<br />
* [[User:Reverland|Reverland]] &ndash; [[Special:Contributions/Reverland|贡献]] &ndash; [[Special:EmailUser/Reverland|Send Email]]<br />
* [[User:Cuihao|cuihao]] &ndash; [[Special:Contributions/Cuihao|贡献]] &ndash; [[Special:EmailUser/Cuihao|Send Email]]<br />
* [[User:Cael|Cael]] &ndash; [[Special:Contributions/Cael|贡献]] &ndash; [[Special:EmailUser/Cael|Send Email]]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229170Emacs (简体中文)2012-10-17T08:22:25Z<p>Jaurung: create page</p>
<hr />
<div>[[Category:Text editors]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]] is the extensible, customizable, self-documenting real-time display editor. At the core of Emacs lies an [[Wikipedia:Emacs Lisp|Emacs Lisp]] interpreter, the language in which the majority of Emacs' built-in functionality and extensions are implemented. GTK is the default X toolkit used as of GNU Emacs 22, though it functions equally well within a CLI environment. The text-editing capabilities of Emacs are often compared to that of [[vim]].<br />
<br />
== Installation ==<br />
Emacs comes in several variants (sometimes referred to as ''emacsen''). The most common of these is [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, available in the [[Official Repositories]].<br />
<br />
Another common variant is {{Pkg|xemacs}}.<br />
<br />
== Quick Start ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===Running Emacs===<br />
====Normal way====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====As a daemon====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===Basic terminology and convention===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===Movement===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===Files and buffers===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===Editing===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===Killing, yanking and regions===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===Search and replace===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===Indentation and prefix arguments===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===Windows and frames===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===Getting help===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===Modes===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==Tips and tricks==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===Keyboard macros and registers===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===Regular expressions===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===Customization===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== Extensions ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== Troubleshooting ==<br />
<br />
===Colored output issues===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===Menus appear empty===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== Problems displaying characters in X Windows ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== Slow startup ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====Incorrect network configuration====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====Init file loads slowly====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== Cannot open load file: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== Alternatives ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== See also ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Emacs&diff=229169Emacs2012-10-17T08:19:52Z<p>Jaurung: add</p>
<hr />
<div>[[Category:Text editors]]<br />
[[sr:Emacs]]<br />
[[zh-CN:Emacs]]<br />
{{Article summary start|Summary}}<br />
{{Article summary text|Tutorial on acquiring and using the Emacs text editor.}}<br />
{{Article summary end}}<br />
<br />
[[Wikipedia:Emacs|Emacs]] is the extensible, customizable, self-documenting real-time display editor. At the core of Emacs lies an [[Wikipedia:Emacs Lisp|Emacs Lisp]] interpreter, the language in which the majority of Emacs' built-in functionality and extensions are implemented. GTK is the default X toolkit used as of GNU Emacs 22, though it functions equally well within a CLI environment. The text-editing capabilities of Emacs are often compared to that of [[vim]].<br />
<br />
== Installation ==<br />
Emacs comes in several variants (sometimes referred to as ''emacsen''). The most common of these is [http://www.gnu.org/software/emacs/ GNU Emacs].<br />
<br />
[[pacman|Install]] {{Pkg|emacs}}, available in the [[Official Repositories]].<br />
<br />
Another common variant is {{Pkg|xemacs}}.<br />
<br />
== Quick Start ==<br />
Although Emacs is complex, it will not take long to begin to understand the benefits which the level of customization and extensibility bring. Furthermore, the comprehensive variety of extensions already available allows it to be transformed into a powerful environment for almost any form of text-editing.<br />
<br />
Emacs has an excellent built-in tutorial which can be accessed by clicking the first link on the splash screen; by selecting ''Help->Emacs Tutorial'' from the menu or by pressing 'F1' followed by 't'. This page is designed to be an additional resource for getting started with Emacs.<br />
<br />
Emacs also includes a set of reference cards, useful for beginners and experts alike, see {{ic|/usr/share/emacs/<version>/etc/refcards/}} (substitute <version> for your version of emacs).<br />
<br />
===Running Emacs===<br />
====Normal way====<br />
To start Emacs run:<br />
<br />
$ emacs<br />
<br />
or, to use it from the console:<br />
<br />
$ emacs -nw<br />
<br />
A file name can also be provided to open that file immediately:<br />
<br />
$ emacs filename.txt<br />
<br />
====As a daemon====<br />
Emacs can take some time to start since it has to load the .emacs file each time. Since version 23, Emacs is capable to run as a daemon to which users can connect. To run Emacs as a daemon:<br />
<br />
$ emacs --daemon<br />
<br />
You are likely to start the daemon at startup time and to connect a window to the daemon. Besides, it is possible to connect ''both'' graphical and console clients to the daemon at the same time and make the GUI to start quickly.<br />
<br />
If you want to connect to the daemon simply use the folowing command (note that it will start a graphical client if called in a graphical environment or a console client if called in a console like a tty):<br />
<br />
$ emacsclient<br />
<br />
If you still want a console client no matter you are in a graphical environment then use:<br />
<br />
$ emacsclient -t<br />
<br />
Furthermore, you can add the {{ic|-a ""}} parameter.<br />
Now, the first time you call the command, it will start emacs as a daemon, so that it remains running in background to improve startup time for future calls (and to remember buffers as well).<br />
<br />
In the end, you could use the following alias:<br />
<br />
$ alias emacs='emacsclient -t -a ""'<br />
<br />
With xfce, if you want to tell it to use emacsclient -c instead of emacs %f when opening a new file, you can change your /usr/share/applications/emacs.desktop and change the line<br />
<br />
$ Exec=emacs %f<br />
<br />
To<br />
<br />
$ Exec=emacsclient -c<br />
<br />
This way, a client will be called each time you open up a file and so be very fast!<br />
<br />
===Basic terminology and convention===<br />
Emacs uses some terminology and conventions which may seem unusual at first and will be introduced where appropriate. However, there is some terminology which should be introduced before-hand, as it is fundamental to working with Emacs.<br />
<br />
The one piece of terminology which must be introduced early is the concept of ''buffers''. A buffer is a representation of data within Emacs. For example, when a file is opened in Emacs, that file is read from disk and its contents stored in a buffer, which allows it to be edited and saved back to disk later. Buffers are not limited to text, and can also contain images and widgets. Work is in progress to allow buffers to even display applications! Another way to think of it: data available on disk is referred to as a 'file', whereas data available in Emacs is referred to as a 'buffer'.<br />
<br />
The convention for key sequences in Emacs may be unfamiliar. Namely:<br />
<br />
'''C-x''' refers to Control-x<br />
<br />
'''M-x''' refers to Meta-x<br />
<br />
{{Note|'Meta' corresponds to the Alt key in most cases. Alternatively, the Esc key can be used.}}<br />
<br />
For example, to exit Emacs use the following key sequence: '''C-x C-c'''. This can be read as "Hold Control and press 'x'. Release. Hold Control and press 'c'." Although Emacs provides a menu bar, it is recommended practise to focus on learning the key sequences. This guide will refer to keybindings with the convention used in Emacs from now on.<br />
<br />
===Movement===<br />
Cursor movement is very similar to other graphical editors. The mouse and arrow keys can be used to change the position of the cursor (referred to as ''point'' in Emacs). The standard movement commands performed by the arrow keys also have more accessible bindings in Emacs. To move forward one character, use '''C-f''' and to move one character backward, '''C-b'''. '''C-n''' and '''C-p''' can be used to move to the next and previous lines, respectively. Again, it is generally recommended to use these key-sequences in preference to the mouse and/or arrow keys.<br />
<br />
As might be expected, Emacs provides more advanced movement commands, including moving by word and sentence. '''M-f''' moves forward one word and '''M-b''' will move point one word backward. Similarly, '''M-e''' moves point one sentence forward and '''M-a''' one sentence backward.<br />
<br />
Until now, all of the movement commands introduced have been relative to point. '''M-<''' can be used to move point to the beginning of the buffer, with its counterpart, '''M->''', moving to the end of the buffer. To move point to a specific line number, use '''M-g g'''. '''M-g g''' will prompt for the desired line number. Also, to move to the start or end of the current line, use '''C-a''' or '''C-e''', respectively.<br />
<br />
{{Note|Keybindings for these commands, or indeed any command, may differ ''slightly'' depending on which modes are currently active. However, it is unusual for the replacement command not to provide equivalent functionality. See [[Emacs#Modes|Modes]] for more information.}}<br />
<br />
===Files and buffers===<br />
Emacs provides a series of commands to act upon files, the most common of which will be detailed here. '''C-x C-f''' is used to open a file (this command is called 'find-file' in Emacs). Should the file specified not exist, Emacs will open an empty buffer. Saving a buffer will create the file with the buffer's contents. '''C-x C-s''' can be used to save a buffer. To save a buffer with a different filename, use '''C-x C-w''' (this is a mnemonic for the command 'write-file'), which will prompt for the new filename before writing it to disk. It is also possible to ensure all buffers are saved with '''C-x s''', which, should a buffer be modified since its last save, a prompt will be displayed asking which action to take.<br />
<br />
{{Note|'''C-x C-f''' does not read the file from disk again if a buffer corresponding to the file is still opened. To re-read the file from disk, kill the buffer ('''C-x k''') prior to '''C-x C-f''' or use '''M-x revert-buffer'''.}}<br />
<br />
Many interactive commands such as "find-file" or "write-file" prompt for input in the bottom-most line of the Emacs window. This line is referred to as the ''minibuffer''. The minibuffer supports many basic editing commands as well as tab-completion similar to that which is available in many *nix shells. '''<TAB>''' can be pressed twice in succession to display a list of completions, and if desired, the mouse can be also be used to select a completion from that list. Completion in the minibuffer is available for many forms of input including commands and filenames.<br />
<br />
The minibuffer also provides a history feature. The previous items entered for a command can be recalled using the '''Up Arrow''' or '''C-p'''.<br />
<br />
To exit the minibuffer at any time, press '''C-g'''.<br />
<br />
After opening several files, a way to switch between them is needed. Opening a file corresponding to a buffer already available in Emacs, will cause Emacs to switch to that buffer. But this is not the most effective way. Emacs provides '''C-x b''', which prompts for the new buffer to be displayed (tab-completion is available here). By entering the name of a buffer which does not exist, a new buffer with that name will be created.<br />
<br />
{{Note|To switch to the previous buffer use '''C-x b <RET>''', as the previous buffer is the default.}}<br />
<br />
A list of all open buffers can be displayed using '''C-x C-b'''. Should a buffer no longer be required, it can be removed with '''C-x k'''.<br />
<br />
===Editing===<br />
Many editing commands exist within Emacs. Perhaps the most important command which has not yet been introduced is 'undo', which can be performed via '''C-_''' or '''C-/'''. Movement commands generally also have a corresponding delete command. For example, '''M-<backspace>''' can be used to delete a word backwards, and '''M-d''' to delete a word forwards. To delete to the end of the line, or the end of the sentence, use '''C-k''' or '''M-k''', respectively.<br />
<br />
It is a rule-of-thumb that no line be allowed to exceed 80 characters. This aids readability, especially in cases where the line wraps at the edge of a window. Automatically inserting (or removing) line separator(s) is known as ''filling'' in Emacs. A paragraph can be filled using '''M-q'''.<br />
<br />
Characters and words can be transposed using '''C-t''' and '''M-t''', respectively. For example: <code>Hello World!</code> → <code>World! Hello</code><br />
<br />
The case of words is also readily adjustable. '''M-l''' downcases a word from point (<code>HELLO</code> → <code>hello</code>); '''M-u''' upcases a word from point (<code>hello</code> → <code>HELLO</code>) and '''M-c''' capitalizes the first character of a word from point while downcasing the remainder (<code>hElLo</code> → <code>Hello</code>).<br />
<br />
===Killing, yanking and regions===<br />
A region is a section of text between two positions. One of those positions is referred to as ''mark'', and the other is point. '''C-<SPC>''' is used to set the position of mark, after which point can be moved to create a region. Within GNU Emacs 23.1 onwards, this region is visible by default. There are a number of commands which act upon regions, among the most commonly used are ''killing'' commands.<br />
<br />
In Emacs, cut and paste are referred to as ''kill'' and ''yank'', respectively. Many commands which delete more than one character (including many of those in the above section, such as '''C-k''' and '''M-d''') actually cut the text and append it to what is known as the ''kill-ring''. The kill-ring is simply a list of killed text. The kill-ring stores up to the last 60 kills by default. Successive kills are concatenated and stored at the head of the list.<br />
<br />
'''C-w''' and '''M-w''' can be used to kill and copy a region, respectively.<br />
<br />
To insert killed text into a buffer (known as 'yanking'), use '''C-y'''. '''C-y''' can be used multiple times in succession to yank text repeatedly. As mentioned, previous kills are stored in a list, however '''C-y''' only retrieves the first of them. The earlier kills can be accessed via '''M-y'''. This will remove the text inserted by 'yank' initially, replacing it with the text killed earlier. '''M-y''' must be used immediately following '''C-y''' and can be used in many times succession to cycle through the kill-ring.<br />
<br />
===Search and replace===<br />
Searching for a string is common practise in text-editing. This can be performed using '''C-s''' (to search forward) or '''C-r''' (to search backward). These commands prompt for the string for which to search. Searching is performed incrementally, and so it will match the next (or previous) occurrence as you type. To move to the next or previous match, press '''C-s''' or '''C-r''' again, respectively. Once a match has been found, '''<RET>''' can be used to end the search. Alternatively, should you wish to return to the location you initiated the search, use '''C-g'''.<br />
<br />
Once a search is completed (i.e., was not aborted with '''C-g''' or similar), the string which was searched for will be the default for any following search. To make use of this, press '''C-s C-s''' or '''C-r C-r''' to search forward or backward again, respectively.<br />
<br />
Regular Expression searches behave identically to the searching described above except for the command to initiate the search. Use '''C-M-s''' or '''C-M-r''' to initiate a regexp search forward or backward, respectively. Once a Regular Expression search has commenced, '''C-s''' and '''C-r''' can be used to search forward or backward, just as with string searches.<br />
<br />
In addition to searching, it is also possible to perform string and regular expression replacement (via '''M-%''' and '''C-M-%''', respectively). Prompts are provided for both the initial and replacement text, and then another prompt for the action to perform on the highlighted match. Although many options are available (the full list is available by pressing '''?'''), the most commonly used are '''y''', to perform replacement, '''n''', to skip this match, and '''!''' to replace this, and all following matches.<br />
<br />
===Indentation and prefix arguments===<br />
Indentation is usually performed with either '''<TAB>''', to indent a single line, or with '''C-M-\''', to indent a region.<br />
<br />
Exactly how text is indented usually depends on the ''major-mode'' which is active. Major-modes often define indentation styles specialising in indenting a certain type of text. (See [[Emacs#Modes|Modes]] for more information.)<br />
<br />
In some cases, a suitable major-mode may not exist for a file type, in which case, manual indentation may be necessary. Create a region (see [[Emacs#Killing, yanking and regions|Killing, yanking and regions]]) then perform indentation with '''C-u <n> C-x <TAB>''' (where '<n>' is the number of columns which the text within the region should be indented). For example:<br />
<br />
Increase the region's indentation by four columns:<br />
<br />
C-u 4 C-x <TAB><br />
<br />
Decrease the region's indentation by two columns.<br />
<br />
C-u -2 C-x <TAB><br />
<br />
{{Note|The trick behind this is '''C-u''', which corresponds to the 'universal-argument' command. Providing a 'universal-argument' is a way to provide more information to a command (this information is referred to as a 'prefix argument'). In this case, we provided the amount of indentation desired to the command invoked by '''C-x <TAB>'''. Without providing an argument, '''C-x <TAB>''' will only increase indentation by 1 column.}}<br />
<br />
===Windows and frames===<br />
Emacs is designed for convenient editing of many files at a time. This is achieved by dividing the Emacs interface into three levels. Namely, buffers, which have already been introduced, as well as ''windows'' and ''frames''.<br />
<br />
A ''window'' is a viewport used for displaying a buffer. A window can display only one buffer at a time, however one buffer can be displayed in many windows. Beneath each window exists a ''mode-line'', which displays information for that buffer.<br />
<br />
A ''frame'' is an Emacs "window" (in standard terminology. i.e., 'window' in the sense of the modern desktop paradigm) which contains a title bar, menu bar and one or more 'windows' (in Emacs terminology. i.e., the above definition of 'window').<br />
<br />
From now on the definition of these terms as they exist in Emacs will be used.<br />
<br />
To split the window vertically or horizontally, use '''C-x 2''' or '''C-x 3''', respectively. This has the effect of creating another window in the current frame. To cycle between multiple windows, use '''C-x o'''.<br />
<br />
The opposite of splitting a window, is deleting it. To delete the current window, use '''C-x 0''' and '''C-x 1''' to delete all windows except the current.<br />
<br />
As with windows, it is also possible to create and delete frames. '''C-x 5 2''' creates a frame. With '''C-x 5 0''' to delete the current frame and '''C-x 5 1''' to delete all except the current frame.<br />
<br />
{{Note|These commands do not affect buffers. For example, deleting a window does not kill the buffer it displays.}}<br />
<br />
===Getting help===<br />
Emacs is self-documenting by design. As such, a great deal of information is available to determine the name of a specific command or its keybinding, for example. The following is a listing of some of the most helpful of these:<br />
<br />
'''C-h t''' Start the Emacs tutorial<br />
<br />
'''C-h b''' List all active keybindings<br />
<br />
'''C-h k''' Find which command a key is bound to<br />
<br />
'''C-h w''' Find which key(s) a command is bound to<br />
<br />
'''C-h a''' Find a command matching a description<br />
<br />
'''C-h m''' Display information regarding the currently active modes<br />
<br />
'''C-h f''' Describe the given function<br />
<br />
===Modes===<br />
An Emacs mode is an extension written in Emacs Lisp that controls the behaviour of the buffer it is attached to. Usually it provides indentation, syntax highlighting and keybindings for editing that form of text. Sophisticated modes can turn Emacs into a full-fledged IDE (Integrated Development Environment). Emacs will generally use a file's extension to determine which mode should be loaded.<br />
<br />
Useful modes for editing shell scripts are sh-mode, line-number-mode and column-number-mode. They can be used in parallel and are invoked by:<br />
<br />
'''M-x sh-mode <RET>'''<br />
<br />
'''M-x column-number-mode <RET>'''<br />
<br />
line-number-mode is enabled by default, though, it can be toggled on/off by issuing the command again:<br />
<br />
'''M-x line-number-mode <RET>'''<br />
<br />
sh-mode is a ''major-mode''. Major-modes adjust Emacs, and often also provide a specialised set of commands, for editing a particular type of text. Only one major-mode can be active in each buffer. In addition to syntax highlighting, and indentation support, sh-mode defines several commands to help write shell scripts. The following shows a few of those commands:<br />
<br />
'''C-c (''' Insert a function definition<br />
<br />
'''C-c C-f''' Insert a 'for' loop<br />
<br />
'''C-c TAB''' Insert an 'if' statement<br />
<br />
'''C-c C-w''' Insert a 'while' loop<br />
<br />
'''C-c C-l''' Insert an indexed loop from 1 to n<br />
<br />
'line-number-mode' and 'column-number-mode', are ''minor-modes''. Minor-modes can be used to extend a major-mode and any number of minor-modes can be enabled at once.<br />
<br />
==Tips and tricks==<br />
While the previous sections has given an overview of the basic editing commands available, it has not given an indication of the possibilities of Emacs. This section will cover some more advanced techniques and functionality.<br />
<br />
===TRAMP===<br />
TRAMP (Transparent Remote Access, Multiple Protocols) is an extension which, as its name suggests, provides transparent access to remote files across a number of protocols. When prompted for a filename, entering a specific form will invoke TRAMP. Some examples:<br />
<br />
To prompt for the root password before opening /etc/hosts with root permissions:<br />
<br />
C-x C-f /su::/etc/hosts<br />
<br />
To connect to 'myhost' as 'myuser' via SSH and open the file ~/example.txt:<br />
<br />
C-x C-f /ssh:myuser@myhost:~/example.txt<br />
<br />
The path for TRAMP is typically of the form '/[protocol]:[[user@]host]:<file>'. TRAMP supports much more than the examples above might indicate. For more information refer to the TRAMP info manual, which is distributed with Emacs.<br />
<br />
===Keyboard macros and registers===<br />
This section will provide a practical demonstration of the use of a couple of more powerful editing features. Namely, ''keyboard macros'' and ''registers''.<br />
<br />
The aim will be to produce a listing of a series of characters and their corresponding position in this list. While it is possible to format each of them by hand, this would be slow and error-prone. Alternatively, some of Emacs' more powerful editing functionality could be leveraged. Before describing a solution, some details behind the techniques which will be used follow.<br />
<br />
The first feature which will be introduced is ''registers''. Registers are used to store and retrieve a variety of data types ranging from numbers to window configurations. Each register is given a name of a single character: this character is used to access the register.<br />
<br />
The other which will be demonstrated is ''keyboard macros''. A keyboard macro stores a sequence of commands so they can be easily repeated later. These changes will now be performed step-by-step.<br />
<br />
Starting with a buffer containing our set of characters:<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
Prepare a register by invoking the `number-to-register' command ('''C-x r n''') then storing the number '0' in register 'k':<br />
<br />
C-x r n k<br />
<br />
With point at the beginning of the buffer, start a keyboard macro ('''C-x (''') and begin to format the characters:<br />
<br />
C-x ( C-f M-4 .<br />
<br />
Insert ('''C-x r i''') and increment ('''C-x r +''') the register 'k'. The prefix argument ('''C-u''') is used to leave point positioned after the inserted text:<br />
<br />
C-u C-x r i k C-x r + k<br />
<br />
Complete the formatting by inserting a newline. Emacs can then repeat that process, beginning from the point where we started defining the keyboard macro, for the rest of the characters. '''C-x e''' completes then invokes the keyboard macro. The prefix argument, '''M-0''', causes the macro to repeat until it comes across an error. In this case it aborts once it reaches the end of the buffer.<br />
<br />
<RET> M-0 C-x e<br />
<br />
The result:<br />
<br />
A....0<br />
B....1<br />
C....2<br />
[...]<br />
x....49<br />
y....50<br />
z....51<br />
<br />
===Regular expressions===<br />
From the Emacs Manual: "A regular expression, or ''regexp'' for short, is a pattern that denotes a (possibly infinite) set of strings." This section will not go into any detail regarding regular expressions themselves (as there is simply too much to cover). It will however provide a quick demonstration of their power. See [http://www.gnu.org/software/emacs/manual/html_node/elisp/Regular-Expressions.html#Regular-Expressions Regular Expressions] section in the Emacs Manual for further reading.<br />
<br />
Given the same scenario presented above: A list of characters which are to be formatted to represent their respective position in the list. (see [[Emacs#Keyboard macros and registers|Keyboard macros and registers]]). Again, starting with a buffer containing.<br />
<br />
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz<br />
<br />
At the beginning of the buffer, use '''C-M-%''' (if the key-sequence is difficult to perform, it may be more comfortable to use '''M-x query-replace-regexp'''). At the prompt:<br />
\(.\)<br />
which simply matches one character. Then, when prompted for the replacement:<br />
\1....\#^J<br />
{{Note|'^J' represents where a newline should be placed, it should not be entered into the prompt. The newline must instead be inserted literally using '''C-q C-j'''.}}<br />
The replacement expression reads: "Insert the matched text between the first set of parentheses (in this case, a single character), followed by 4 periods then insert an automatically incremented number followed by a newline.<br />
<br />
Finally, press '''!''' to apply this across the entire buffer. All of the formatting that was performed in the previous section was performed with a single regexp replacement.<br />
<br />
===Customization===<br />
Emacs can configured by editing '~/.emacs' or using '''M-x customize'''. This section will focus on editing ~/.emacs by hand, and provide some example customizations to demonstrate commonly-configured aspects of Emacs. The customize command provides a simple interface to make adjustments, though it may become restricting as you grow more familiar with Emacs.<br />
<br />
All of the examples here can be performed while Emacs is running. To evaluate the expression within Emacs, use:<br />
<br />
'''C-M-x''' with point anywhere within the expression.<br />
<br />
or<br />
<br />
'''C-x C-e''' with point following the last ')'<br />
<br />
For some users, typing 'yes' and 'no' in prompts can quickly become tiring. To instead use the 'y' and 'n' keys at these prompts:<br />
<br />
(defalias 'yes-or-no-p 'y-or-n-p)<br />
<br />
To stop the cursor blinking, use:<br />
<br />
(blink-cursor-mode -1)<br />
<br />
Similarly, to enable column-number-mode, as discussed in the previous section:<br />
<br />
(column-number-mode 1)<br />
<br />
The similarities between the previous two commands are not a coincidence: blink-cursor-mode and column-number-mode are both minor-modes. As a rule, minor-modes can be enabled given positive argument or disabled with a negative argument. Should the argument be omitted, the minor-mode will be toggled on/off.<br />
<br />
Here are some more examples of minor-modes. The following will disable the scroll bars, menu-bar and tool-bar, respectively.<br />
<br />
(scroll-bar-mode -1)<br />
(menu-bar-mode -1)<br />
(tool-bar-mode -1)<br />
<br />
The variable, 'auto-mode-alist', can be modified to change the major-mode used by default for certain file names. The following example will make the default major-mode for '.tut' and '.req' files 'text-mode'.<br />
<br />
(setq auto-mode-alist<br />
(append<br />
'(("\\.tut$" . text-mode)<br />
("\\.req$" . text-mode))<br />
auto-mode-alist))<br />
<br />
Settings can also be applied on a per-mode basis. A common method for this is to add a function to a ''hook''. For example, to force indentation to use spaces instead of tabs, but only in text-mode:<br />
<br />
(add-hook 'text-mode-hook (lambda () (setq indent-tabs-mode nil)))<br />
<br />
Similarly, to only use spaces for indentation everywhere:<br />
<br />
(setq-default indent-tabs-mode nil)<br />
<br />
Keybindings can be adjusted in two ways. The first of which is 'define-key'. 'define-key' creates a keybinding for a command but only in one mode. The example below will make '''F8''' delete any whitespace from the end of each line of a 'text-mode' buffer:<br />
<br />
(define-key text-mode-map (kbd "<f8>") 'delete-trailing-whitespace)<br />
<br />
The other method is 'global-set-key'. This is used to bind a key to a command everywhere. To bind 'query-replace-regexp' ('''C-M-%''') to '<f7>'.<br />
<br />
(global-set-key (kbd "<f7>") 'query-replace-regexp)<br />
<br />
Binding a command to an alternate key does not replace any existing bindings. Which is to say, 'query-replace-regexp' would be bound to both '''F7''' and '''C-M-%''' after the above example.<br />
<br />
Almost anything within Emacs can be configured. Browsing through the [http://emacswiki.org/ Emacs Wiki] should give a solid place to start.<br />
<br />
=== Extensions ===<br />
<br />
While Emacs includes hundreds of modes, libraries and other extensions, there are many more available to further Emacs' capabilities. The majority of these come with instructions detailing any changes needed to be made to ~/.emacs. These instructions are generally found in the comment block at the beginning of an elisp source file, or in a README (or similar) should the extension consist of multiple source files.<br />
<br />
A number of popular extensions are available as packages in the 'community' repository, and more still are available via the [[AUR]]. The name of such packages have a 'emacs-' prefix (for example, emacs-lua-mode). In many cases, the changes which need to be made to ~/.emacs are shown during the installation of the package.<br />
<br />
Should instructions describing how to activate a specific extension not be available in the aforementioned location(s), check for a corresponding page in the [http://emacswiki.org/ Emacs Wiki], which will almost certainly provide an example configuration. The Emacs Wiki is also an excellent resource for discovering even more extensions.<br />
<br />
You can also use the [http://tromey.com/elpa/ Emacs Lisp Package Archive (ELPA)] to automatically install packages. See the website for instructions. ELPA is included with Emacs 24 (the newest version of Emacs); it is an accepted part of the Emacs ecosystem.<br />
<br />
== Troubleshooting ==<br />
<br />
===Colored output issues===<br />
By default, the Emacs shell will show raw escape sequences used to print colors. In other words, it will display strange symbols in place of the desired colored output.<br />
<br />
Including the following into {{ic|~/.emacs}} amends the problem:<br />
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)<br />
<br />
===Menus appear empty===<br />
A bug exists in GNU Emacs 23.1 (using the GTK toolkit) which may cause some menus to appear empty. This appears to be fixed in Emacs' CVS trunk. The corresponding [http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=550541 Debian bug report] contains a workaround.<br />
<br />
=== Problems displaying characters in X Windows ===<br />
If when you start emacs in X windows all the characters in the main window are white boxes with black borders (the ones you see if you try to view characters for which you do not have the correct font installed), you need to install {{pkg|xorg-fonts-75dpi}} and/or {{pkg|xorg-fonts-100dpi}} and restart X windows.<br />
<br />
=== Slow startup ===<br />
Slow startup times are often caused by one of two things.<br />
<br />
To determine which it might be, run Emacs with:<br />
<br />
$ emacs -q<br />
<br />
If Emacs still starts slowly, refer to [[Emacs#Incorrect network configuration|Incorrect network configuration]]. If not, it is almost certainly a [[Emacs#Init file loads slowly|problem in your .emacs]].<br />
<br />
====Incorrect network configuration====<br />
<br />
Mistakes, particularly in /etc/hosts, will often result in a 5+ second delay when starting Emacs. Refer to '[[Configuring_network#Set_the_hostname|set the hostname]]' in the network configuration guide for information.<br />
<br />
====Init file loads slowly====<br />
<br />
A simple way to search for the cause is to comment-out (i.e., prefix lines with ';') suspect sections of your ~/.emacs (or ~/.emacs.d/init.el) then start Emacs again to see if there's any change. Keep in mind use of "require" and "load" can slow the startup down, especially when used with larger extensions. They should, as a rule, only be used when their target is either: needed once Emacs starts or provides little more than "autoloads" for an extension. Otherwise, use the 'autoload function directly. For example, instead of:<br />
<br />
(require 'anything)<br />
<br />
you might use:<br />
<br />
(autoload 'anything "anything" "Select anything" t)<br />
<br />
=== Cannot open load file: ... ===<br />
<br />
The most common cause of this error is the 'load-path' variable not including the path to the directory within which the extension is located. To solve this, add the appropriate path to the list to be searched prior to attempting to load the extension:<br />
<br />
(add-to-list 'load-path "/path/to/directory/")<br />
<br />
When attempting to use packages for extensions and Emacs has been configured with a prefix other than '/usr', the load-path will need to be updated. Place the following in ~/.emacs prior to the instructions provided by the package:<br />
<br />
(add-to-list 'load-path "/usr/share/emacs/site-lisp")<br />
<br />
If compiling Emacs by hand, keep in mind that the default prefix is '/usr/local'.<br />
<br />
== Alternatives ==<br />
<br />
There are numerous implementations of Emacs. GNU/Emacs is probably the most popular. <br><br />
Lighter Emacs compatibile alternatives can be found in Arch repositories or in [https://aur.archlinux.org/ AUR].<br />
<br />
=== mg ===<br />
<br />
mg (originally called MicroGnuEmacs) is lightweight implementation of Emacs written in C.<br />
<br />
It's possible to install mg right away from {{ic|community}}<br />
# pacman -S mg<br />
or download source from official [http://homepage.boetes.org/software/mg/ page].<br />
<br />
=== zile ===<br />
<br />
According to the offical web [https://www.gnu.org/software/zile/ page] "GNU Zile is a lightweight Emacs clone. Zile is short for Zile Is Lossy Emacs. Zile has been written to be as similar as possible to Emacs; every Emacs user should feel at home.".<br />
<br />
zile can be found in {{ic|extra}}<br />
<br />
# pacman -S zile<br />
<br />
the latest taballs can be found in official GNU [http://ftp.sh.cvut.cz/MIRRORS/gnu/pub/gnu/zile/ mirrors].<br />
<br />
=== uemacs ===<br />
<br />
uemacs is "Micro-emacs version customized by Linus Torvalds".<br />
It can be found in [https://aur.archlinux.org/ AUR] as [https://aur.archlinux.org/packages.php?ID=31502 uemacs].<br />
<br />
== See also ==<br />
* [http://www.gnu.org/software/emacs/ GNU Emacs home page]<br />
* [http://www.gnu.org/software/emacs/manual/emacs.html GNU Emacs Manual]<br />
* [http://www.emacswiki.org/cgi-bin/wiki/ Emacs Wiki]<br />
* [http://wikemacs.org WikEmacs - a more readable, but less complete Emacs Wiki]<br />
* [http://www2.lib.uchicago.edu/keith/tcl-course/emacs-tutorial.html Useful introduction to Emacs and its shortcuts]<br />
* [http://www.dina.kvl.dk/~abraham/religion/ The Church of Emacs]<br />
* [http://repo.or.cz/w/emacs.git/blob/HEAD:/etc/refcards/refcard.pdf Official reference card]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=ArchWiki:Translation_Team_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229055ArchWiki:Translation Team (简体中文)2012-10-16T14:49:10Z<p>Jaurung: /* 页面维护列表 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:ArchWiki (简体中文)]]<br />
[[en:ArchWiki Translation Team]]<br />
[[es:ArchWiki Translation Team]]<br />
[[hr:ArchWiki Translation Team]]<br />
[[it:ArchWiki Translation Team]]<br />
[[pl:ArchWiki Translation Team]]<br />
[[tr:ArchWiki_Çeviri_Ekibi]]<br />
Arch Wiki 上有许多中文页面,这些页面是无数中文志愿者劳动的结晶。随着时间推移,有些页面因为没有及时维护,内容严重过时。而目前的翻译工作缺少组织,效率偏低。所以参照西班牙和意大利翻译组的做法,添加这个页面。<br />
<br />
如果希望进行翻译和维护,只需要编辑下面的[[#页面维护列表]],将自己加为页面的维护者。如果列表中还没有要认领翻译的页面,请自行添加。如果因为时间原因无法再维护页面,请及时将自己从维护者列表中删除。<br />
<br />
== 创建翻译 ==<br />
{{注意|如果不准备翻译页面的大部分内容,请尽量不要新建简体中文页面。检查英文页面的更新需要花费不少精力,没有翻译的页面会增加维护负担。}}<br />
# 如果还不知道如何编辑 wiki,请阅读 [[Help:Editing (简体中文)|编辑帮助]]。<br />
# 阅读 [[Help:i18n (简体中文)|i18n帮助]],文章给出了 ArchWiki 国际化和本地化的指南。<br />
# [[Special:UserLogin |登录]] 以进行编辑。<br />
# 选择要翻译的页面,例如从 [[Special:Random|随机页面]] 或[[#页面维护列表 | 页面维护列表]] 中选择一个未翻译完成的页面。假设要翻译 [[Some Page]].<br />
# 进入选择的英文页面,点击页面顶部的 '''编辑'''。<br />
# 添加要翻译文件的语言间链接 (参见[[Help:i18n#Interlanguage links]])。<br />
# 复制所有页面代码。<br />
# 保存页面 (新加了语言链接)<br />
# 访问页面右边新添加的语言链接,应该会进到 [[Some Page (简体中文)]] : {{ic|<nowiki>https://wiki.archlinux.org/index.php/Some_Page_(</nowiki>''简体中文'')}}<br />
# 因为页面不存在,点击 '''创建'''。<br />
# 将显示一个编辑器 - 粘贴复制的英文页面。<br />
# 将文章分类修改为本地化版本,例如将 {{ic|<nowiki>[[Category:Internationalization]]</nowiki>}} 修改为 {{ic|<nowiki>[[Category:Internationalization (简体中文)]]</nowiki>}}<br />
# 修改语言间链接,指向英文页面(将 {{ic|zh-CN}} 修改为 {{ic|en}},并将英文页面移到文章顶部。<br />
# 翻译页面,进行保存。<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
# 更新所有其它语言页面,加入刚翻译文章的语言间链接。<br />
# (可选)创建一个简体中文名称的页面,指向新创建的页面:访问 {{ic|<nowiki>https://wiki.archlinux.org/index.php/</nowiki>''页面的中文名称''}}.<br />
# (可选)建立新页面,并加入:{{bc|<nowiki>#REDIRECT [[Some Page (简体中文)</nowiki>]]}}<br />
<br />
== 完善翻译 ==<br />
[https://wiki.archlinux.org/index.php?title=Special:WhatLinksHere/Template:Translateme_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&limit=100 这个页面] 包含了需要完善翻译的简体中文页面。完善翻译的基本步骤:<br />
# 选择自己比较熟悉的文章进行翻译<br />
# 先检查英文页面的对应段落,更新成最新的英文后再翻译,避免翻译过时的内容,减少信息遗漏。<br />
# 翻译完成后删除页面中的 <nowiki>{{translateme (简体中文)}}</nowiki> 标记<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
<br />
== 维护翻译 ==<br />
完成页面的翻译只是初步完成任务,即时同步英文页面改动、更新翻译是一个持续性的工作,可能会耗费更多的时间。<br />
<br />
=== 页面认领 ===<br />
所有人都可以认领页面。认领后的责任包括进行翻译,关注英文页面的改动,及时同步翻译。<br />
<br />
为了更好的跟踪英文页面的修改,请务必在设置中启用监视列表邮件通知,并监视对应的英文页面(从设置中找到监视列表,加入英文页面。或者直接到英文页面点击页面顶端的监视标签。这样只要有改动,就会收到邮件通知)。<br />
<br />
{{小贴士|如果收到邮件通知后没有访问页面或者访问了页面却没有登录用户,下次页面改动时就不会再发邮件通知。可以点击监视列表中的'''标记所有页面为已读'''再次获取更新。}}<br />
<br />
如果页面有维护者但长期得不到更新,将会在维护列表中删除维护者。<br />
<br />
=== 发现过期页面怎么办? === <br />
如果发现有 Wiki 页面过期或错误:<br />
* 小的改动,有时间可以立即进行修改同步,维护者并不控制页面的编辑权限,越多的人参与维护越好。如果改动较大,请先联系维护者,避免重复劳动。<br />
* 没有时间查看更改,请给页面加上 {{ic|<nowiki>{{out of date}}</nowiki>}} 模版,这样其他贡献者更容易发现需要更新的页面,而读者看到过期标记就可以直接查看英文页面,以免被错误内容误导,白白耽误时间。<br />
* 没有时间翻译,请将过期的中文部分删去,从英文页面中复制更改的部分到中文页面的相应部分,去掉{{ic|<nowiki>{{out of date}}</nowiki>}}模板(如果页面上有的话)并加上{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他贡献者就更容易发现需要翻译的页面,而读者也不会被过期的内容误导。<br />
如果发现有页面未翻译:<br />
* 有时间的话,请将页面中的英文部分翻译为中文,并去掉{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板。<br />
* 没有时间翻译,请为页面添加{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他的贡献者就能更容易发现需要翻译的页面。<br />
{{注意|在修改页面上的模板时,请同时更新页面维护列表的翻译状态。}}<br />
<br />
=== 翻译状态模板 ===<br />
Arch 作为滚动发行版,软件变化比较快,对应的文档变化也比较快。许多翻译的文章由于缺乏更新,会产生命令运行出错或不起作用等问题。而由于这些过期页面没有及时标记出来,所以用户无法及时获得更新。[[Template:TranslationStatus (简体中文)|翻译状态模板]]就是为了解决这个问题而创建。<br />
<br />
此模板可以起到如下作用:<br />
* 为用户提供翻译状况,包括翻译时间、英文页面的最后版本等<br />
* 用户可以点击查看翻译后,英文页面的改动,这样英文不是很好的用户可以只查看很小一部分英文内容,并判断出是否影响操作。<br />
* 翻译人员可以跟踪页面状况,通过[https://wiki.archlinux.org/index.php/Special:WhatLinksHere/Template:TranslationStatus_(简体中文) 模板的反向链接]可以查找到所有标记页面,查看需要更新翻译的部分。<br />
<br />
[[Template:TranslationStatus (简体中文)|模板页面]]有详细的使用方法。<br />
<br />
=== 页面维护列表 ===<br />
{{注意|请按照拉丁字母顺序添加页面。}}<br />
翻译状态说明:<br />
;过期:页面内容未与英文页面同步,对应{{ic|<nowiki>{{out of date}}</nowiki>}} 模版<br />
;未翻译:页面中含有英文内容,对应{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板<br />
;完成:页面已与英文页面同步<br />
{| class="wikitable sortable collapsible" border="1"<br />
|-<br />
! 页面<br />
! 翻译状态<br />
! 维护者<br />
! class="unsortable" width="30%" | 备注<br />
|-<br />
| [[acpid (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[ACPI hotkeys (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ACPI modules (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Activating Numlock on Bootup (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Ad-hoc networking (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Advanced Linux Sound Architecture (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AHCI (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Allow Users to Shutdown (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[aMule (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Android (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Apache, suEXEC and Virtual Hosts (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Based Distributions (Active) (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ArchWiki:About (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ATI (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AUR Helpers (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Avant Window Navigator (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[awesome (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无<br />
|-<br />
| [[Bash (简体中文)]]<br />
| 完成<br />
| Jaurung<br />
| 无<br />
|-<br />
| [[Bumblebee (简体中文)]]<br />
| 完成<br />
| Peter<br />
| 无<br />
|-<br />
| [[Common Applications (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Compiz (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Configuring Network (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Creating Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Disabling IPv6 (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Downgrading Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Font Configuration (简体中文)]]<br />
| 翻译中<br />
| Jaurung<br />
| 完善中<br />
|-<br />
| [[Fonts (简体中文)]]<br />
| 翻译中<br />
| zhangwen<br />
| 完善中<br />
|-<br />
| [[Fstab (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[GRUB (简体中文)]]<br />
| 翻译中<br />
| 无<br />
| 无<br />
|-<br />
| [[Help:Style (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[IBus (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Improve_Pacman_Performance_(简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation/Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Laptop Mode Tools (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[LibreOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Local Mirror (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Makepkg (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[mkinitcpio (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Network Time Protocol daemon (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Official Repositories (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Openbox (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[OpenOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman GUI Frontends (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[pacman Tips (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pidgin (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无 <br />
|- <br />
| [[Polipo (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无 <br />
|-<br />
| [[Python (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无 <br />
|-<br />
| [[Smart Common Input Method platform (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Common Applications/Science (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Secure Shell (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Systemd (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[TeXLive (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Vim (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[VMware (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Wine (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[Xscreensaver (简体中文)]]<br />
| 完成<br />
| liuyix<br />
| 无<br />
|-<br />
| [[Xmonad (简体中文)]]<br />
| 未翻译<br />
| Rns<br />
| 翻译中<br />
|}<br />
<br />
== 贡献列表 ==<br />
为翻译做出贡献的用户请加入列表,感谢所有人做出的贡献。<br />
* [[User:Fengchao|Fengchao]] &ndash; [[Special:Contributions/Fengchao|贡献]] &ndash; [[Special:EmailUser/Fengchao|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Skydiver|Skydiver]] &ndash; [[Special:Contributions/Skydiver|贡献]] &ndash; [[Special:EmailUser/Skydiver|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Alswl|Alswl]] &ndash; [[Special:Contributions/Alswl|贡献]] &ndash; [[Special:EmailUser/Alswl|Send Email]]<br />
* [[User:Reverland|Reverland]] &ndash; [[Special:Contributions/Reverland|贡献]] &ndash; [[Special:EmailUser/Reverland|Send Email]]<br />
* [[User:Cuihao|cuihao]] &ndash; [[Special:Contributions/Cuihao|贡献]] &ndash; [[Special:EmailUser/Cuihao|Send Email]]<br />
* [[User:Cael|Cael]] &ndash; [[Special:Contributions/Cael|贡献]] &ndash; [[Special:EmailUser/Cael|Send Email]]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229054Font configuration (简体中文)2012-10-16T14:48:06Z<p>Jaurung: 翻译了heading</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[Category:简体中文]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#补丁包]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==字体路径==<br />
<br />
For fonts to be known to applications, they must be cataloged for easy and quick access.<br />
<br />
The font paths initially known to Fontconfig are: {{ic|/usr/share/fonts/}} and {{ic|~/.fonts/}} (of which Fontconfig will scan recursively). For ease of organization and installation, it is recommended to use these font paths when [[Fonts#Installation|adding fonts]].<br />
<br />
To see a list of known Fontconfig fonts:<br />
$ fc-list : file<br />
<br />
See {{ic|man fc-list}} for more out put format.<br />
<br />
Check for Xorg's known font paths by reviewing its log:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{Tip|You can also check the list of [[Xorg]]'s known font paths using the command {{ic|xset q}}.}}<br />
<br />
Keep in mind that Xorg does not search recursively through the {{ic|/usr/share/fonts/}} directory like Fontconfig does. To add a path, the full path must be used:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
If you want font paths to be set on a per-user basis, you can add and remove font paths from the default by adding the following line(s) to {{ic|~/.xinitrc}}:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
To see a list of known Xorg fonts use {{ic|xlsfonts}}, from the {{Pkg|xorg-xlsfonts}} package.<br />
<br />
==Fontconfig配置==<br />
<br />
Fontconfig is documented in the [http://fontconfig.org/fontconfig-user.html fonts.conf] man page.<br />
<br />
Configuration can be done per-user through {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, and globally with {{ic|/etc/fonts/local.conf}}. The settings in the per-user configuration have precedence over the global configuration. Both these files use the same syntax.<br />
{{Note|Configuration files and directories: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} and {{ic|~/.fontconfig/*.cache-*}} are deprecated since fontconfig 2.10.1 ([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) and will not be read by default in the future versions of package. Use instead {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} and {{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} respectively.}}<br />
<br />
Fontconfig gathers all its configurations in a central file ({{ic|/etc/fonts/fonts.conf}}). This file is replaced during fontconfig updates and shouldn't be edited. Fontconfig-aware applications source this file to know available fonts and how they get rendered. This file is a conglomeration of rules from the global configuration ({{ic|/etc/fonts/local.conf}}), the configured presets in {{ic|/etc/fonts/conf.d/}}, and the user configuration file ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|For some desktop environments (such as [[GNOME]] and [[KDE]]) using the ''Font Control Panel'' will automatically create or overwrite the user font configuration file. For these desktop environments, it is best to match your already defined font configurations to get the expected behavior.}}<br />
<br />
Fontconfig configuration files use [[Wikipedia:XML|XML]] format and need these headers:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
The configuration examples in this article omit these tags.<br />
<br />
===预设===<br />
<br />
There are presets installed in the directory {{ic|/etc/fonts/conf.avail}}. They can be enabled by creating [[Wikipedia:Symbolic link|symbolic link]]s to them, both per-user and globally, as described in {{ic|/etc/fonts/conf.d/README}}. These presets will override matching settings in their respective configuration files.<br />
<br />
For example, to enable sub-pixel RGB rendering globally:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
To do the same but instead for a per-user configuration:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===反锯齿===<br />
<br />
[[Wikipedia:Font rasterization|Font rasterization]] converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to [[Wikipedia:Aliasing|aliasing]]. [[Wikipedia:Anti-aliasing|anti-aliasing]] is enabled by default and increases the apparent resolution of font edges.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===微调===<br />
<br />
[[Wikipedia:Font hinting|Font hinting]] (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, such as the pixel grid in a display. Fonts will not line up correctly without hinting until displays have 300 [[Wikipedia:Dots per inch|DPI]] or greater. Two types of hinting are available.<br />
<br />
====字节码解释器(BCI)====<br />
Using normal hinting, TrueType hinting instructions in the font are interpreted by freetype's Byte-Code Interpreter. This works best for fonts with good hinting instructions.<br />
<br />
To enable normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====自动微调器====<br />
Auto-discovery for hinting. This looks worse than normal hinting for fonts with good instructions, but better for those with poor or no instructions. The autohinter and subpixel rendering are not designed to work together and should not be used in combination.<br />
<br />
To enable auto-hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====微调字体====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===亚像素渲染===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD滤光器====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====高级LCD滤光器说明====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===取消粗体字的自动微调功能===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
===只对较大的字体打开反锯齿功能===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===替换字体===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===禁用点阵字型===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===为不完善的字体构建粗体风格和意大利体风格===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===改变规则重定义机制===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===fontconfig配置的例子===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==补丁包==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
=== ClearType包 ===<br />
<br />
These packages attempt to emulate ClearType, a type of font rendering that is used in Windows systems and is designed to work on both LCD and CRT monitors.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]]. Package names: {{AUR|freetype2-cleartype}} {{AUR|libxft-cleartype}} {{AUR|cairo-cleartype}}<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [http://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===恢复到未打补丁的包===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==没有fontconfig支持的应用程序==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==字体问题解决方法==<br />
<br />
===字体扭曲===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===较旧的GTK和QT应用程序===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==资源==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229051Font configuration (简体中文)2012-10-16T14:32:46Z<p>Jaurung: </p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[Category:简体中文]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{Translateme (简体中文)}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#Patched packages]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==Font paths==<br />
<br />
For fonts to be known to applications, they must be cataloged for easy and quick access.<br />
<br />
The font paths initially known to Fontconfig are: {{ic|/usr/share/fonts/}} and {{ic|~/.fonts/}} (of which Fontconfig will scan recursively). For ease of organization and installation, it is recommended to use these font paths when [[Fonts#Installation|adding fonts]].<br />
<br />
To see a list of known Fontconfig fonts:<br />
$ fc-list : file<br />
<br />
See {{ic|man fc-list}} for more out put format.<br />
<br />
Check for Xorg's known font paths by reviewing its log:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{Tip|You can also check the list of [[Xorg]]'s known font paths using the command {{ic|xset q}}.}}<br />
<br />
Keep in mind that Xorg does not search recursively through the {{ic|/usr/share/fonts/}} directory like Fontconfig does. To add a path, the full path must be used:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
If you want font paths to be set on a per-user basis, you can add and remove font paths from the default by adding the following line(s) to {{ic|~/.xinitrc}}:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
To see a list of known Xorg fonts use {{ic|xlsfonts}}, from the {{Pkg|xorg-xlsfonts}} package.<br />
<br />
==Fontconfig configuration==<br />
<br />
Fontconfig is documented in the [http://fontconfig.org/fontconfig-user.html fonts.conf] man page.<br />
<br />
Configuration can be done per-user through {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, and globally with {{ic|/etc/fonts/local.conf}}. The settings in the per-user configuration have precedence over the global configuration. Both these files use the same syntax.<br />
{{Note|Configuration files and directories: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} and {{ic|~/.fontconfig/*.cache-*}} are deprecated since fontconfig 2.10.1 ([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) and will not be read by default in the future versions of package. Use instead {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} and {{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} respectively.}}<br />
<br />
Fontconfig gathers all its configurations in a central file ({{ic|/etc/fonts/fonts.conf}}). This file is replaced during fontconfig updates and shouldn't be edited. Fontconfig-aware applications source this file to know available fonts and how they get rendered. This file is a conglomeration of rules from the global configuration ({{ic|/etc/fonts/local.conf}}), the configured presets in {{ic|/etc/fonts/conf.d/}}, and the user configuration file ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|For some desktop environments (such as [[GNOME]] and [[KDE]]) using the ''Font Control Panel'' will automatically create or overwrite the user font configuration file. For these desktop environments, it is best to match your already defined font configurations to get the expected behavior.}}<br />
<br />
Fontconfig configuration files use [[Wikipedia:XML|XML]] format and need these headers:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
The configuration examples in this article omit these tags.<br />
<br />
===Presets===<br />
<br />
There are presets installed in the directory {{ic|/etc/fonts/conf.avail}}. They can be enabled by creating [[Wikipedia:Symbolic link|symbolic link]]s to them, both per-user and globally, as described in {{ic|/etc/fonts/conf.d/README}}. These presets will override matching settings in their respective configuration files.<br />
<br />
For example, to enable sub-pixel RGB rendering globally:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
To do the same but instead for a per-user configuration:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===Anti-aliasing===<br />
<br />
[[Wikipedia:Font rasterization|Font rasterization]] converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to [[Wikipedia:Aliasing|aliasing]]. [[Wikipedia:Anti-aliasing|anti-aliasing]] is enabled by default and increases the apparent resolution of font edges.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===Hinting===<br />
<br />
[[Wikipedia:Font hinting|Font hinting]] (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, such as the pixel grid in a display. Fonts will not line up correctly without hinting until displays have 300 [[Wikipedia:Dots per inch|DPI]] or greater. Two types of hinting are available.<br />
<br />
====Byte-Code Interpreter (BCI)====<br />
Using normal hinting, TrueType hinting instructions in the font are interpreted by freetype's Byte-Code Interpreter. This works best for fonts with good hinting instructions.<br />
<br />
To enable normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Autohinter====<br />
Auto-discovery for hinting. This looks worse than normal hinting for fonts with good instructions, but better for those with poor or no instructions. The autohinter and subpixel rendering are not designed to work together and should not be used in combination.<br />
<br />
To enable auto-hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Hint style====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===Subpixel rendering===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD filter====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Advanced LCD filter specification====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===Disable auto-hinter for bold fonts===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
=== Enable anti-aliasing only for bigger fonts ===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===Replace fonts===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===Disable bitmap fonts===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===Create bold and italic styles for incomplete fonts===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===Change rule overriding===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===Example fontconfig configurations===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==Patched packages==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
=== ClearType packages ===<br />
<br />
These packages attempt to emulate ClearType, a type of font rendering that is used in Windows systems and is designed to work on both LCD and CRT monitors.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]]. Package names: {{AUR|freetype2-cleartype}} {{AUR|libxft-cleartype}} {{AUR|cairo-cleartype}}<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [http://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===Reverting to unpatched packages===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==Applications without fontconfig support==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==Troubleshooting==<br />
<br />
===Distorted fonts===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===Older GTK and QT applications===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==See also==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229050Font configuration (简体中文)2012-10-16T14:32:13Z<p>Jaurung: </p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[Category:简体中文]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{TranslationStatus (简体中文)|Fonts Configuration|2012-10-16|227928}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#Patched packages]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==Font paths==<br />
<br />
For fonts to be known to applications, they must be cataloged for easy and quick access.<br />
<br />
The font paths initially known to Fontconfig are: {{ic|/usr/share/fonts/}} and {{ic|~/.fonts/}} (of which Fontconfig will scan recursively). For ease of organization and installation, it is recommended to use these font paths when [[Fonts#Installation|adding fonts]].<br />
<br />
To see a list of known Fontconfig fonts:<br />
$ fc-list : file<br />
<br />
See {{ic|man fc-list}} for more out put format.<br />
<br />
Check for Xorg's known font paths by reviewing its log:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{Tip|You can also check the list of [[Xorg]]'s known font paths using the command {{ic|xset q}}.}}<br />
<br />
Keep in mind that Xorg does not search recursively through the {{ic|/usr/share/fonts/}} directory like Fontconfig does. To add a path, the full path must be used:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
If you want font paths to be set on a per-user basis, you can add and remove font paths from the default by adding the following line(s) to {{ic|~/.xinitrc}}:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
To see a list of known Xorg fonts use {{ic|xlsfonts}}, from the {{Pkg|xorg-xlsfonts}} package.<br />
<br />
==Fontconfig configuration==<br />
<br />
Fontconfig is documented in the [http://fontconfig.org/fontconfig-user.html fonts.conf] man page.<br />
<br />
Configuration can be done per-user through {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, and globally with {{ic|/etc/fonts/local.conf}}. The settings in the per-user configuration have precedence over the global configuration. Both these files use the same syntax.<br />
{{Note|Configuration files and directories: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} and {{ic|~/.fontconfig/*.cache-*}} are deprecated since fontconfig 2.10.1 ([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) and will not be read by default in the future versions of package. Use instead {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} and {{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} respectively.}}<br />
<br />
Fontconfig gathers all its configurations in a central file ({{ic|/etc/fonts/fonts.conf}}). This file is replaced during fontconfig updates and shouldn't be edited. Fontconfig-aware applications source this file to know available fonts and how they get rendered. This file is a conglomeration of rules from the global configuration ({{ic|/etc/fonts/local.conf}}), the configured presets in {{ic|/etc/fonts/conf.d/}}, and the user configuration file ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|For some desktop environments (such as [[GNOME]] and [[KDE]]) using the ''Font Control Panel'' will automatically create or overwrite the user font configuration file. For these desktop environments, it is best to match your already defined font configurations to get the expected behavior.}}<br />
<br />
Fontconfig configuration files use [[Wikipedia:XML|XML]] format and need these headers:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
The configuration examples in this article omit these tags.<br />
<br />
===Presets===<br />
<br />
There are presets installed in the directory {{ic|/etc/fonts/conf.avail}}. They can be enabled by creating [[Wikipedia:Symbolic link|symbolic link]]s to them, both per-user and globally, as described in {{ic|/etc/fonts/conf.d/README}}. These presets will override matching settings in their respective configuration files.<br />
<br />
For example, to enable sub-pixel RGB rendering globally:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
To do the same but instead for a per-user configuration:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===Anti-aliasing===<br />
<br />
[[Wikipedia:Font rasterization|Font rasterization]] converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to [[Wikipedia:Aliasing|aliasing]]. [[Wikipedia:Anti-aliasing|anti-aliasing]] is enabled by default and increases the apparent resolution of font edges.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===Hinting===<br />
<br />
[[Wikipedia:Font hinting|Font hinting]] (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, such as the pixel grid in a display. Fonts will not line up correctly without hinting until displays have 300 [[Wikipedia:Dots per inch|DPI]] or greater. Two types of hinting are available.<br />
<br />
====Byte-Code Interpreter (BCI)====<br />
Using normal hinting, TrueType hinting instructions in the font are interpreted by freetype's Byte-Code Interpreter. This works best for fonts with good hinting instructions.<br />
<br />
To enable normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Autohinter====<br />
Auto-discovery for hinting. This looks worse than normal hinting for fonts with good instructions, but better for those with poor or no instructions. The autohinter and subpixel rendering are not designed to work together and should not be used in combination.<br />
<br />
To enable auto-hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Hint style====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===Subpixel rendering===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD filter====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Advanced LCD filter specification====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===Disable auto-hinter for bold fonts===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
=== Enable anti-aliasing only for bigger fonts ===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===Replace fonts===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===Disable bitmap fonts===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===Create bold and italic styles for incomplete fonts===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===Change rule overriding===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===Example fontconfig configurations===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==Patched packages==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
=== ClearType packages ===<br />
<br />
These packages attempt to emulate ClearType, a type of font rendering that is used in Windows systems and is designed to work on both LCD and CRT monitors.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]]. Package names: {{AUR|freetype2-cleartype}} {{AUR|libxft-cleartype}} {{AUR|cairo-cleartype}}<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [http://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===Reverting to unpatched packages===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==Applications without fontconfig support==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==Troubleshooting==<br />
<br />
===Distorted fonts===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===Older GTK and QT applications===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==See also==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229049Font configuration (简体中文)2012-10-16T14:30:34Z<p>Jaurung: 改变所有内容</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[Category:简体中文]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{out of date}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#Patched packages]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==Font paths==<br />
<br />
For fonts to be known to applications, they must be cataloged for easy and quick access.<br />
<br />
The font paths initially known to Fontconfig are: {{ic|/usr/share/fonts/}} and {{ic|~/.fonts/}} (of which Fontconfig will scan recursively). For ease of organization and installation, it is recommended to use these font paths when [[Fonts#Installation|adding fonts]].<br />
<br />
To see a list of known Fontconfig fonts:<br />
$ fc-list : file<br />
<br />
See {{ic|man fc-list}} for more out put format.<br />
<br />
Check for Xorg's known font paths by reviewing its log:<br />
$ grep /fonts /var/log/Xorg.0.log<br />
<br />
{{Tip|You can also check the list of [[Xorg]]'s known font paths using the command {{ic|xset q}}.}}<br />
<br />
Keep in mind that Xorg does not search recursively through the {{ic|/usr/share/fonts/}} directory like Fontconfig does. To add a path, the full path must be used:<br />
Section "Files"<br />
FontPath "/usr/share/fonts/local/"<br />
EndSection<br />
<br />
If you want font paths to be set on a per-user basis, you can add and remove font paths from the default by adding the following line(s) to {{ic|~/.xinitrc}}:<br />
xset +fp /usr/share/fonts/local/ # Prepend a custom font path to Xorg's list of known font paths<br />
xset -fp /usr/share/fonts/sucky_fonts/ # Remove the specified font path from Xorg's list of known font paths<br />
<br />
To see a list of known Xorg fonts use {{ic|xlsfonts}}, from the {{Pkg|xorg-xlsfonts}} package.<br />
<br />
==Fontconfig configuration==<br />
<br />
Fontconfig is documented in the [http://fontconfig.org/fontconfig-user.html fonts.conf] man page.<br />
<br />
Configuration can be done per-user through {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, and globally with {{ic|/etc/fonts/local.conf}}. The settings in the per-user configuration have precedence over the global configuration. Both these files use the same syntax.<br />
{{Note|Configuration files and directories: {{ic|~/.fonts.conf}}, {{ic|~/.fonts.conf.d}} and {{ic|~/.fontconfig/*.cache-*}} are deprecated since fontconfig 2.10.1 ([http://cgit.freedesktop.org/fontconfig/commit/?id&#61;8c255fb185d5651b57380b0a9443001e8051b29d upstream commit]) and will not be read by default in the future versions of package. Use instead {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}, {{ic|$XDG_CONFIG_HOME/fontconfig/conf.d}} and {{ic|$XDG_CACHE_HOME/fontconfig/*.cache-*}} respectively.}}<br />
<br />
Fontconfig gathers all its configurations in a central file ({{ic|/etc/fonts/fonts.conf}}). This file is replaced during fontconfig updates and shouldn't be edited. Fontconfig-aware applications source this file to know available fonts and how they get rendered. This file is a conglomeration of rules from the global configuration ({{ic|/etc/fonts/local.conf}}), the configured presets in {{ic|/etc/fonts/conf.d/}}, and the user configuration file ({{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}).<br />
<br />
{{Note|For some desktop environments (such as [[GNOME]] and [[KDE]]) using the ''Font Control Panel'' will automatically create or overwrite the user font configuration file. For these desktop environments, it is best to match your already defined font configurations to get the expected behavior.}}<br />
<br />
Fontconfig configuration files use [[Wikipedia:XML|XML]] format and need these headers:<br />
<br />
{{bc|<nowiki><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<!-- settings go here --><br />
<br />
</fontconfig><br />
</nowiki>}}<br />
<br />
The configuration examples in this article omit these tags.<br />
<br />
===Presets===<br />
<br />
There are presets installed in the directory {{ic|/etc/fonts/conf.avail}}. They can be enabled by creating [[Wikipedia:Symbolic link|symbolic link]]s to them, both per-user and globally, as described in {{ic|/etc/fonts/conf.d/README}}. These presets will override matching settings in their respective configuration files.<br />
<br />
For example, to enable sub-pixel RGB rendering globally:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/10-sub-pixel-rgb.conf<br />
<br />
To do the same but instead for a per-user configuration:<br />
<br />
$ mkdir $XDG_CONFIG_HOME/fontconfig/conf.d<br />
$ ln -s /etc/fonts/conf.avail/10-sub-pixel-rgb.conf $XDG_CONFIG_HOME/fontconfig/conf.d<br />
<br />
===Anti-aliasing===<br />
<br />
[[Wikipedia:Font rasterization|Font rasterization]] converts vector font data to bitmap data so that it can be displayed. The result can appear jagged due to [[Wikipedia:Aliasing|aliasing]]. [[Wikipedia:Anti-aliasing|anti-aliasing]] is enabled by default and increases the apparent resolution of font edges.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===Hinting===<br />
<br />
[[Wikipedia:Font hinting|Font hinting]] (also known as instructing) is the use of mathematical instructions to adjust the display of an outline font so that it lines up with a rasterized grid, such as the pixel grid in a display. Fonts will not line up correctly without hinting until displays have 300 [[Wikipedia:Dots per inch|DPI]] or greater. Two types of hinting are available.<br />
<br />
====Byte-Code Interpreter (BCI)====<br />
Using normal hinting, TrueType hinting instructions in the font are interpreted by freetype's Byte-Code Interpreter. This works best for fonts with good hinting instructions.<br />
<br />
To enable normal hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hinting" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Autohinter====<br />
Auto-discovery for hinting. This looks worse than normal hinting for fonts with good instructions, but better for those with poor or no instructions. The autohinter and subpixel rendering are not designed to work together and should not be used in combination.<br />
<br />
To enable auto-hinting:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="autohint" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Hint style====<br />
<br />
Hint style is the amount of influence the hinting mode has. Hinting can be set to: {{ic|hintfull}}, {{ic|hintmedium}}, {{ic|hintslight}} and {{ic|hintnone}}. With BCI hinting, hintfull should work best for most fonts. With the autohinter, hintslight is recommended.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="hintstyle" mode="assign"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
===Subpixel rendering===<br />
<br />
Subpixel rendering effectively triples the horizontal (or vertical) resolution for fonts by making use of subpixels. The autohinter and subpixel rendering are not designed to work together and should not be used in combination without the [[#Infinality]] patch set.<br />
<br />
Most monitors manufactured today use the Red, Green, Blue (RGB) specification. Fontconfig will need to know your monitor type to be able to display your fonts correctly.<br />
<br />
''RGB (most common), BGR, V-RGB (vertical), or V-BGR''<br />
<br />
To enable subpixel rendering:<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><br />
<const>rgb</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
If you notice unusual colors around font's borders, the wrong subpixel arrangement might be configured. The [http://www.lagom.nl/lcd-test/subpixel.php Lagom subpixel layout test] web page can help identify it.<br />
<br />
====LCD filter====<br />
<br />
When using subpixel rendering, you should enable the LCD filter, which is designed to reduce colour fringing. This is described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html LCD filtering] in the FreeType 2 API reference. Different options are described under [http://www.freetype.org/freetype2/docs/reference/ft2-lcd_filtering.html#FT_LcdFilter FT_LcdFilter], and are illustrated by this [http://www.spasche.net/files/lcdfiltering/ LCD filter test] page.<br />
<br />
The {{ic|lcddefault}} filter will work for most users. Other filters are available that can be used in special situations: {{ic|lcdlight}}; a lighter filter ideal for fonts that look too bold or fuzzy, {{ic|lcdlegacy}}, the original Cairo filter; and {{ic|lcdnone}} to disable it entirely.<br />
<br />
{{bc|<nowiki><br />
<match target="font"><br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
</match><br />
</nowiki>}}<br />
<br />
====Advanced LCD filter specification====<br />
<br />
If the available, built-in LCD filters are not satisfactory, it is possible to tweak the font rendering very specifically by building a custom freetype2 package and modifying the hardcoded filters. The [[Arch Build System]] can be used to build and install packages from source.<br />
<br />
First, refresh the freetype2 PKGBUILD as root:<br />
<br />
# abs extra/freetype2<br />
<br />
This example uses {{ic|/var/abs/build}} as the build directory, substitute it according to your personal ABS setup. Download and extract the freetype2 package as a regular user:<br />
<br />
$ cd /var/abs/build<br />
$ cp -r ../extra/freetype2 .<br />
$ cd freetype2<br />
$ makepkg -o<br />
<br />
Edit the file {{ic|src/freetype-VERSION/src/base/ftlcdfil.c}} and look up the definition of the constant {{ic|default_filter[5]}}:<br />
<br />
static const FT_Byte default_filter[5] =<br />
{ 0x10, 0x40, 0x70, 0x40, 0x10 };<br />
<br />
This constant defines a low-pass filter applied to the rendered glyph. Modify it as needed. Save the file, build and install the custom package:<br />
<br />
$ makepkg -e<br />
$ sudo pacman -Rd freetype2<br />
$ sudo pacman -U freetype2-VERSION-ARCH.pkg.tar.xz<br />
<br />
Reboot or restart X. The lcddefault filter should now render fonts differently.<br />
<br />
===Disable auto-hinter for bold fonts===<br />
<br />
The auto-hinter uses sophisticated methods for font rendering, but often makes bold fonts too wide. Fortunately, a solution can be turning off the autohinter for bold fonts while leaving it on for the rest:<br />
...<br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
...<br />
<br />
=== Enable anti-aliasing only for bigger fonts ===<br />
<br />
''See also [http://sharpfonts.co.cc/ sharpfonts.co.cc] for related information.''<br />
<br />
Some users prefer the sharper rendering that anti-aliasing does not offer:<br />
<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<edit name="antialias" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="size" qual="any" compare="more"><br />
<double>12</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test name="pixelsize" qual="any" compare="more"><br />
<double>16</double><br />
</test><br />
<edit name="antialias" mode="assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
<br />
===Replace fonts===<br />
<br />
The most reliable way to do this is to add an XML fragment similar to the one below. This will cause Bitstream Vera Sans to be used in place of Helvetica:<br />
...<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
...<br />
An alternate approach is to set the "preferred" font, but ''this only works if the original font is not on the system'', in which case the one specified will be substituted:<br />
...<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
...<br />
<br />
===Disable bitmap fonts===<br />
<br />
To disable bitmap fonts in fontconfig, use {{ic|70-no-bitmaps.conf}} (which is not placed by fontconfig by default):<br />
<br />
# cd /etc/fonts/conf.d<br />
# rm 70-yes-bitmaps.conf<br />
# ln -s ../conf.avail/70-no-bitmaps.conf<br />
<br />
You may not need to remove {{ic|70-yes-bitmaps.conf}} if it does not exist. You can choose which fonts to replace bitmaps fonts with (Helvetica, Courier and Times bitmap mapts to TTF fonts) by:<br />
<br />
# cd /etc/fonts/conf.d<br />
# ln -s ../conf.avail/29-replace-bitmap-fonts.conf<br />
<br />
To disable embedded bitmap fonts for a specific font:<br />
<br />
<match target="font"><br />
<test qual="any" name="family"><br />
<string>Monaco</string><br />
</test><br />
<edit name="embeddedbitmap"><bool>false</bool></edit><br />
</match><br />
<br />
===Create bold and italic styles for incomplete fonts===<br />
<br />
Freetype has the ability to automatically create ''italic'' and '''bold''' styles for fonts that do not have them, but only if explicitly required by the application. Given programs rarely send these requests, this section covers manually forcing generation of missing styles.<br />
<br />
Start by editing {{ic|/usr/share/fonts/fonts.cache-1}} as explained below. Store a copy of the modifications on another file, because a font update with {{ic|fc-cache}} will overwrite {{ic|/usr/share/fonts/fonts.cache-1}}.<br />
<br />
Assuming the Dupree font is installed:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Duplicate the line, change {{ic|<nowiki>style=Regular</nowiki>}} to {{ic|<nowiki>style=Bold</nowiki>}} or any other style. Also change {{ic|<nowiki>slant=0</nowiki>}} to {{ic|<nowiki>slant=100</nowiki>}} for italic, {{ic|<nowiki>weight=80</nowiki>}} to {{ic|<nowiki>weight=200</nowiki>}} for bold, or combine them for '''''bold italic''''':<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:''etc...''<br />
<br />
Now add necessary modifications to {{ic|$XDG_CONFIG_HOME/fontconfig/fonts.conf}}:<br />
{{bc|<nowiki><br />
...<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="weight" compare="more_eq"><int>140</int></test><br />
<edit name="embolden" mode="assign"><bool>true</bool></edit><br />
</match><br />
<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test name="slant" compare="more_eq"><int>80</int></test><br />
<edit name="matrix" mode="assign"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
...<br />
</nowiki>}}<br />
{{Tip| Use the value 'embolden' for existing bold fonts in order to make them even bolder.}}<br />
<br />
===Change rule overriding===<br />
<br />
Fontconfig processes files in {{ic|/etc/fonts/conf.d}} in reverse numerical order. This enables rules or files to override one another, but often confuses users about what file gets parsed last.<br />
<br />
To guarantee that personal settings take precedence over any other rules, change their ordering:<br />
# cd /etc/fonts/conf.d<br />
# mv 50-user.conf 00-user.conf<br />
<br />
This change seems however to be unnecessary for the most of the cases, because a user is given enough control by default to set up own font preferences, hinting and antialiasing properties, alias new fonts to generic font families, etc.<br />
<br />
===Example fontconfig configurations===<br />
<br />
Example fontconfig configurations can be found on this [[Font_Configuration/fontconfig_Examples|page]].<br />
<br />
A simple starting point:<br />
<br />
{{hc|/etc/fonts/local.conf|<nowiki><br />
<?xml version='1.0'?><br />
<!DOCTYPE fontconfig SYSTEM 'fonts.dtd'><br />
<fontconfig><br />
<match target="font"><br />
<br />
<edit mode="assign" name="rgba"><br />
<const>rgb</const><br />
</edit><br />
<br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
<br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
<br />
<edit mode="assign" name="lcdfilter"><br />
<const>lcddefault</const><br />
</edit><br />
<br />
</match><br />
</fontconfig><br />
</nowiki>}}<br />
<br />
==Patched packages==<br />
<br />
These patched packages are available in the [[Arch User Repository|AUR]]. A few considerations:<br />
<br />
* Configuration is usually necessary.<br />
* The new font rendering will not kick in until applications restart.<br />
* Applications which [[Wikipedia:Static library|statically link]] to a library will not be affected by patches applied to the system library.<br />
<br />
=== ClearType packages ===<br />
<br />
These packages attempt to emulate ClearType, a type of font rendering that is used in Windows systems and is designed to work on both LCD and CRT monitors.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]]. Package names: {{AUR|freetype2-cleartype}} {{AUR|libxft-cleartype}} {{AUR|cairo-cleartype}}<br />
<br />
===Infinality===<br />
{{Warning|1=Since the [http://www.archlinux.org/news/fontconfig-2101-update-manual-intervention-required/ Fontconfig 2.10.1 update], Infinality users will receive multiple warnings similar to:<br />
{{ic|Fontconfig warning: "/etc/fonts/infinality/conf.d/60-group-non-tt-fonts.conf", line 483: Having multiple values in <test> isn't supported and may not works as expected}}<br />
Rule adjustments are currently being worked on. See: [http://www.infinality.net/forum/viewtopic.php?f=2&t=254 this article] for more information.}}<br />
<br />
The infinality patchset aims to greatly improve freetype2 font rendering. It adds multiple new capabilities.<br />
<br />
*[http://www.infinality.net/blog/infinality-freetype-patches/ Home page].<br />
*[http://www.infinality.net/forum/ Forum].<br />
<br />
Infinality's settings are all configurable at runtime via environment variables in {{ic|/etc/profile.d/infinality-settings.sh}}, and include the following:<br />
<br />
*'''Emboldening Enhancement''': Disables Y emboldening, producing a much nicer result on fonts without bold versions. Works on native TT hinter and autohinter.<br />
*'''Auto-Autohint''': Automatically forces autohint on fonts that contain no TT instructions.<br />
*'''Autohint Enhancement''': Makes autohint snap horizontal stems to pixels. Gives a result that appears like a well-hinted truetype font, but is 100% patent-free (as far as I know).<br />
*'''Customized FIR Filter''': Select your own [http://www.infinality.net/forum/viewtopic.php?f=2&t=19 filter values] at run-time. Works on native TT hinter and autohinter.<br />
*'''Stem Alignment''': Aligns bitmap glyphs to optimized pixel boundaries. Works on native TT hinter and autohinter.<br />
*'''Pseudo Gamma Correction''': Lighten and darken glyphs at a given value, below a given size. Works on native TT hinter and autohinter.<br />
*'''Embolden Thin Fonts''': Embolden thin or light fonts so that they are more visible. Works on autohinter.<br />
*'''Force Slight Hinting''': Force slight hinting even when programs want full hinting. If you use the local.conf I provide (included in infinality-settings fedora package) you will notice nice improvements on @font-face fonts.<br />
*'''ChromeOS Style Sharpening''': ChromeOS uses a patch to sharpen the look of fonts. This is now included in the infinality patchset.<br />
<br />
A number of presets are included and can be used by setting the USE_STYLE variable in {{ic|/etc/profile.d/infinality-settings.sh}}.<br />
<br />
{{AUR|freetype2-infinality}} can be installed from the [[Arch User Repository|AUR]]. Additionally, if you are using {{pkg|lib32-freetype2}} from [multilib], replace it with {{AUR|lib32-freetype2-infinality}} from the AUR. The AUR also contains a Git version of freetype2 that builds the latest development snapshot of freetype2 with the Infinality patchset: {{AUR|freetype2-git-infinality}}, {{AUR|lib32-freetype2-git-infinality}}.<br />
<br />
It is recommended to also install {{AUR|fontconfig-infinality}} to enable selection of predefined font substitution styles and antialiasing settings, apart from the rendering settings of the engine itself. After doing so, you can select the font style (win7, winxp, osx, linux, ...) with:<br />
# infctl setstyle<br />
<br />
If you set e.g. win7 or osx you need the corresponding fonts installed.<br />
<br />
{{Note|Default infinality settings can cause some programs to display fonts at 72 DPI instead of 96. If you notice a problem open /etc/fonts/infinality/infinality.conf search for the section on DPI and change 72 to 96. This problem can specifically affect conky causing the fonts to appear smaller than they should. Thus not aligning properly with images. }}<br />
<br />
{{Note|''The README for {{AUR|fontconfig-infinality}} says that /etc/fonts/local.conf should either not exist, or have no infinality-related configurations in it. The local.conf is now obsolete and completely replaced by this configuration.''}}<br />
<br />
for more information see this article: http://www.infinality.net/forum/viewtopic.php?f=2&t=77<br />
<br />
===Ubuntu===<br />
<br />
Ubuntu adds extra configurations, and occasionally patches to the font rendering libraries.<br />
<br />
Install the patched packages from the [[Arch User Repository|AUR]], the package names are: {{AUR|freetype2-ubuntu}} {{AUR|fontconfig-ubuntu}} {{AUR|libxft-ubuntu}} {{AUR|cairo-ubuntu}}.<br />
<br />
The global configuration will need to be added. See [[#Example fontconfig configurations]] for a starting point.<br />
<br />
===Reverting to unpatched packages===<br />
<br />
To restore the unpatched packages, reinstall the originals:<br />
<br />
# pacman -S --asdeps freetype2 libxft cairo fontconfig<br />
<br />
==Applications without fontconfig support==<br />
<br />
Some applications like [[URxvt]] will ignore fontconfig settings. This is very apparent when using the infinality patches which are heavily reliant on proper configuration. You can work around this by using {{ic|~/.Xresources}}, but it is not nearly as flexible as fontconfig. Example (see [[#Fontconfig configuration]] for explanations of the options):<br />
<br />
{{hc|~/.Xresources|<nowiki><br />
Xft.autohint: 0<br />
Xft.lcdfilter: lcddefault<br />
Xft.hintstyle: hintfull<br />
Xft.hinting: 1<br />
Xft.antialias: 1<br />
Xft.rgba: rgb<br />
</nowiki>}}<br />
<br />
Make sure the settings are loaded properly when X starts with {{ic|xrdb -q}} (see [[Xresources]] for more information).<br />
<br />
==Troubleshooting==<br />
<br />
===Distorted fonts===<br />
{{Note|96 DPI is not a standard. You should use your monitor's actual DPI to get proper font rendering, especially when using subpixel rendering.}}<br />
<br />
If fonts are still unexpectedly large or small, poorly proportioned or simply rendering poorly, fontconfig may be using the incorrect DPI.<br />
<br />
Fontconfig should be able to detect DPI parameters as discovered by the Xorg server. You can check the automatically discovered DPI with {{ic|xdpyinfo}}:<br />
<br />
{{hc|<nowiki>$ xdpyinfo | grep dots</nowiki>| resolution: 102x102 dots per inch}}<br />
<br />
{{Note|To use the ''xdpyinfo'' command, you must install the package {{pkg|xorg-xdpyinfo}}.}}<br />
<br />
If the DPI is detected incorrectly (usually due to an incorrect monitor EDID), you can specify it manually in the Xorg configuration, see [[Xorg#Display Size and DPI]]. This is the recommended solution, but it may not work with buggy drivers.<br />
<br />
Fontconfig will default to the Xft.dpi variable if it is set. Xft.dpi is usually set by desktop environments (usually to Xorg's DPI setting) or manually in {{ic|~/.Xdefaults}} or {{ic|~/.Xresources}}. Use xrdb to query for the value:<br />
<br />
{{hc|<nowiki>$ xrdb -query | grep dpi</nowiki>|Xft.dpi: 102}}<br />
<br />
Those still having problems can fall back to manually setting the DPI used by fontconfig:<br />
<br />
...<br />
<!-- Setup for DPI=96 --><br />
<match target="pattern"><br />
<edit name="dpi" mode="assign"><double>102</double></edit><br />
</match><br />
...<br />
<br />
===Older GTK and QT applications===<br />
<br />
Modern GTK apps enable Xft by default but this was not the case before version 2.2. If it is not possible to update these applications, force Xft for old [[GNOME]] applications by adding to {{ic|~/.bashrc}}:<br />
<br />
export GDK_USE_XFT=1<br />
<br />
For older QT applications:<br />
<br />
export QT_XFT=true<br />
<br />
==See also==<br />
*[http://www.x.org/X11R6.8.2/doc/fonts.html Fonts in X11R6.8.2] - Official Xorg font information<br />
*[http://freetype.sourceforge.net/freetype2/ FreeType 2 Overview]<br />
*[https://forums.gentoo.org/viewtopic-t-723341.html Gentoo font-rendering thread]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Font_configuration_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229048Font configuration (简体中文)2012-10-16T14:28:23Z<p>Jaurung: introduction的翻译</p>
<hr />
<div>[[Category:X Server (简体中文)]]<br />
[[Category:Fonts (简体中文)]]<br />
[[Category:简体中文]]<br />
[[en:Font Configuration]]<br />
[[it:Font Configuration]]<br />
[[ru:Font Configuration]]<br />
[[sr:Font Configuration]]<br />
[[tr:Yazıtipi_yapılandırması]]<br />
{{out of date}}<br />
{{Article summary start|摘要}}<br />
{{Article summary text|An overview of font configuration options and various techniques for improving the readability of fonts}}<br />
{{Article summary heading|相关页面}}<br />
{{Article summary wiki|Fonts}}: Information on adding fonts and font recommendations<br />
{{Article summary wiki|Java Runtime Environment Fonts}}: Fonts specific to Sun's Java machine<br />
{{Article summary wiki|MS Fonts}}: Adding Microsoft fonts and mimicking Windows' font settings<br />
{{Article summary wiki|Font Configuration/fontconfig Examples}}<br />
{{Article summary end}}<br />
<br />
Fontconfig是一个库,它被设计用来为应用程序提供可用[[Fonts (简体中文)|字体]],或者用来配置字体渲染效果,参见包{{Pkg|fontconfig}}和[[Wikipedia:Fontconfig]]。 Free type库({{Pkg|freetype2}}包)就是以此为配置基础来渲染字体。<br />
<br />
尽管Fontconfig已经是当今Linux的标准库,但是仍有一部分应用程序构建在更加原始的字体分类法上:Xorg server配置。<br />
<br />
Arch Linux包含的字体渲染包支持有字节码解释器(BCI)的''freetype2''。为了更好的字体渲染,特别是在LCD显示器上,一些补丁包也添加到库中,参见下面的[[#Patched packages]]。[[#Infinality]]包同时支持自动微调和亚像素渲染,允许在无须重新编译的情况下微调LCD滤光器,而且在粗体字下自动微调仍然表现良好。<br />
<br />
==X的字体配置和美化==<br />
:参见 [http://www.x.org/X11R6.8.2/doc/fonts.html Xorg Font Documentation] 查看所有细节。<br />
:参见 the [http://freetype.sourceforge.net/freetype2/ FreeType2 Project Page] 查看关于 freetype X.org 模块的的细节。<br />
:参见 [http://avi.alkalay.net/linux/docs/font-howto/Font.html Optimal Use of Fonts on Linux] 查看更多关于 Linux 字体的信息。<br />
<br />
===xorg.conf模块===<br />
*freetype - 为True Type (ttf, ttc), Type1 (pfa, pfb), CID (cid), CFF, Open Type, 点阵bitmap (bdf, pcf, snf), Windows (fnt), PFR, 和 Type42 字体提供支持<br />
*type1 - 为Type1 (pfa, pfb) 和CID (cid) 字体提供支持<br />
*speedo - 支持Bitstream Speedo (spd) 字体<br />
*xtt - 为True Type (ttf, ttc) 字体提供支持 ('''与freetype有冲突''')<br />
*bitmap - 提供bitmap (bdf, pcf, snf) 的支持<br />
<br />
如你所看到的,freetype提供了所有的支持.补充说明一点,xtt于freetype有冲突.<br />
<br />
==X.org字体路径和/etc/fonts/配置目录==<br />
===xorg.conf字体路径===<br />
xorg.conf里面的字体路径是给非xft字体用的. 为大多数字体在这里指定路径是值得的. 那些不支持xft的程序会寻找X的字体路径.我个人来说,我在这里填写最少的字体路径-仅仅为了xterm和那一类程序使用.<br />
<br />
===/etc/fonts/配置目录===<br />
/etc/fonts下的配置文件 (fonts.conf and local.conf)是用来配置字体的(Xft fonts). fonts.conf 不应该被更改, 如果要更改应该改local.conf(系统全局) 或者 ~/.fonts.conf (用户自定义).<br />
在/etc/fonts/conf.d目录下的文件都是以一个数字开头,还有.conf结尾的一个软链接(指向/etc/fonts/conf.avail/).<br />
<br />
在fonts.conf列出的目录会为字体配置而被fc-cache扫描 (/usr/share/fonts 和 ~/.fonts). 所有的字体都应该放在这些文件夹内. 如果安装一个新字体,运行'''fc-cache -fv'''会让改变生效.<br />
<br />
===添加新字体===<br />
当新字体被添加后,它们不过是系统里面的一些文件. 必须使用一些工具来告诉系统新字体已经被安装了.<br />
/usr/bin/fc-cache<br />
这样将会更新系统字体缓存, 当然是假设新字体能够被配置文件找到 (看上一节关于/etc/fonts部分)<br />
/usr/bin/mkfontscale<br />
/usr/bin/mkfontdir<br />
ln -s /usr/X11R6/lib/X11/fonts/encodings/encodings.dir encodings.dir<br />
<br />
这几个工具需要在含有新字体的目录内运行. mkfontscale创建一个fonts.scale文件, mkfontdir 则创建一个fonts.dir文件. 这两个文件被X服务所使用, 也仅仅需要当字体通过X.org的字体路径使用的时候运行.而encodings的软链接允许X服务使用这些新字体(支持相关编码情况下).所有这些完成后, 你会发现这个字体目录下有3个新文件 : fonts.scale, fonts.dir, and encodings.dir.<br />
<br />
===fc-list和xlsfont工具===<br />
这两个工具将在命令行下用不同方式列出所有可用字体. fc-list将列出所有配置过的字体,而xlsfont则会列出所有的X字体. 如果同时使用grep效果会非常好,例如: "xlsfonts || grep -i bitstream" 可以看到所有可用的bitstream字体.<br />
<br />
==一些字体的下载==<br />
*[http://www.users.bigpond.net.au/gavindi/ Arkpandora TrueType fonts] - Replacements for Arial and Times New Roman.<br />
*[http://themes.freshmeat.net/projects/ppantsfonts/ PPants Angular Font Collection]-Small collection of Angular-styled fonts with a general width of six pixels. <br />
*[http://www.tobias-jung.de/seekingprofont/ Profont]-Programming font.<br />
<br />
==Goodies==<br />
===LCD的ClearType补丁===<br />
[http://bbs.archlinux.org/viewtopic.php?id=33955 http://bbs.archlinux.org/viewtopic.php?id=33955]<br />
<br />
===我的字体很难看.我都配置好了,但是好像是我缺少好看字体.===<br />
建议你从pacman安装如下包来解决:<br />
pacman -S ttf-ms-fonts ttf-cheapskate artwiz-fonts<br />
<br />
另外一个方法是删除75/100dpi包然后安装Bitstream Vera.后者提供漂亮的等宽终端字体,也能是浏览网页字体更好看(至少是firefox里面这样):<br />
pacman -Rns xorg-fonts-75dpi xorg-fonts-100dpi<br />
pacman -S ttf-bitstream-vera<br />
<br />
补充:中文用户,安装如下任意一个中文字体,带有很全的GBK字符集,需要打开community仓库<br />
pacman -S wqy-bitmapfont 文泉驿点阵字体<br />
pacman -S wqy-zenhei 文泉驿正黑字体<br />
<br />
===我有一些针对Gtk 2.2和以下版本编译的程序,字体仍然看起来很垃圾.===<br />
的确这个会发生.现在的Gtk程序默认开启了xft支持, 但是2.2字体以前就没有这样了. 也许这些程序应该升级到一个针对新Gtk的新版本了. 如果那不可能,那么就添加 '''export GDK_USE_XFT=1''' 到全局设置文件 (/etc/profile, /etc/profile.d/gnome.sh, ~/.xinitrc, 等,任选一个) 将会为老程序启用xft的支持.<br />
<br />
===我有的老的Qt基础的程序有同样的问题.===<br />
同上, 添加 '''export QT_XFT=true'''.<br />
<br />
===在用KDE桌面的时候,Gtk程序字体太小.===<br />
安装gtk-qt-engine:<br />
pacman -S gtk-qt-engine<br />
*更改Gtk程序字体大小:`Control Center' -> `Appearance & Themes' -> `GTK Styles and Fonts'.<br />
<br />
===bytecode interpreter让我字体看起来很丑,但是我已经把它编译进去了,我需要重新编译么?===<br />
完全不需要. 只是Freetype内部的自动微调(auto-hinting)关闭了. 在某些distros(也许可以翻译成源)里面, bytecode interpreter 被编译进去而且默认开启了. 这样造成bytecode interpreter 替代了freetype的自动微调(autohinter) (这还是开发者比较得意的地方). 指定自动微调开启, 添加下面的段到/etc/fonts/local.conf 或者 ~/.fonts.conf<br />
<!-- Use the Autohinter --><br />
<match target="pattern"><br />
<edit name=<code>"autohint" mode=</code>"assign"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
或者改变 /etc/fonts/conf.d目录, 即从conf.avail做一个10-autohint.conf的软链接到这里. 如下(第二个命令需要有超级用户权限).<br />
cd /etc/fonts/conf.d<br />
ln -s ../conf.avail/10-autohint.conf<br />
<br />
问题: 我不明白,bytecode interpreter 会和自动微调(autohinter)冲突都有段时间了,所以我不知道为什么有人想要自动微调. <br />
回答: 因为 bytecode interpreter 在2.3分支(branch)里面支持相当不好 . 这里有一个论坛帖子是关于这个的: http://bbs.archlinux.org/viewtopic.php?id=29976 那上面的代码让我的字体好看很多. 尽管我重启效果就会失效,我也不知道为什么.<br />
<br />
===自动微调(Autohint)运行的很好,但是我的字体的粗体就不行了,我怎样能针对粗体关闭它?===<br />
自动微调可以让字体很好看,但是有时也让字体变太宽. 特别是字体为粗体模式时尤其严重. 幸好你可以为粗体关闭微调,而为其他字体模式保留.<br />
*First turn on autohinter (see above) and add the following to ~/[[.fonts.conf]]<br />
<match target="font"><br />
<test name=<code>"weight" compare=</code>"more"><br />
<const>medium</const><br />
</test><br />
<edit name=<code>"autohint" mode=</code>"assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<br />
===我有一个使用DVI数据线的TFT/DFP/LCD显示器,字体看起来模糊不清晰===<br />
这是CRT和非CTR渲染的不同造成的. 为了解决这个问题,你应该开启次像素(sub-pixel)渲染. 编辑~/[[[.fonts.conf]]] 文件. 添加下面一小段开启用. 说明:这样并没有显示质量的提高,只是做了CRT显示器完成的一部分额外工作(NOTE that this will do nothing but a minor amount of extra work on CRTs and does not improve the display quality). 这里 '''const'''可能的值是- rgb, bgr, vrgb, bgrv, 等.<br />
<br />
< !-- Enable sub-pixel rendering --><br />
<match target="font" ><br />
<edit mode="assign" name="rgba" ><br />
<const>rgb</const><br />
</edit><br />
</match><br />
<br />
===我不希望我的字体在某些字号下反锯齿(或者叫边缘模糊 AA Antialiase).===<br />
一份例子是/etc/fonts/local.conf文件. 推荐这样做, 当然就像次像素渲染那一节一样写. 如果有任何改变,就应该改变 '''compare="less_eq"''' , 和'''<int>12</int>'''区域 - 这分别是渲染强弱和点大小.<br />
<!-- Disable anti-aliasing for fonts that are size <=12 --><br />
<match target="pattern"><br />
<test qual="any" name="size" compare="less_eq"><br />
<int>12</int><br />
</test><br />
<edit name="antialias" mode="assign"><bool>false</bool></edit><br />
</match><br />
<br />
===我使用MS的TrueType字体(verdana),想针对看起来有锯齿的大号字体开启反锯齿.===<br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<fontconfig><br />
<br />
<match target="font" ><br />
<test compare<code>"more" name</code>"size" qual="any" ><br />
<double>12</double><br />
</test><br />
<edit mode<code>"assign" name</code>"antialias" ><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<match target="font" ><br />
<test compare<code>"more" name</code>"pixelsize" qual="any" ><br />
<double>17</double><br />
</test><br />
<edit mode<code>"assign" name</code>"antialias" ><br />
<bool>true</bool><br />
</edit><br />
</match><br />
</fontconfig><br />
<br />
===我想安装更多字体.===<br />
保存你的字体到一个目录然后到'''~/[[[.fonts.conf]]]'''添加路径<br />
<br />
< !-- Additional font directories --><br />
<dir>/path/to/dir</dir><br />
<br />
===我希望我的字体大小符合我的DPI设置.===<br />
照下面编辑'''~/[[[.fonts.conf]]]'''. 这个设置应该适合你[[xorg.conf]]里面的Dpi,或者startx命令. 使用xdpyinfo来查看你目前的DPI设置. 大多数人适合或者正在使用96或者100的值.应该依照这个文档[[Xorg#Display_Size.2FDPI|Xorg DisplaySize/DPI]]来改变X的DPI值<br />
<!-- Setup for DPI = 100 --><br />
<match target="pattern"><br />
<edit name=<code>"dpi" mode=</code>"assign"><double>100</double></edit><br />
</match><br />
<br />
===我不喜欢 <某个字体>希望用<另一个字体>替代它===<br />
<br />
最可靠的办法是同上面一样添加一段XML段落到 ~/[[.fonts.conf]]. 这会让Bitstream Vera Sans取代Helvetica:<br />
<br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit mode="assign" name="family" ><br />
<string>Bitstream Vera Sans</string><br />
</edit><br />
</match><br />
<br />
<br />
<br />
一个另类的办法是设置"更喜欢"字体,'''但这仅仅在原始字体不存在的时候生效''',这样你设置的字体才能生效:<br />
<br />
<br />
< !-- Replace Helvetica with Bitstream Vera Sans Mono --><br />
< !-- Note, an alias for Helvetica should already exist in default conf files --><br />
<alias><br />
<family>Helvetica</family><br />
<prefer><family>Bitstream Vera Sans Mono</family></prefer><br />
<default><family>fixed</family></default><br />
</alias><br />
<br />
===我有一堆不想要的恶心的像素字体(pixel fonts)===<br />
只有两个字体你需要一定保留,否则X服务无法启动:'cursor' 和 'fixed', 他们都在/usr/share/fonts/misc目录. 如果你不想要除此之外所有的像素字体, 你可以删除那个目录下多数文件, 除了'''cursor.pcf.gz'''和所有类似'''9x18.pcf.gz'''或者'''9x18-ISO8859-1.pcf.gz'''. 我删除所有不需要字体后,misc目录还有大约337个文件, 所以如果你比这个数字少,那么在重启X之前你最好是还原删除的问题件.<br />
<br />
译者补充:<br />
*我试过这种方法,不过我的文件是可以更少的,只需要保留cursor.pcf.gz和类似6x13-Iso8859-[1-10].pcf.gz就行了,没有实验能不能更少,其实没有必要删除这么多,系统还是会剩下某个字号的fiexd字体,可以利用上面提到的字体替换方法替换成你喜欢字体,避免任何程序调用.<br />
<br />
*如够你删除了所有文件,但是没有备份,那么可以<br />
pacman -S xorg-fonts-misc<br />
来重新安装这个字体,否则你的X是不能启动的,当然也可以解压你cache文件夹下相应包.<br />
<br />
*这种方法对于opera的中文字体难看问题有一定程度的解决<br />
<br />
===我的点阵字体被禁用了,我想使用它们.===<br />
默认的, fontconfig 2.3.2-4和更高版本会禁用点阵(bitmap)字体. 这个设置是被/etc/fonts/conf.d/10-no-bitmaps.conf管理的, 在更高版本里面是/etc/fonts/conf.d/10-bitmaps.conf.<br />
启用点阵字体而且在升级fontconfig后也保持, 建立一个软链接从yes-bitmaps.conf到10-bitmaps.conf, 覆盖no-bitmaps.conf.<br />
<br />
===为没有粗斜体的字体构造粗体和斜体===<br />
Freetype已经具备这样的能力,但是如果不是程序要求,是不会这样作的 - 也就是说它自己无论如何也不会给正常字体添加粗斜体样式. 要是用这些样式,你需要手动编辑''/usr/share/fonts/fonts.cache-1'' (保留一份你的修改,因为fc-cache的更新会覆盖它). 假设你有一个字体叫Dupree:<br />
"dupree.ttf" 0 "Dupree:style=Regular:slant=0:weight=80:width=100:foundry=unknown:index=0:outline=True:....<br />
复制这一行, 把 ''style=Regular''改成''style=Bold''或者其他样式. 同时为斜体更改 ''slant=0'' 为 ''slant=100'' , 为粗体更改''weight=80''为''weight=200'' (粗斜体则都更改):<br />
"dupree.ttf" 0 "Dupree:style=Bold Italic:slant=100:weight=200:width=100:foundry=unknown:index=0:outline=True:....<br />
添加必须的设置到''~/.fonts.conf'':<br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test compare="more_eq" name="weight"><int>140</int></test><br />
<edit mode="assign" name="embolden"><bool>true</bool></edit><br />
</match><br />
<match target="font"><br />
<test name="family" qual="any"><br />
<string>Dupree</string><br />
&lt;!-- other fonts here .... --&gt;<br />
</test><br />
<test compare="more_eq" name="slant"><int>80</int></test><br />
<edit mode="assign" name="matrix"><br />
<times><br />
<name>matrix</name><br />
<matrix><br />
<double>1</double><double>0.2</double><br />
<double>0</double><double>1</double><br />
</matrix><br />
</times><br />
</edit><br />
</match><br />
(注意,现在你就能使用粗体了 - 或者把他们变得更粗)<br />
<br />
===~/.fonts.conf===<br />
一个网络开发者的.~/[[.fonts.conf]],是论坛上来的. 备份你现有的这是,尝试一下. <br />
<pre><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<br />
<!-- the cathectic LCD tweaks, from linuxquestions.org,<br />
http://www.linuxquestions.org/questions/showthread.php? postid=1361098#post1361098 --><br />
<br />
<fontconfig><br />
<br />
<!-- Disable sub-pixel rendering.<br />
X detects it anyway, and if you set this as well, it just looks really horrible --><br />
<match target="font" ><br />
<edit mode="assign" name="rgba" ><br />
<const>none</const><br />
</edit><br />
</match><br />
<match target="font" ><br />
<edit mode="assign" name="hinting"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<match target="font" ><br />
<edit mode="assign" name="hintstyle"><br />
<const>hintfull</const><br />
</edit><br />
</match><br />
<br />
<!-- The first part of the 'magic.'<br />
This makes the fonts start to look nice,<br />
but some of the shapes will be distorted, so hinting is needed still --><br />
<match target="font" ><br />
<edit mode="assign" name="antialias"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<br />
<!-- Autohinter is not turned on automatically.<br />
Only disable this if you have recompiled Freetype with the bytecode interpreter,<br />
which is run automatically.<br /> --><br />
<match target="pattern" ><br />
<edit mode="assign" name="autohint"><br />
<bool>true</bool><br />
</edit><br />
</match><br />
<match target="font"><br />
<test name="weight" compare="more"><br />
<const>medium</const><br />
</test><br />
<edit name="autohint" mode="assign"><br />
<bool>false</bool><br />
</edit><br />
</match><br />
<!-- Helvetica is a non true type font, and will look bad.<br />
This replaces it with whatever is the default sans-serif font --><br />
<match target="pattern" name="family" ><br />
<test name="family" qual="any" ><br />
<string>Helvetica</string><br />
</test><br />
<edit mode="assign" name="family" ><br />
<string>sans-serif</string><br />
</edit><br />
</match><br />
<dir>~/.fonts</dir><br />
</fontconfig><br />
</pre><br />
<br />
===另一个.fonts.conf===<br />
<pre><br />
<?xml version="1.0"?><br />
<!DOCTYPE fontconfig SYSTEM "fonts.dtd"><br />
<br />
<fontconfig><br />
<br />
<!-- Info:<br />
xeffects thread: http://forums.gentoo.org/viewtopic-t-511382.html<br />
http://wiki.archlinux.org/index.php/XOrg_Font_Configuration<br />
http://antigrain.com/research/font_rasterization/index.html<br />
http://fontconfig.org/fontconfig-user.html<br />
--><br />
<br />
<br />
<!-- http://bugs.gentoo.org/show_bug.cgi?id=130466 --><br />
<br />
<alias><br />
<family>serif</family><br />
<prefer><br />
<family>Bitstream Vera Serif</family><br />
<family>DejaVu Serif</family><br />
<family>WenQuanYi Micro Hei</family><br />
<family>WenQuanYi Zen Hei</family><br />
</prefer><br />
</alias><br />
<br />
<alias><br />
<family>sans-serif</family><br />
<prefer><br />
<family>DejaVu Sans</family><br />
<family>Bitstream Vera Sans</family><br />
<family>WenQuanYi Micro Hei</family><br />
<family>WenQuanYi Zen Hei</family><br />
</prefer><br />
</alias><br />
<br />
<alias><br />
<family>monospace</family><br />
<prefer><br />
<family>DejaVu Sans Mono</family><br />
<family>Bitstream Vera Sans Mono</family><br />
<family>WenQuanYi Micro Hei Mono</family><br />
<family>WenQuanYi Zen Hei Mono</family><br />
</prefer><br />
</alias><br />
<br />
<!-- Reject bitmap fonts in favour of Truetype, Postscript, etc. --><br />
<selectfont><br />
<rejectfont><br />
<pattern><br />
<patelt name="scalable"><br />
<bool>false</bool><br />
</patelt><br />
</pattern><br />
</rejectfont><br />
</selectfont><br />
<br />
<!-- Replace Luxi Sans with a better-looking font - looks terrible at e.g. http://market-ticker.org/ --><br />
<match name="family" target="pattern"><br />
<test name="family" qual="any"><br />
<string>Luxi Sans</string><br />
</test><br />
<edit name="family" mode="assign"><br />
<string>Liberation Sans</string><br />
</edit><br />
</match><br />
<br />
<!-- Ubuntu options: lcdnone, lcddefault, lcdlight, lcdlegacy --><br />
<!-- hintnone, hintslight, hintmedium, hintfull --><br />
<!-- Keep autohint off --><br />
<!-- Blurry fonts: Try rgb, bgr, vrgb, vbgr for "rgba" --><br />
<!-- Blurry: http://forums.gentoo.org/viewtopic-p-5060979.html#5060979 --><br />
<match target="font"><br />
<edit name="rgba" mode="assign"><const>rgb</const></edit><br />
<edit name="autohint" mode="assign"><bool>false</bool></edit><br />
<edit name="antialias" mode="assign"><bool>true</bool></edit><br />
<edit name="hinting" mode="assign"><bool>true</bool></edit><br />
<edit name="hintstyle" mode="assign"><const>hintmedium</const></edit><br />
<edit name="lcdfilter" mode="assign"><const>lcddefault</const></edit><br />
</match><br />
<br />
<!-- Tweak Courier --><br />
<match name="family" target="pattern"><br />
<test name="family" qual="any"><br />
<string>Courier</string><br />
</test><br />
<edit name="lcdfilter" mode="assign"><const>lcdlegacy</const></edit><br />
</match><br />
<br />
<!-- Tweak Courier New --><br />
<match name="family" target="pattern"><br />
<test name="family" qual="any"><br />
<string>Courier New</string><br />
</test><br />
<edit name="lcdfilter" mode="assign"><const>lcdlegacy</const></edit><br />
</match><br />
<br />
</fontconfig><br />
<br />
<br />
</pre><br />
WikiMigration--[[User:Dlanor|dlanor]] 14:05, 23 Jul 2005 (EDT)</div>Jaurunghttps://wiki.archlinux.org/index.php?title=ArchWiki:Translation_Team_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=229032ArchWiki:Translation Team (简体中文)2012-10-16T13:46:05Z<p>Jaurung: /* 页面维护列表 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:ArchWiki (简体中文)]]<br />
[[en:ArchWiki Translation Team]]<br />
[[es:ArchWiki Translation Team]]<br />
[[hr:ArchWiki Translation Team]]<br />
[[it:ArchWiki Translation Team]]<br />
[[pl:ArchWiki Translation Team]]<br />
[[tr:ArchWiki_Çeviri_Ekibi]]<br />
Arch Wiki 上有许多中文页面,这些页面是无数中文志愿者劳动的结晶。随着时间推移,有些页面因为没有及时维护,内容严重过时。而目前的翻译工作缺少组织,效率偏低。所以参照西班牙和意大利翻译组的做法,添加这个页面。<br />
<br />
如果希望进行翻译和维护,只需要编辑下面的[[#页面维护列表]],将自己加为页面的维护者。如果列表中还没有要认领翻译的页面,请自行添加。如果因为时间原因无法再维护页面,请及时将自己从维护者列表中删除。<br />
<br />
== 创建翻译 ==<br />
{{注意|如果不准备翻译页面的大部分内容,请尽量不要新建简体中文页面。检查英文页面的更新需要花费不少精力,没有翻译的页面会增加维护负担。}}<br />
# 如果还不知道如何编辑 wiki,请阅读 [[Help:Editing (简体中文)|编辑帮助]]。<br />
# 阅读 [[Help:i18n (简体中文)|i18n帮助]],文章给出了 ArchWiki 国际化和本地化的指南。<br />
# [[Special:UserLogin |登录]] 以进行编辑。<br />
# 选择要翻译的页面,例如从 [[Special:Random|随机页面]] 或[[#页面维护列表 | 页面维护列表]] 中选择一个未翻译完成的页面。假设要翻译 [[Some Page]].<br />
# 进入选择的英文页面,点击页面顶部的 '''编辑'''。<br />
# 添加要翻译文件的语言间链接 (参见[[Help:i18n#Interlanguage links]])。<br />
# 复制所有页面代码。<br />
# 保存页面 (新加了语言链接)<br />
# 访问页面右边新添加的语言链接,应该会进到 [[Some Page (简体中文)]] : {{ic|<nowiki>https://wiki.archlinux.org/index.php/Some_Page_(</nowiki>''简体中文'')}}<br />
# 因为页面不存在,点击 '''创建'''。<br />
# 将显示一个编辑器 - 粘贴复制的英文页面。<br />
# 将文章分类修改为本地化版本,例如将 {{ic|<nowiki>[[Category:Internationalization]]</nowiki>}} 修改为 {{ic|<nowiki>[[Category:Internationalization (简体中文)]]</nowiki>}}<br />
# 修改语言间链接,指向英文页面(将 {{ic|zh-CN}} 修改为 {{ic|en}},并将英文页面移到文章顶部。<br />
# 翻译页面,进行保存。<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
# 更新所有其它语言页面,加入刚翻译文章的语言间链接。<br />
# (可选)创建一个简体中文名称的页面,指向新创建的页面:访问 {{ic|<nowiki>https://wiki.archlinux.org/index.php/</nowiki>''页面的中文名称''}}.<br />
# (可选)建立新页面,并加入:{{bc|<nowiki>#REDIRECT [[Some Page (简体中文)</nowiki>]]}}<br />
<br />
== 完善翻译 ==<br />
[https://wiki.archlinux.org/index.php?title=Special:WhatLinksHere/Template:Translateme_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&limit=100 这个页面] 包含了需要完善翻译的简体中文页面。完善翻译的基本步骤:<br />
# 选择自己比较熟悉的文章进行翻译<br />
# 先检查英文页面的对应段落,更新成最新的英文后再翻译,避免翻译过时的内容,减少信息遗漏。<br />
# 翻译完成后删除页面中的 <nowiki>{{translateme (简体中文)}}</nowiki> 标记<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
<br />
== 维护翻译 ==<br />
完成页面的翻译只是初步完成任务,即时同步英文页面改动、更新翻译是一个持续性的工作,可能会耗费更多的时间。<br />
<br />
=== 页面认领 ===<br />
所有人都可以认领页面。认领后的责任包括进行翻译,关注英文页面的改动,及时同步翻译。<br />
<br />
为了更好的跟踪英文页面的修改,请务必在设置中启用监视列表邮件通知,并监视对应的英文页面(从设置中找到监视列表,加入英文页面。或者直接到英文页面点击页面顶端的监视标签。这样只要有改动,就会收到邮件通知)。<br />
<br />
{{小贴士|如果收到邮件通知后没有访问页面或者访问了页面却没有登录用户,下次页面改动时就不会再发邮件通知。可以点击监视列表中的'''标记所有页面为已读'''再次获取更新。}}<br />
<br />
如果页面有维护者但长期得不到更新,将会在维护列表中删除维护者。<br />
<br />
=== 发现过期页面怎么办? === <br />
如果发现有 Wiki 页面过期或错误:<br />
* 小的改动,有时间可以立即进行修改同步,维护者并不控制页面的编辑权限,越多的人参与维护越好。如果改动较大,请先联系维护者,避免重复劳动。<br />
* 没有时间查看更改,请给页面加上 {{ic|<nowiki>{{out of date}}</nowiki>}} 模版,这样其他贡献者更容易发现需要更新的页面,而读者看到过期标记就可以直接查看英文页面,以免被错误内容误导,白白耽误时间。<br />
* 没有时间翻译,请将过期的中文部分删去,从英文页面中复制更改的部分到中文页面的相应部分,去掉{{ic|<nowiki>{{out of date}}</nowiki>}}模板(如果页面上有的话)并加上{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他贡献者就更容易发现需要翻译的页面,而读者也不会被过期的内容误导。<br />
如果发现有页面未翻译:<br />
* 有时间的话,请将页面中的英文部分翻译为中文,并去掉{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板。<br />
* 没有时间翻译,请为页面添加{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他的贡献者就能更容易发现需要翻译的页面。<br />
{{注意|在修改页面上的模板时,请同时更新页面维护列表的翻译状态。}}<br />
<br />
=== 翻译状态模板 ===<br />
Arch 作为滚动发行版,软件变化比较快,对应的文档变化也比较快。许多翻译的文章由于缺乏更新,会产生命令运行出错或不起作用等问题。而由于这些过期页面没有及时标记出来,所以用户无法及时获得更新。[[Template:TranslationStatus (简体中文)|翻译状态模板]]就是为了解决这个问题而创建。<br />
<br />
此模板可以起到如下作用:<br />
* 为用户提供翻译状况,包括翻译时间、英文页面的最后版本等<br />
* 用户可以点击查看翻译后,英文页面的改动,这样英文不是很好的用户可以只查看很小一部分英文内容,并判断出是否影响操作。<br />
* 翻译人员可以跟踪页面状况,通过[https://wiki.archlinux.org/index.php/Special:WhatLinksHere/Template:TranslationStatus_(简体中文) 模板的反向链接]可以查找到所有标记页面,查看需要更新翻译的部分。<br />
<br />
[[Template:TranslationStatus (简体中文)|模板页面]]有详细的使用方法。<br />
<br />
=== 页面维护列表 ===<br />
{{注意|请按照拉丁字母顺序添加页面。}}<br />
翻译状态说明:<br />
;过期:页面内容未与英文页面同步,对应{{ic|<nowiki>{{out of date}}</nowiki>}} 模版<br />
;未翻译:页面中含有英文内容,对应{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板<br />
;完成:页面已与英文页面同步<br />
{| class="wikitable sortable collapsible" border="1"<br />
|-<br />
! 页面<br />
! 翻译状态<br />
! 维护者<br />
! class="unsortable" width="30%" | 备注<br />
|-<br />
| [[acpid (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[ACPI hotkeys (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ACPI modules (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Activating Numlock on Bootup (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Ad-hoc networking (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Advanced Linux Sound Architecture (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AHCI (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Allow Users to Shutdown (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[aMule (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Android (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Apache, suEXEC and Virtual Hosts (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Based Distributions (Active) (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ArchWiki:About (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ATI (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AUR Helpers (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Avant Window Navigator (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[awesome (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无<br />
|-<br />
| [[Bash (简体中文)]]<br />
| 完成<br />
| Jaurung<br />
| 无<br />
|-<br />
| [[Bumblebee (简体中文)]]<br />
| 完成<br />
| Peter<br />
| 无<br />
|-<br />
| [[Common Applications (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Compiz (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Configuring Network (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Creating Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Disabling IPv6 (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Downgrading Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Font Configuration (简体中文)]]<br />
| 待更新<br />
| Jaurung<br />
| 完善中<br />
|-<br />
| [[Fonts (简体中文)]]<br />
| 翻译中<br />
| zhangwen<br />
| 完善中<br />
|-<br />
| [[Fstab (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[GRUB (简体中文)]]<br />
| 翻译中<br />
| 无<br />
| 无<br />
|-<br />
| [[Help:Style (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[IBus (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Improve_Pacman_Performance_(简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation/Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Laptop Mode Tools (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[LibreOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Local Mirror (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Makepkg (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[mkinitcpio (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Network Time Protocol daemon (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Official Repositories (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Openbox (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[OpenOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman GUI Frontends (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[pacman Tips (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pidgin (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无 <br />
|- <br />
| [[Polipo (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无 <br />
|-<br />
| [[Python (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无 <br />
|-<br />
| [[Smart Common Input Method platform (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Common Applications/Science (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Secure Shell (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Systemd (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[TeXLive (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Vim (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[VMware (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Wine (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[Xscreensaver (简体中文)]]<br />
| 完成<br />
| liuyix<br />
| 无<br />
|-<br />
| [[Xmonad (简体中文)]]<br />
| 未翻译<br />
| Rns<br />
| 翻译中<br />
|}<br />
<br />
== 贡献列表 ==<br />
为翻译做出贡献的用户请加入列表,感谢所有人做出的贡献。<br />
* [[User:Fengchao|Fengchao]] &ndash; [[Special:Contributions/Fengchao|贡献]] &ndash; [[Special:EmailUser/Fengchao|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Skydiver|Skydiver]] &ndash; [[Special:Contributions/Skydiver|贡献]] &ndash; [[Special:EmailUser/Skydiver|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Alswl|Alswl]] &ndash; [[Special:Contributions/Alswl|贡献]] &ndash; [[Special:EmailUser/Alswl|Send Email]]<br />
* [[User:Reverland|Reverland]] &ndash; [[Special:Contributions/Reverland|贡献]] &ndash; [[Special:EmailUser/Reverland|Send Email]]<br />
* [[User:Cuihao|cuihao]] &ndash; [[Special:Contributions/Cuihao|贡献]] &ndash; [[Special:EmailUser/Cuihao|Send Email]]<br />
* [[User:Cael|Cael]] &ndash; [[Special:Contributions/Cael|贡献]] &ndash; [[Special:EmailUser/Cael|Send Email]]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Skydiver&diff=229029User talk:Skydiver2012-10-16T13:43:35Z<p>Jaurung: /* Configuration的中文页面 */</p>
<hr />
<div>==Kernel页面==<br />
你好,Kernel页面已经out of date,貌似很多内容需要改动。<br />
[[User:Liuyix|Liuyix]] ([[User talk:Liuyix|talk]]) 12:15, 22 July 2012 (UTC)<br />
:你是说[[Kernels (简体中文)]] 页面吧?--[[User:Skydiver|Skydiver]] ([[User talk:Skydiver|talk]]) 12:37, 22 July 2012 (UTC)<br />
==Configuration的中文页面==<br />
你好,Skydiver,[[Font Configuration]]的中文页面是由你来维护吗?页面已经过期了,我想来维护Font Configuration中文页面。--Jaurung<br />
:Jaurung你好。最近我没有没有维护这个页面。[[ArchWiki Translation Team (简体中文)#页面维护列表|这里]]有中文页面的维护列表。多谢为ArchWiki做贡献~--[[User:Skydiver|Skydiver]] ([[User talk:Skydiver|talk]]) 05:46, 16 October 2012 (UTC)<br />
::好的,谢谢回复:-) --[[User:Jaurung|Jaurung]] ([[User talk:Jaurung|talk]]) 21:43, 16 October 2012 (UTC)</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Skydiver&diff=228964User talk:Skydiver2012-10-16T05:40:50Z<p>Jaurung: /* Kernel页面 */</p>
<hr />
<div>==Kernel页面==<br />
你好,Kernel页面已经out of date,貌似很多内容需要改动。<br />
[[User:Liuyix|Liuyix]] ([[User talk:Liuyix|talk]]) 12:15, 22 July 2012 (UTC)<br />
:你是说[[Kernels (简体中文)]] 页面吧?--[[User:Skydiver|Skydiver]] ([[User talk:Skydiver|talk]]) 12:37, 22 July 2012 (UTC)<br />
==Configuration的中文页面==<br />
你好,Skydiver,Font Configuration的中文页面是由你来维护吗?页面已经过期了,我想来维护Font Configuration中文页面。--Jaurung</div>Jaurunghttps://wiki.archlinux.org/index.php?title=User_talk:Skydiver&diff=228963User talk:Skydiver2012-10-16T05:40:27Z<p>Jaurung: /* Kernel页面 */</p>
<hr />
<div>==Kernel页面==<br />
你好,Kernel页面已经out of date,貌似很多内容需要改动。<br />
[[User:Liuyix|Liuyix]] ([[User talk:Liuyix|talk]]) 12:15, 22 July 2012 (UTC)<br />
:你是说[[Kernels (简体中文)]] 页面吧?--[[User:Skydiver|Skydiver]] ([[User talk:Skydiver|talk]]) 12:37, 22 July 2012 (UTC)<br />
你好,Skydiver,Font Configuration的中文页面是由你来维护吗?页面已经过期了,我想来维护Font Configuration中文页面。--Jaurung</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228900Bash (简体中文)2012-10-15T17:07:59Z<p>Jaurung: /* 高级的补全方法 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{TranslationStatus (简体中文)|Bash|2012-10-15|220209}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{注意|传统模式指以{{Ic|sh}}来调用}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常进入到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为需要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228898Bash (简体中文)2012-10-15T16:55:44Z<p>Jaurung: /* 外壳和环境变量 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{TranslationStatus (简体中文)|Bash|2012-10-15|220209}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{注意|传统模式指以{{Ic|sh}}来调用}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常进入到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228896Bash (简体中文)2012-10-15T16:42:23Z<p>Jaurung: /* 命令未找到时的钩子拓展(HOOKS) */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{TranslationStatus (简体中文)|Bash|2012-10-15|220209}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{注意|传统模式指以{{Ic|sh}}来调用}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常进入到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228895Bash (简体中文)2012-10-15T16:30:58Z<p>Jaurung: /* 函数 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{TranslationStatus (简体中文)|Bash|2012-10-15|220209}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{注意|传统模式指以{{Ic|sh}}来调用}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常进入到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228894Bash (简体中文)2012-10-15T16:27:03Z<p>Jaurung: /* 配置文件在启动时的引用顺序 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{TranslationStatus (简体中文)|Bash|2012-10-15|220209}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{注意|传统模式指以{{Ic|sh}}来调用}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=ArchWiki:Translation_Team_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228881ArchWiki:Translation Team (简体中文)2012-10-15T14:08:30Z<p>Jaurung: /* 页面维护列表 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:ArchWiki (简体中文)]]<br />
[[en:ArchWiki Translation Team]]<br />
[[es:ArchWiki Translation Team]]<br />
[[hr:ArchWiki Translation Team]]<br />
[[it:ArchWiki Translation Team]]<br />
[[pl:ArchWiki Translation Team]]<br />
[[tr:ArchWiki_Çeviri_Ekibi]]<br />
Arch Wiki 上有许多中文页面,这些页面是无数中文志愿者劳动的结晶。随着时间推移,有些页面因为没有及时维护,内容严重过时。而目前的翻译工作缺少组织,效率偏低。所以参照西班牙和意大利翻译组的做法,添加这个页面。<br />
<br />
如果希望进行翻译和维护,只需要编辑下面的[[#页面维护列表]],将自己加为页面的维护者。如果列表中还没有要认领翻译的页面,请自行添加。如果因为时间原因无法再维护页面,请及时将自己从维护者列表中删除。<br />
<br />
== 创建翻译 ==<br />
{{注意|如果不准备翻译页面的大部分内容,请尽量不要新建简体中文页面。检查英文页面的更新需要花费不少精力,没有翻译的页面会增加维护负担。}}<br />
# 如果还不知道如何编辑 wiki,请阅读 [[Help:Editing (简体中文)|编辑帮助]]。<br />
# 阅读 [[Help:i18n (简体中文)|i18n帮助]],文章给出了 ArchWiki 国际化和本地化的指南。<br />
# [[Special:UserLogin |登录]] 以进行编辑。<br />
# 选择要翻译的页面,例如从 [[Special:Random|随机页面]] 或[[#页面维护列表 | 页面维护列表]] 中选择一个未翻译完成的页面。假设要翻译 [[Some Page]].<br />
# 进入选择的英文页面,点击页面顶部的 '''编辑'''。<br />
# 添加要翻译文件的语言间链接 (参见[[Help:i18n#Interlanguage links]])。<br />
# 复制所有页面代码。<br />
# 保存页面 (新加了语言链接)<br />
# 访问页面右边新添加的语言链接,应该会进到 [[Some Page (简体中文)]] : {{ic|<nowiki>https://wiki.archlinux.org/index.php/Some_Page_(</nowiki>''简体中文'')}}<br />
# 因为页面不存在,点击 '''创建'''。<br />
# 将显示一个编辑器 - 粘贴复制的英文页面。<br />
# 将文章分类修改为本地化版本,例如将 {{ic|<nowiki>[[Category:Internationalization]]</nowiki>}} 修改为 {{ic|<nowiki>[[Category:Internationalization (简体中文)]]</nowiki>}}<br />
# 修改语言间链接,指向英文页面(将 {{ic|zh-CN}} 修改为 {{ic|en}},并将英文页面移到文章顶部。<br />
# 翻译页面,进行保存。<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
# 更新所有其它语言页面,加入刚翻译文章的语言间链接。<br />
# (可选)创建一个简体中文名称的页面,指向新创建的页面:访问 {{ic|<nowiki>https://wiki.archlinux.org/index.php/</nowiki>''页面的中文名称''}}.<br />
# (可选)建立新页面,并加入:{{bc|<nowiki>#REDIRECT [[Some Page (简体中文)</nowiki>]]}}<br />
<br />
== 完善翻译 ==<br />
[https://wiki.archlinux.org/index.php?title=Special:WhatLinksHere/Template:Translateme_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&limit=100 这个页面] 包含了需要完善翻译的简体中文页面。完善翻译的基本步骤:<br />
# 选择自己比较熟悉的文章进行翻译<br />
# 先检查英文页面的对应段落,更新成最新的英文后再翻译,避免翻译过时的内容,减少信息遗漏。<br />
# 翻译完成后删除页面中的 <nowiki>{{translateme (简体中文)}}</nowiki> 标记<br />
# (推荐)给翻译完成的页面加上[[Template:TranslationStatus (简体中文)|翻译状态]],后有详细介绍。<br />
<br />
== 维护翻译 ==<br />
完成页面的翻译只是初步完成任务,即时同步英文页面改动、更新翻译是一个持续性的工作,可能会耗费更多的时间。<br />
<br />
=== 页面认领 ===<br />
所有人都可以认领页面。认领后的责任包括进行翻译,关注英文页面的改动,及时同步翻译。<br />
<br />
为了更好的跟踪英文页面的修改,请务必在设置中启用监视列表邮件通知,并监视对应的英文页面(从设置中找到监视列表,加入英文页面。或者直接到英文页面点击页面顶端的监视标签。这样只要有改动,就会收到邮件通知)。<br />
<br />
{{小贴士|如果收到邮件通知后没有访问页面或者访问了页面却没有登录用户,下次页面改动时就不会再发邮件通知。可以点击监视列表中的'''标记所有页面为已读'''再次获取更新。}}<br />
<br />
如果页面有维护者但长期得不到更新,将会在维护列表中删除维护者。<br />
<br />
=== 发现过期页面怎么办? === <br />
如果发现有 Wiki 页面过期或错误:<br />
* 小的改动,有时间可以立即进行修改同步,维护者并不控制页面的编辑权限,越多的人参与维护越好。如果改动较大,请先联系维护者,避免重复劳动。<br />
* 没有时间查看更改,请给页面加上 {{ic|<nowiki>{{out of date}}</nowiki>}} 模版,这样其他贡献者更容易发现需要更新的页面,而读者看到过期标记就可以直接查看英文页面,以免被错误内容误导,白白耽误时间。<br />
* 没有时间翻译,请将过期的中文部分删去,从英文页面中复制更改的部分到中文页面的相应部分,去掉{{ic|<nowiki>{{out of date}}</nowiki>}}模板(如果页面上有的话)并加上{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他贡献者就更容易发现需要翻译的页面,而读者也不会被过期的内容误导。<br />
如果发现有页面未翻译:<br />
* 有时间的话,请将页面中的英文部分翻译为中文,并去掉{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板。<br />
* 没有时间翻译,请为页面添加{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板,这样其他的贡献者就能更容易发现需要翻译的页面。<br />
{{注意|在修改页面上的模板时,请同时更新页面维护列表的翻译状态。}}<br />
<br />
=== 翻译状态模板 ===<br />
Arch 作为滚动发行版,软件变化比较快,对应的文档变化也比较快。许多翻译的文章由于缺乏更新,会产生命令运行出错或不起作用等问题。而由于这些过期页面没有及时标记出来,所以用户无法及时获得更新。[[Template:TranslationStatus (简体中文)|翻译状态模板]]就是为了解决这个问题而创建。<br />
<br />
此模板可以起到如下作用:<br />
* 为用户提供翻译状况,包括翻译时间、英文页面的最后版本等<br />
* 用户可以点击查看翻译后,英文页面的改动,这样英文不是很好的用户可以只查看很小一部分英文内容,并判断出是否影响操作。<br />
* 翻译人员可以跟踪页面状况,通过[https://wiki.archlinux.org/index.php/Special:WhatLinksHere/Template:TranslationStatus_(简体中文) 模板的反向链接]可以查找到所有标记页面,查看需要更新翻译的部分。<br />
<br />
[[Template:TranslationStatus (简体中文)|模板页面]]有详细的使用方法。<br />
<br />
=== 页面维护列表 ===<br />
{{注意|请按照拉丁字母顺序添加页面。}}<br />
翻译状态说明:<br />
;过期:页面内容未与英文页面同步,对应{{ic|<nowiki>{{out of date}}</nowiki>}} 模版<br />
;未翻译:页面中含有英文内容,对应{{ic|<nowiki>{{translateme (简体中文)}}</nowiki>}}模板<br />
;完成:页面已与英文页面同步<br />
{| class="wikitable sortable collapsible" border="1"<br />
|-<br />
! 页面<br />
! 翻译状态<br />
! 维护者<br />
! class="unsortable" width="30%" | 备注<br />
|-<br />
| [[acpid (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[ACPI hotkeys (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ACPI modules (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Activating Numlock on Bootup (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Ad-hoc networking (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Advanced Linux Sound Architecture (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AHCI (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Allow Users to Shutdown (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[aMule (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Android (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Apache, suEXEC and Virtual Hosts (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Based Distributions (Active) (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ArchWiki:About (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[ATI (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[AUR Helpers (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Avant Window Navigator (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[awesome (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无<br />
|-<br />
| [[Bash (简体中文)]]<br />
| 完成<br />
| Jaurung<br />
| 无<br />
|-<br />
| [[Bumblebee (简体中文)]]<br />
| 完成<br />
| Peter<br />
| 无<br />
|-<br />
| [[Common Applications (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Compiz (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Configuring Network (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Creating Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Disabling IPv6 (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Downgrading Packages (简体中文)]]<br />
| 完成<br />
| Cael<br />
| 无<br />
|-<br />
| [[Fonts (简体中文)]]<br />
| 翻译中<br />
| zhangwen<br />
| 完善中<br />
|-<br />
| [[Fstab (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[GRUB (简体中文)]]<br />
| 翻译中<br />
| 无<br />
| 无<br />
|-<br />
| [[Help:Style (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无<br />
|-<br />
| [[IBus (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Improve_Pacman_Performance_(简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Kernel Compilation/Arch Build System (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Laptop Mode Tools (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[LibreOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Local Mirror (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Makepkg (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[mkinitcpio (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Network Time Protocol daemon (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Official Repositories (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Openbox (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[OpenOffice (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pacman GUI Frontends (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[pacman Tips (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[Pidgin (简体中文)]]<br />
| 进行中<br />
| Cael<br />
| 无 <br />
|- <br />
| [[Polipo (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无 <br />
|-<br />
| [[Python (简体中文)]]<br />
| 完成<br />
| Fengchao<br />
| 无 <br />
|-<br />
| [[Smart Common Input Method platform (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Common Applications/Science (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Secure Shell (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 部分未翻译<br />
|-<br />
| [[Systemd (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[TeXLive (简体中文)]]<br />
| 未翻译<br />
| 无<br />
| 无<br />
|-<br />
| [[Vim (简体中文)]]<br />
| 完成<br />
| 无<br />
| 无<br />
|-<br />
| [[VMware (简体中文)]]<br />
| 过期<br />
| 无<br />
| 无<br />
|-<br />
| [[Wine (简体中文)]]<br />
| 完成<br />
| cuihao<br />
| 无<br />
|-<br />
| [[Xscreensaver (简体中文)]]<br />
| 完成<br />
| liuyix<br />
| 无<br />
|-<br />
| [[Xmonad (简体中文)]]<br />
| 未翻译<br />
| Rns<br />
| 翻译中<br />
|}<br />
<br />
== 贡献列表 ==<br />
为翻译做出贡献的用户请加入列表,感谢所有人做出的贡献。<br />
* [[User:Fengchao|Fengchao]] &ndash; [[Special:Contributions/Fengchao|贡献]] &ndash; [[Special:EmailUser/Fengchao|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Skydiver|Skydiver]] &ndash; [[Special:Contributions/Skydiver|贡献]] &ndash; [[Special:EmailUser/Skydiver|Send Email]] &ndash; [[ArchWiki:Maintainers|ArchWiki Maintainers]]<br />
* [[User:Alswl|Alswl]] &ndash; [[Special:Contributions/Alswl|贡献]] &ndash; [[Special:EmailUser/Alswl|Send Email]]<br />
* [[User:Reverland|Reverland]] &ndash; [[Special:Contributions/Reverland|贡献]] &ndash; [[Special:EmailUser/Reverland|Send Email]]<br />
* [[User:Cuihao|cuihao]] &ndash; [[Special:Contributions/Cuihao|贡献]] &ndash; [[Special:EmailUser/Cuihao|Send Email]]<br />
* [[User:Cael|Cael]] &ndash; [[Special:Contributions/Cael|贡献]] &ndash; [[Special:EmailUser/Cael|Send Email]]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228879Bash (简体中文)2012-10-15T14:02:54Z<p>Jaurung: </p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{TranslationStatus (简体中文)|Bash|2012-10-15|220209}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228878Bash (简体中文)2012-10-15T13:59:22Z<p>Jaurung: /* Bash历史补全 */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228877Bash (简体中文)2012-10-15T13:58:54Z<p>Jaurung: </p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===修正窗口大小调整时的换行===<br />
<br />
加入你在vi中调整了你的xterm大小,Bash并不会得到resize信号,所以你键入的文本就不会正确的换行,于是它们会重叠提示符。<br />
<br />
在{{ic|/etc/bash.bashrc}} (来自Debian)用下面的设置 :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash历史补全===<br />
Bash历史补全功能绑定到方向键上(下,上):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
或者同样的放在{{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
更多的信息在[[Readline#History]]和[https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228873Bash (简体中文)2012-10-15T13:50:38Z<p>Jaurung: /* Customise Title */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash&diff=228872Bash2012-10-15T13:50:35Z<p>Jaurung: /* 定制标题 */</p>
<hr />
<div>[[Category:Command shells]] <br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
[[zh-CN:Bash]]<br />
{{Article summary start}}<br />
{{Article summary text|Discussing and improving Bash's capabilities.}}<br />
{{Article summary heading|Related}}<br />
{{Article summary wiki|Readline}}<br />
{{Article summary wiki|Environment Variables}}<br />
{{Article summary wiki|Color Bash Prompt}}<br />
{{Article summary end}}<br />
'''Bash''' (Bourne-again Shell) is a [[Command shell|shell]]/programming language by the [[GNU Project]]. Its name is a homaging reference to its predecessor: the long-deprecated Bourne shell. Bash can be run on most UNIX-like operating systems, including GNU/Linux.<br />
<br />
==Invocation==<br />
Bash behaviour can be altered depending on how it is invoked. Some descriptions of different modes follow.<br />
===Login shell===<br />
If Bash is spawned by {{ic|login}} in a tty, by an [[SSH]] daemon, or similar means, it is considered a login shell. This mode can also be engaged using the {{Ic|-l}} or {{Ic|--login}} command line options.<br />
<br />
===Interactive shell===<br />
Bash is considered an interactive shell if it is started neither with the {{Ic|-c}} option nor any non-option arguments, and whose standard input and error are connected to terminals.<br />
<br />
===POSIX compliance===<br />
Bash can be run with enhanced POSIX compliance by starting Bash with the {{Ic|--posix}} command-line option or executing ‘{{Ic|set -o posix}}’ while Bash is running.<br />
<br />
===Legacy mode===<br />
In Arch {{ic|/bin/sh}} (which used to be the Bourne shell executable) is symlinked to {{ic|/bin/bash}}.<br />
<br />
If Bash is invoked with the name {{Ic|sh}}, it tries to mimic the startup behavior of historical versions of {{Ic|sh}}.<br />
<br />
==Configuration==<br />
{{poor writing}}<br />
===Configuration file overview===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''Non-standard'': only some distros, Arch included)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
An overview of the commonly used configuration files:<br />
====/etc/profile====<br />
{{ic|/etc/profile}} is sourced by all Bourne-compatible shells upon login. It sets up an environment upon login and loads application-specific ({{ic|/etc/profile.d/*.sh}}) settings.<br />
<br />
====.profile====<br />
This file is read and sourced by bash when an interactive login shell is started.<br />
<br />
====.bashrc====<br />
The file {{ic|~/.bashrc}} is read and sourced by bash when a non-login interactive shell is started, for example, when you open a virtual console from the desktop environment. This file is useful for setting up a user-specific shell environment.<br />
<br />
===Configuration file sourcing order at startup===<br />
These files are sourced by bash in different circumstances. <br />
* if interactive + login shell → {{ic|/etc/profile}} then the first readable of {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash will source {{ic|~/.bash_logout}} upon exit. <br />
* if interactive + non-login shell → {{ic|/etc/bash.bashrc}} then {{ic|~/.bashrc}}<br />
* if login shell + legacy mode → {{ic|/etc/profile}} then {{ic|~/.profile}}<br />
<br />
But, in Arch, by default:<br />
* {{ic|/etc/profile}} (indirectly) sources {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} which users are encouraged to copy to {{ic|~/.bash_profile}}, sources {{ic|~/.bashrc}}<br />
which means that {{ic|/etc/bash.bashrc}} and {{ic|~/.bashrc}} will be executed for all interactive shells, whether they are login shells or not.<br />
<br />
Examples of the user dotfiles can be found in {{ic|/etc/skel/}}.<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===Shell and environment variables===<br />
The behavior of bash and programs run by it can be influenced by a number of environment variable. Environment variables are used to store useful values such as command search directories, or which browser to use. When a new shell or script is launched it inherits its parent's variables, thus starting with an internal set of shell variables[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ].<br />
<br />
These shell variables in bash can be exported in order to become environment variables:<br />
VARIABLE=content<br />
export VARIABLE<br />
or with a shortcut<br />
export VARIABLE=content<br />
<br />
Environment variables are conventionally placed in {{ic|~/.profile}} or {{ic|/etc/profile}} so that all bourne-compatible shells can use them.<br />
<br />
See [[Environment Variables]] for more general information.<br />
<br />
==Command line==<br />
Bash command line is managed by the separate library called [[Readline]]. Readline provides a lot of shortcuts for interacting with the command line i.e. moving back and forth on the word basis, deleting words etc. It is also Readline's responsibility to manage [[Readline#History|history]] of input commands. Last, but not least, it allows you to create [[Readline#Macros|macros]].<br />
<br />
==Aliases==<br />
[[Wikipedia:alias|alias]] is a command, which enables a replacement of a word with another string. It is often used for abbreviating a system command, or for adding default arguments to a regularly used command.<br />
<br />
Personal aliases are preferably stored in {{ic|~/.bashrc}}, and system-wide aliases (which affect all users) belong in {{ic|/etc/bash.bashrc}}.<br />
<br />
An example excerpt from {{ic|~/.bashrc}} covering several time-saving aliases:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with your favorite AUR helper)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==Functions==<br />
Bash also support functions. The following function will extract a wide range of compressed file types. Add the function to {{ic|~/.bashrc}} and use it with the syntax {{Ic|extract <file1> <file2> ...}}<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{note|[[Bash]] users should make sure extglob is enabled: {{Ic|shopt -s extglob}}, for example by adding it to the {{ic|.bashrc}}. It is enabled by default if using [[Bash#Advanced completion|Bash completion]]. [[Zsh]] users should do: {{Ic|setopt kshglob}} instead.}}<br />
Another way to do this is to install the {{AUR|unp}} package from aur which contains a perl script.<br />
<br />
Very often changing to a directory is followed by the 'ls' command to list its contents. Therefore it is helpful to have a second function doing both at once.<br />
In this example we will name it 'cl' and show an error message if the specified directory does not exist.<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
Of course the ls command can be altered to fit your needs, for example 'ls -hall --color=auto'.<br />
<br />
More bash function examples can be found [https://bbs.archlinux.org/viewtopic.php?id=30155 here.]<br />
<br />
==Tips and tricks==<br />
===Prompt customization===<br />
The bash prompt is governed by the variable {{Ic|$PS1}}. To colorize the bash prompt, first comment out the default {{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
Then add the following line:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
This {{Ic|$PS1}} is useful for a root bash prompt, with red designation and green console text. For details on customizing your bash prompt, see [[Color Bash Prompt]].<br />
<br />
===Auto-completion===<br />
It is useful to have the auto-complete feature (pressing {{Keypress|Tab}} key twice on the keyboard) after you type some command like sudo.<br />
<br />
To do this add a line in this format to your {{ic|~/.bashrc}} file:<br />
complete -cf your_command<br />
<br />
For example, to enable auto-complete after sudo and man:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====Advanced completion====<br />
Despite Bash's native support for basic file name, command, and variable auto-completion, there are ways of improving and extending its reach.<br />
<br />
The {{Pkg|bash-completion}} package extends functionality by adding auto-completion to a wide range of commands and their options. Enabling advanced bash completion is quite simple, just install the following package:<br />
# pacman -S bash-completion<br />
Start a new shell and it will be automatically enabled thanks to {{ic|/etc/bash.bashrc}}.<br />
{{Note|If you added any lines similar to "complete -cf sudo" as mentioned in the previous settings and have problems with bash-completion, try removing those lines.}}<br />
<br />
{{Note|1=The normal expansions that you are used to like "$ ls file.*<tab><tab>" will not work unless you "$ compopt -o bashdefault <prog>" for all programs you want to fallback to the normal glob expansions. See https://bbs.archlinux.org/viewtopic.php?id=128471 and https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====Faster completion====<br />
By appending the following into the readline initialization file ({{ic|~/.inputrc}} or {{ic|/etc/inputrc}} by default):<br />
set show-all-if-ambiguous on<br />
it is no longer necessary to hit {{Keypress|Tab}} (default binding) twice to produce a list of all possible completions (both when a partial completion is possible and when no completion is possible), as a single key-press will suffice. Alternatively, to produce such a list only when no completion is possible (i.e., not when a partial completion is possible), append the following command in lieu of the previous one:<br />
set show-all-if-unmodified on<br />
<br />
=== The "command not found" hook ===<br />
The [[pkgfile]] package includes a "command not found" hook that will automatically search the [[official repositories]] when you enter an unrecognized command. Then it will display something like this:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
An alternative "command not found" hook is also provided by the AUR package [https://aur.archlinux.org/packages.php?ID=52305 command-not-found], which will generate an output like the following:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== Disable Ctrl+z in terminal===<br />
You can disable {{Keypress|Ctrl+z}} (pauses/closes your CLI application) feature for you CLI by wrapping your command in this script<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
example:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
With this example script, when you accidentally press {{Keypress|Ctrl+z}} instead of {{Keypress|Shift+z}} or some other key combination while playing Adom(game) your game will not end. Nothing will happen because {{Keypress|Ctrl+z}} will be ignored.<br />
<br />
===Clear the screen after logging out===<br />
To clear the screen after logging out on a virtual terminal, append the following lines to {{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII art, fortunes and cowsay===<br />
Along with colors, system info and ASCII symbols, Bash can be made to display a piece of ASCII art on login. ASCII images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, place the string <br />
cat /path/to/text/file<br />
at the top of {{ic|~/.bashrc}}.<br />
<br />
Random poignant, inspirational, silly or snide phrases can also be shown. To see an example, install the {{Pkg|fortune-mod}} package from the {{Ic|extra}} repository.<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other has gone.}}<br />
<br />
To have a random phrase displayed when logging into a terminal, just set <br />
command fortune<br />
as the top line in {{ic|~/.bashrc}}.<br />
<br />
{{Note|By default, {{Ic|fortune}} displays quotes and phrases that are rather inoccuous. However, the package does contain a set of comments some will find offensive, located in {{ic|/usr/share/fortune/off}}. See the man page for more info on these.}}<br />
<br />
These two features can be combined, using the program {{Pkg|cowsay}}. Modify the line at the top of {{ic|~/.bashrc}} to read <br />
command cowsay $(fortune)<br />
<br />
or<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
The ASCII images are generated by {{ic|.cow}} text files located in {{ic|/usr/share/cows}}, and all themes can be listed with the command {{Ic|cowsay -l}} These files can be edited to the user's liking; custom images can also be created from scratch or found on the net. The easiest way create a custom cow file from an image found online would be to open an existing {{ic|.cow}} file in a text editor, copy-and-paste the image from a browser and save the file as a different name. Test the custom file using<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
This can produce some nice eye candy, and the commands used can be more complex. For a specialized example, take a look [http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ here.] Another example, to use a random cow, random facial expression, and nicely wrap the text of long fortunes.<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{Note|If you want a full colored cowsay-like art, the best option is {{Pkg|ponysay}}, this show full colored ponies (more than 220 at version 1.1) in you terminal (inside X11 or in TTY you have full 256 colored ponies) runing 'ponysay "command or fortune command"', the complete list of ponies are showed usind 'ponysay -l'.<br />
Exist in AUR a tool for creating more ponies (or other stuff) called {{aur|util-say-git}}, and these news archives need to be stored in $HOME/.local/share/ponysay/ponies and $HOME/.local/share/ponysay/ttyponies for desktop and TTY respectibely}}<br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory you will need the {{Pkg|rpmextract}} package installed. Then from your home directory, run the following:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
This will change your title to the last command run, and make sure your history file is always up-to-date:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===Fix line wrap on window resize===<br />
<br />
When you resize your xterm in vi for example, Bash will not get the resize signal, and the text you type will not wrap correctly, overlapping the prompt.<br />
<br />
Use the following in your {{ic|/etc/bash.bashrc}} (from Debian) :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash history completion===<br />
Bash history completion bound to arrow keys (down, up):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
or equivalently in {{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
More info at [[Readline#History]] and [https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==See also==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]<br />
* [http://wiki.gotux.net/bash:arc Create and Extract Various Archives]<br />
* [http://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html Readline Init File Syntax ]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash&diff=228870Bash2012-10-15T13:49:57Z<p>Jaurung: /* Customise Title */</p>
<hr />
<div>[[Category:Command shells]] <br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
[[zh-CN:Bash]]<br />
{{Article summary start}}<br />
{{Article summary text|Discussing and improving Bash's capabilities.}}<br />
{{Article summary heading|Related}}<br />
{{Article summary wiki|Readline}}<br />
{{Article summary wiki|Environment Variables}}<br />
{{Article summary wiki|Color Bash Prompt}}<br />
{{Article summary end}}<br />
'''Bash''' (Bourne-again Shell) is a [[Command shell|shell]]/programming language by the [[GNU Project]]. Its name is a homaging reference to its predecessor: the long-deprecated Bourne shell. Bash can be run on most UNIX-like operating systems, including GNU/Linux.<br />
<br />
==Invocation==<br />
Bash behaviour can be altered depending on how it is invoked. Some descriptions of different modes follow.<br />
===Login shell===<br />
If Bash is spawned by {{ic|login}} in a tty, by an [[SSH]] daemon, or similar means, it is considered a login shell. This mode can also be engaged using the {{Ic|-l}} or {{Ic|--login}} command line options.<br />
<br />
===Interactive shell===<br />
Bash is considered an interactive shell if it is started neither with the {{Ic|-c}} option nor any non-option arguments, and whose standard input and error are connected to terminals.<br />
<br />
===POSIX compliance===<br />
Bash can be run with enhanced POSIX compliance by starting Bash with the {{Ic|--posix}} command-line option or executing ‘{{Ic|set -o posix}}’ while Bash is running.<br />
<br />
===Legacy mode===<br />
In Arch {{ic|/bin/sh}} (which used to be the Bourne shell executable) is symlinked to {{ic|/bin/bash}}.<br />
<br />
If Bash is invoked with the name {{Ic|sh}}, it tries to mimic the startup behavior of historical versions of {{Ic|sh}}.<br />
<br />
==Configuration==<br />
{{poor writing}}<br />
===Configuration file overview===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''Non-standard'': only some distros, Arch included)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
An overview of the commonly used configuration files:<br />
====/etc/profile====<br />
{{ic|/etc/profile}} is sourced by all Bourne-compatible shells upon login. It sets up an environment upon login and loads application-specific ({{ic|/etc/profile.d/*.sh}}) settings.<br />
<br />
====.profile====<br />
This file is read and sourced by bash when an interactive login shell is started.<br />
<br />
====.bashrc====<br />
The file {{ic|~/.bashrc}} is read and sourced by bash when a non-login interactive shell is started, for example, when you open a virtual console from the desktop environment. This file is useful for setting up a user-specific shell environment.<br />
<br />
===Configuration file sourcing order at startup===<br />
These files are sourced by bash in different circumstances. <br />
* if interactive + login shell → {{ic|/etc/profile}} then the first readable of {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash will source {{ic|~/.bash_logout}} upon exit. <br />
* if interactive + non-login shell → {{ic|/etc/bash.bashrc}} then {{ic|~/.bashrc}}<br />
* if login shell + legacy mode → {{ic|/etc/profile}} then {{ic|~/.profile}}<br />
<br />
But, in Arch, by default:<br />
* {{ic|/etc/profile}} (indirectly) sources {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} which users are encouraged to copy to {{ic|~/.bash_profile}}, sources {{ic|~/.bashrc}}<br />
which means that {{ic|/etc/bash.bashrc}} and {{ic|~/.bashrc}} will be executed for all interactive shells, whether they are login shells or not.<br />
<br />
Examples of the user dotfiles can be found in {{ic|/etc/skel/}}.<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===Shell and environment variables===<br />
The behavior of bash and programs run by it can be influenced by a number of environment variable. Environment variables are used to store useful values such as command search directories, or which browser to use. When a new shell or script is launched it inherits its parent's variables, thus starting with an internal set of shell variables[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ].<br />
<br />
These shell variables in bash can be exported in order to become environment variables:<br />
VARIABLE=content<br />
export VARIABLE<br />
or with a shortcut<br />
export VARIABLE=content<br />
<br />
Environment variables are conventionally placed in {{ic|~/.profile}} or {{ic|/etc/profile}} so that all bourne-compatible shells can use them.<br />
<br />
See [[Environment Variables]] for more general information.<br />
<br />
==Command line==<br />
Bash command line is managed by the separate library called [[Readline]]. Readline provides a lot of shortcuts for interacting with the command line i.e. moving back and forth on the word basis, deleting words etc. It is also Readline's responsibility to manage [[Readline#History|history]] of input commands. Last, but not least, it allows you to create [[Readline#Macros|macros]].<br />
<br />
==Aliases==<br />
[[Wikipedia:alias|alias]] is a command, which enables a replacement of a word with another string. It is often used for abbreviating a system command, or for adding default arguments to a regularly used command.<br />
<br />
Personal aliases are preferably stored in {{ic|~/.bashrc}}, and system-wide aliases (which affect all users) belong in {{ic|/etc/bash.bashrc}}.<br />
<br />
An example excerpt from {{ic|~/.bashrc}} covering several time-saving aliases:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with your favorite AUR helper)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==Functions==<br />
Bash also support functions. The following function will extract a wide range of compressed file types. Add the function to {{ic|~/.bashrc}} and use it with the syntax {{Ic|extract <file1> <file2> ...}}<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{note|[[Bash]] users should make sure extglob is enabled: {{Ic|shopt -s extglob}}, for example by adding it to the {{ic|.bashrc}}. It is enabled by default if using [[Bash#Advanced completion|Bash completion]]. [[Zsh]] users should do: {{Ic|setopt kshglob}} instead.}}<br />
Another way to do this is to install the {{AUR|unp}} package from aur which contains a perl script.<br />
<br />
Very often changing to a directory is followed by the 'ls' command to list its contents. Therefore it is helpful to have a second function doing both at once.<br />
In this example we will name it 'cl' and show an error message if the specified directory does not exist.<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
Of course the ls command can be altered to fit your needs, for example 'ls -hall --color=auto'.<br />
<br />
More bash function examples can be found [https://bbs.archlinux.org/viewtopic.php?id=30155 here.]<br />
<br />
==Tips and tricks==<br />
===Prompt customization===<br />
The bash prompt is governed by the variable {{Ic|$PS1}}. To colorize the bash prompt, first comment out the default {{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
Then add the following line:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
This {{Ic|$PS1}} is useful for a root bash prompt, with red designation and green console text. For details on customizing your bash prompt, see [[Color Bash Prompt]].<br />
<br />
===Auto-completion===<br />
It is useful to have the auto-complete feature (pressing {{Keypress|Tab}} key twice on the keyboard) after you type some command like sudo.<br />
<br />
To do this add a line in this format to your {{ic|~/.bashrc}} file:<br />
complete -cf your_command<br />
<br />
For example, to enable auto-complete after sudo and man:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====Advanced completion====<br />
Despite Bash's native support for basic file name, command, and variable auto-completion, there are ways of improving and extending its reach.<br />
<br />
The {{Pkg|bash-completion}} package extends functionality by adding auto-completion to a wide range of commands and their options. Enabling advanced bash completion is quite simple, just install the following package:<br />
# pacman -S bash-completion<br />
Start a new shell and it will be automatically enabled thanks to {{ic|/etc/bash.bashrc}}.<br />
{{Note|If you added any lines similar to "complete -cf sudo" as mentioned in the previous settings and have problems with bash-completion, try removing those lines.}}<br />
<br />
{{Note|1=The normal expansions that you are used to like "$ ls file.*<tab><tab>" will not work unless you "$ compopt -o bashdefault <prog>" for all programs you want to fallback to the normal glob expansions. See https://bbs.archlinux.org/viewtopic.php?id=128471 and https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====Faster completion====<br />
By appending the following into the readline initialization file ({{ic|~/.inputrc}} or {{ic|/etc/inputrc}} by default):<br />
set show-all-if-ambiguous on<br />
it is no longer necessary to hit {{Keypress|Tab}} (default binding) twice to produce a list of all possible completions (both when a partial completion is possible and when no completion is possible), as a single key-press will suffice. Alternatively, to produce such a list only when no completion is possible (i.e., not when a partial completion is possible), append the following command in lieu of the previous one:<br />
set show-all-if-unmodified on<br />
<br />
=== The "command not found" hook ===<br />
The [[pkgfile]] package includes a "command not found" hook that will automatically search the [[official repositories]] when you enter an unrecognized command. Then it will display something like this:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
An alternative "command not found" hook is also provided by the AUR package [https://aur.archlinux.org/packages.php?ID=52305 command-not-found], which will generate an output like the following:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== Disable Ctrl+z in terminal===<br />
You can disable {{Keypress|Ctrl+z}} (pauses/closes your CLI application) feature for you CLI by wrapping your command in this script<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
example:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
With this example script, when you accidentally press {{Keypress|Ctrl+z}} instead of {{Keypress|Shift+z}} or some other key combination while playing Adom(game) your game will not end. Nothing will happen because {{Keypress|Ctrl+z}} will be ignored.<br />
<br />
===Clear the screen after logging out===<br />
To clear the screen after logging out on a virtual terminal, append the following lines to {{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII art, fortunes and cowsay===<br />
Along with colors, system info and ASCII symbols, Bash can be made to display a piece of ASCII art on login. ASCII images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, place the string <br />
cat /path/to/text/file<br />
at the top of {{ic|~/.bashrc}}.<br />
<br />
Random poignant, inspirational, silly or snide phrases can also be shown. To see an example, install the {{Pkg|fortune-mod}} package from the {{Ic|extra}} repository.<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other has gone.}}<br />
<br />
To have a random phrase displayed when logging into a terminal, just set <br />
command fortune<br />
as the top line in {{ic|~/.bashrc}}.<br />
<br />
{{Note|By default, {{Ic|fortune}} displays quotes and phrases that are rather inoccuous. However, the package does contain a set of comments some will find offensive, located in {{ic|/usr/share/fortune/off}}. See the man page for more info on these.}}<br />
<br />
These two features can be combined, using the program {{Pkg|cowsay}}. Modify the line at the top of {{ic|~/.bashrc}} to read <br />
command cowsay $(fortune)<br />
<br />
or<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
The ASCII images are generated by {{ic|.cow}} text files located in {{ic|/usr/share/cows}}, and all themes can be listed with the command {{Ic|cowsay -l}} These files can be edited to the user's liking; custom images can also be created from scratch or found on the net. The easiest way create a custom cow file from an image found online would be to open an existing {{ic|.cow}} file in a text editor, copy-and-paste the image from a browser and save the file as a different name. Test the custom file using<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
This can produce some nice eye candy, and the commands used can be more complex. For a specialized example, take a look [http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ here.] Another example, to use a random cow, random facial expression, and nicely wrap the text of long fortunes.<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{Note|If you want a full colored cowsay-like art, the best option is {{Pkg|ponysay}}, this show full colored ponies (more than 220 at version 1.1) in you terminal (inside X11 or in TTY you have full 256 colored ponies) runing 'ponysay "command or fortune command"', the complete list of ponies are showed usind 'ponysay -l'.<br />
Exist in AUR a tool for creating more ponies (or other stuff) called {{aur|util-say-git}}, and these news archives need to be stored in $HOME/.local/share/ponysay/ponies and $HOME/.local/share/ponysay/ttyponies for desktop and TTY respectibely}}<br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory you will need the {{Pkg|rpmextract}} package installed. Then from your home directory, run the following:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===定制标题===<br />
<br />
变量{{ic|$PROMPT_COMMAND}}允许你在提示符前执行一个命令。比如说,下面的命令会改变标题为整个当前目录名:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
下面的命令会改变你的标题为上一个运行的命令,并且保证你的历史文件总为最新:<br />
export HISTCONTROL=ignoreboth<br />
export HISTIGNORE='history*'<br />
export PROMPT_COMMAND='history -a;echo -en "\e]2;";history 1|sed "s/^[ \t]*[0-9]\{1,\} //g";echo -en "\e\\";<br />
<br />
===Fix line wrap on window resize===<br />
<br />
When you resize your xterm in vi for example, Bash will not get the resize signal, and the text you type will not wrap correctly, overlapping the prompt.<br />
<br />
Use the following in your {{ic|/etc/bash.bashrc}} (from Debian) :<br />
# check the window size after each command and, if necessary,<br />
# update the values of LINES and COLUMNS.<br />
shopt -s checkwinsize<br />
<br />
===Bash history completion===<br />
Bash history completion bound to arrow keys (down, up):<br />
# ~/.bashrc<br />
bind '"\e[A": history-search-backward'<br />
bind '"\e[B": history-search-forward'<br />
or equivalently in {{ic|~/.inputrc}}:<br />
# ~/.inputrc<br />
"\e[A": history-search-backward<br />
"\e[B": history-search-forward<br />
More info at [[Readline#History]] and [https://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html]<br />
<br />
==See also==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]<br />
* [http://wiki.gotux.net/bash:arc Create and Extract Various Archives]<br />
* [http://www.gnu.org/software/bash/manual/html_node/Readline-Init-File-Syntax.html Readline Init File Syntax ]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228868Bash (简体中文)2012-10-15T13:46:48Z<p>Jaurung: /* ASCII Historical Calendar */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII历史日历===<br />
执行下面命令以安装[http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar]文件在你的{{ic|~/.calendar}}目录中:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
这些会随后显示日历项<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228867Bash (简体中文)2012-10-15T13:45:01Z<p>Jaurung: /* ASCII的艺术, fortunes和cowsay */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies,它们分别用在桌面和TTy中。}}<br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228866Bash (简体中文)2012-10-15T13:44:07Z<p>Jaurung: /* ASCII的艺术, fortunes和cowsay */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies分别用在桌面和TTy中。}}<br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228865Bash (简体中文)2012-10-15T13:43:47Z<p>Jaurung: /* ASCII的艺术, fortunes和cowsay */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
{{注意|如果你想要一幅全色彩的类似于cowsay的艺术图,最好的选择就是{{Pkg|ponysay}},通过运行命令'ponysay "command or fortune command"',这个包会在你的终端(在X11或者在TTY中你会获得256全色的ponies)里面显示全色彩的小型马(ponies)图片(版本1.1时超过220种),命令'ponysay -l'显示完整的小型马(ponies)的列表。<br />
存在于AUR的一种工具可以用来创作更多的小型马(ponies)的图片(也可创造其它类型),这个工具叫做{{aur|util-say-git}},而这些新的档案需要存储在$HOME/.local/share/ponysay/ponies和$HOME/.local/share/ponysay/ttyponies分别用在桌面和TTy中。<br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228863Bash (简体中文)2012-10-15T13:28:25Z<p>Jaurung: /* ASCII的艺术, fortunes和cowsay */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ 这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228862Bash (简体中文)2012-10-15T13:27:44Z<p>Jaurung: /* ASCII的艺术, fortunes和cowsay */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
有了色彩,系统信息和ASCII符号,我们就可以让Bash在登录时展示出一幅ASCII的艺术品。ASCII图片可以在网上找到并粘贴到一个text文件中, 或者通过涂鸦产生。images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, 将下面的字符串<br />
cat /path/to/text/file<br />
加入{{ic|~/.bashrc}}的顶部。<br />
<br />
Bash也可以随机显示一些伤感的,激动人心的,可笑的,讽刺的短句。你可以{{Ic|extra}}库中下载安装{{Pkg|fortune-mod}}包来显示一个例子。<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
如果要使短句在登录时随机出现,只需要将下面这句话<br />
command fortune<br />
加入到{{ic|~/.bashrc}}的顶部。<br />
<br />
{{Note|默认情况下,{{Ic|fortune}}显示的引用短语都是无伤大雅的。尽管如此,包里面确实包含了一些无礼的言论,它们放在{{ic|/usr/share/fortune/off}}。你可以查看man手册已得到更多的信息。}}<br />
<br />
这两个功能可以合并在一起,通过这个程序{{Pkg|cowsay}}。改变{{ic|~/.bashrc}}的顶部行来读入下面的命令<br />
command cowsay $(fortune)<br />
<br />
或者<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
ASCII图像通过{{ic|.cow}}txt文件来生成,它位于{{ic|/usr/share/cows}}中,并且所有的主题可以都可以通过这个命令{{Ic|cowsay -l}}来列出。这些文件可以依照用户的喜好进行编辑;自定义的图片可以通过涂鸦和在网上寻找的方式获得。创作一个自定义cow文件的最简方法就是在文本编辑器打开一个存在的{{ic|.cow}}文件,再将浏览器中的ASCII图片复制粘贴到编辑器中,另取名保存即可。你可以用下面的命令测试自定义文件<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
这个能产生一幅华丽的图画,命令的使用也更加复杂。如果需要更加专业的例子,访问[http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/这里。] 另外一个例子,这个例子使用了随机产生的cow,随机的脸部表情,并且把fortunes产生文字和图片漂亮的包装在一起。<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurunghttps://wiki.archlinux.org/index.php?title=Bash_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)&diff=228848Bash (简体中文)2012-10-15T12:51:47Z<p>Jaurung: /* ASCII art, fortunes and cowsay */</p>
<hr />
<div>[[Category:简体中文]]<br />
[[Category:Command shells (简体中文)]]<br />
[[en:Bash]]<br />
[[es:Bashrc]]<br />
[[it:Bash]]<br />
[[nl:Bashrc]]<br />
{{Translateme (简体中文)}}<br />
<br />
'''Bash''' (Bourne-again Shell) 是一个[[Command shell|外壳]]/编程语言,来自 [[GNU Project]]。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。 <br />
<br />
==调用==<br />
Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。<br />
===登录外壳===<br />
如果Bash由在tty中的{{ic|登录}}, [[SSH]] 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项{{Ic|-l}} 或者 {{Ic|--login}} 来使用这个种模式。<br />
<br />
===交互式外壳===<br />
如果Bash在启动的时候既没有使用 {{Ic|-c}} 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。<br />
<br />
===符合 POSIX===<br />
通过在Bash启动时使用 {{Ic|--posix}} 命令行参数或者在启动后执行 ‘{{Ic|set -o posix}}’ 来使Bash在增强的POSIX标准下运行。<br />
<br />
===传统模式===<br />
在Arch下 {{ic|/bin/sh}} (过去是Bourne shell)被符号链接至{{ic|/bin/bash}}.<br />
<br />
如果以命令名{{Ic|sh}}来调用Bash, Bash会尽可能地模仿历史版本的{{Ic|sh}}的启动过程。<br />
<br />
==配置==<br />
{{poor writing}}<br />
===配置文件概览===<br />
* {{ic|/etc/profile}}<br />
* {{ic|~/.bash_profile}}<br />
* {{ic|~/.bash_login}}<br />
* {{ic|~/.profile}}<br />
* {{ic|/etc/bash.bashrc}} (''非标准'': 只对部分发行版有效,Arch包含在这部分中)<br />
* {{ic|~/.bashrc}}<br />
* {{ic|~/.bash_logout}}<br />
对经常使用的配置文件的概述:<br />
====/etc/profile====<br />
{{ic|/etc/profile}}被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定({{ic|/etc/profile.d/*.sh}})的设置。<br />
<br />
====.profile====<br />
此文件在启动一个交互式的登录shell时被Bash所读入和引用。<br />
<br />
====.bashrc====<br />
此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。<br />
<br />
===配置文件在启动时的引用顺序===<br />
这些文件在不同的情形下被Bash所引用。<br />
* 如果交互式+登录shell → {{ic|/etc/profile}} 然后按以下顺序读取 {{ic|~/.bash_profile}}, {{ic|~/.bash_login}}, and {{ic|~/.profile}}<br />
**Bash会在退出时引用{ic|~/.bash_logout}}。<br />
* 如果交互式+非登录shell → {{ic|/etc/bash.bashrc}} 然后 {{ic|~/.bashrc}}<br />
* 如果交互式+传统模式 → {{ic|/etc/profile}} 然后 {{ic|~/.profile}}<br />
<br />
但是,在Arch下,默认的:<br />
* {{ic|/etc/profile}} (间接地) 引用 {{ic|/etc/bash.bashrc}}<br />
* {{ic|/etc/skel/.bash_profile}} Arch鼓励用户将{{ic|/etc/skel/.bash_profile}}复制到 {{ic|~/.bash_profile}}, 并引用 {{ic|~/.bashrc}}<br />
这意味着 {{ic|/etc/bash.bashrc}} 和 {{ic|~/.bashrc}} 将会为所有的交互式shell所执行, 不管它是不是登录shell.<br />
<br />
用户dotfiles的例子可以在{{ic|/etc/skel/}}中被找到。<br />
<br />
{{Note|legacy mode is when invoked with the name {{Ic|sh}}}}<br />
<br />
===外壳和环境变量===<br />
Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[http://www.kingcomputerservices.com/unix_101/understanding_unix_shells_and_environment_variables.htm ]。<br />
<br />
这些Bash中的shell变量可以被导出以变成环境变量:<br />
VARIABLE=content<br />
export VARIABLE<br />
或者快捷地:<br />
export VARIABLE=content<br />
<br />
环境变量依照惯例放置在{{ic|~/.profile}}或者{{ic|/etc/profile}},这样所有兼容Bourne shell的shell都可以使用。<br />
<br />
参阅[[Environment Variables]]以获得更加全面的信息。<br />
<br />
==命令行==<br />
Bash的命令行由一个叫做[[Readline]]的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入[[Readline#History|历史]]也是Readline的职责。最后一点也非常重要, 它允许你创造[[Readline#Macros|宏]]。<br />
<br />
==别名==<br />
[[Wikipedia:alias|alias]]是一个命令, 它让用其它字符串替代一句话成为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。<br />
<br />
用户个人的别名(alias)最好保存在{{ic|~/.bashrc}}, 而系统级的别名(这些别名会影响所有用户)存放在{{ic|/etc/bash.bashrc}}。<br />
<br />
摘录于{{ic|~/.bashrc}}的一个例子涵盖了为节约时间而写的别名:<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
# modified commands<br />
alias diff='colordiff' # requires colordiff package<br />
alias grep='grep --color=auto'<br />
alias more='less'<br />
alias df='df -h'<br />
alias du='du -c -h'<br />
alias mkdir='mkdir -p -v'<br />
alias nano='nano -w'<br />
alias ping='ping -c 5'<br />
alias ..='cd ..'<br />
<br />
# new commands<br />
alias da='date "+%A, %B %d, %Y [%T]"'<br />
alias du1='du --max-depth=1'<br />
alias hist='history | grep $1' # requires an argument<br />
alias openports='netstat --all --numeric --programs --inet --inet6'<br />
alias pg='ps -Af | grep $1' # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)<br />
<br />
# privileged access<br />
if [ $UID -ne 0 ]; then<br />
alias sudo='sudo '<br />
alias scat='sudo cat'<br />
alias svim='sudo vim'<br />
alias root='sudo su'<br />
alias reboot='sudo reboot'<br />
alias halt='sudo halt'<br />
alias update='sudo pacman -Su'<br />
alias netcfg='sudo netcfg2'<br />
fi<br />
<br />
# ls<br />
alias ls='ls -hF --color=auto'<br />
alias lr='ls -R' # recursive ls<br />
alias ll='ls -l'<br />
alias la='ll -A'<br />
alias lx='ll -BX' # sort by extension<br />
alias lz='ll -rS' # sort by size<br />
alias lt='ll -rt' # sort by date<br />
alias lm='la | more'<br />
<br />
# safety features<br />
alias cp='cp -i'<br />
alias mv='mv -i'<br />
alias rm='rm -I' # 'rm -i' prompts for every file<br />
alias ln='ln -i'<br />
alias chown='chown --preserve-root'<br />
alias chmod='chmod --preserve-root'<br />
alias chgrp='chgrp --preserve-root'<br />
<br />
# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)<br />
alias pac="pacman -S" # default action - install one or more packages<br />
alias pacu="pacman -Syu" # '[u]pdate' - upgrade all packages to their newest version<br />
alias pacs="pacman -Ss" # '[s]earch' - search for a package using one or more keywords<br />
alias paci="pacman -Si" # '[i]nfo' - show information about a package<br />
alias pacr="pacman -R" # '[r]emove' - uninstall one or more packages<br />
alias pacl="pacman -Sl" # '[l]ist' - list all packages of a repository<br />
alias pacll="pacman -Qqm" # '[l]ist [l]ocal' - list all packages which were locally installed (e.g. AUR packages)<br />
alias paclo="pacman -Qdt" # '[l]ist [o]rphans' - list all packages which are orphaned<br />
alias paco="pacman -Qo" # '[o]wner' - determine which package owns a given file<br />
alias pacf="pacman -Ql" # '[f]iles' - list all files installed by a given package<br />
alias pacc="pacman -Sc" # '[c]lean cache' - delete all not currently installed package files<br />
alias pacm="makepkg -fci" # '[m]ake' - make package from PKGBUILD file in current directory<br />
</nowiki>}}<br />
<br />
==函数==<br />
Bash也支持函数。下面这个函数可以解压多种类型的压缩文件。将下面这个函数加入{{ic|~/.bashrc}}中并以这个语法{{Ic|extract <file1> <file2> ...}}使用它。<br />
<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
extract() {<br />
local c e i<br />
<br />
(($#)) || return<br />
<br />
for i; do<br />
c=''<br />
e=1<br />
<br />
if [[ ! -r $i ]]; then<br />
echo "$0: file is unreadable: \`$i'" >&2<br />
continue<br />
fi<br />
<br />
case $i in<br />
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))<br />
c='bsdtar xvf';;<br />
*.7z) c='7z x';;<br />
*.Z) c='uncompress';;<br />
*.bz2) c='bunzip2';;<br />
*.exe) c='cabextract';;<br />
*.gz) c='gunzip';;<br />
*.rar) c='unrar x';;<br />
*.xz) c='unxz';;<br />
*.zip) c='unzip';;<br />
*) echo "$0: unrecognized file extension: \`$i'" >&2<br />
continue;;<br />
esac<br />
<br />
command $c "$i"<br />
e=$?З<br />
done<br />
<br />
return $e<br />
}<br />
</nowiki>}}<br />
<br />
{{注意|[[Bash]]用户应该确保extglob功能被打开: {{Ic|shopt -s extglob}}, 比如说将它加入到{{ic|.bashrc}}。如果使用[[Bash#Advanced completion|Bash completion]],这个功能将默认被打开。 [[Zsh]]用户应该这样做: 执行{{Ic|setopt kshglob}}来替代上面的操作。}}<br />
<br />
另一个实现方式就是安装''unp''包。<br />
<br />
通常改变到另一个目录后我们会用ls来列出目录下的文件。所以我们可以写一个函数来同时做这两件事情。<br />
这个例子中我们把函数命名为'cl'并且会在给定的目录不存在时报错。<br />
{{hc|~/.bashrc<br />
|2=<nowiki><br />
cl()<br />
{<br />
if [ -d $1 ]; then<br />
cd $1<br />
ls<br />
else<br />
echo "bash: cl: $1: Directory not found"<br />
fi<br />
}<br />
</nowiki>}}<br />
当然ls命令可以被改变以适应你的需求, 比如'ls -hall --color=auto'。<br />
<br />
更多bash函数的例子在[https://bbs.archlinux.org/viewtopic.php?id=30155 这里。]<br />
<br />
==提示与技巧==<br />
===自定义提示符===<br />
Bash提示符由变量{{Ic|$PS1}}控制。为了让提示符色彩丰富些, 首先要注释掉默认的{{Ic|$PS1}}:<br />
#PS1='[\u@\h \W]\$ '<br />
然后加入下面这句:<br />
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '<br />
{{Ic|$PS1}}将shell改变成红色的名称和绿色的控制台文本,这对一个root权限的bash提示符十分有用。欲了解更多关于自定义shell的内容, 参阅[[Color Bash Prompt]]。<br />
<br />
===自动命令补全===<br />
当你键入一些命令比如sudo时,自动补全功能(在键盘上按{{Keypress|Tab}}两次)显得尤其有用。<br />
<br />
你可以加入以下内容到{{ic|~/.bashrc}}文件中以实现补全功能:<br />
complete -cf your_command<br />
<br />
比如说,为了激活sudo和man之后的自动补全功能,可以这样:<br />
complete -cf sudo<br />
complete -cf man<br />
<br />
====高级的补全方法====<br />
尽管Bash原生支持基本的文件名,命令和变量的自动补全, 我们仍然可以通过一些方法扩充它的功能。<br />
<br />
包{{Pkg|bash-completion}}通过将自动补全扩充到一个更加广泛的的命令和他们的选项中去使自动补全在shell中的表现更加强大。激活高级补全的方法也非常简单,只需要安装这个包就可以:<br />
# pacman -S bash-completion<br />
启动一个新的shell,然后它由于配置文件{{ic|/etc/bash.bashrc}}的作用就会自动激活补全了。<br />
{{注意|如果你加入了类似于上文提到的"complete -cf sudo"的设置,并且在Bash自动补全中出现问题,尝试删除那些设置语句。}}<br />
<br />
{{注意|1=通常你使用过去的这些命令操作"$ ls file.*<tab><tab>"来补全命令语句,但这可能不会正常的工作,除非你为想要退回到正常全局补全的程序执行下面的命令"$ compopt -o bashdefault <prog>"。参见 https://bbs.archlinux.org/viewtopic.php?id=128471 和 https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion-Builtins.html}}<br />
<br />
====更快的补全操作====<br />
通过加入下面这句话到readline默认的初始化文件({{ic|~/.inputrc}}或者{{ic|/etc/inputrc}}中):<br />
set show-all-if-ambiguous on<br />
之后没有必要敲击{{Keypress|Tab}}(默认绑定)两次来产生可能的补全列表(包括有多种补全可能或者没有补全可能时), 因为一次敲击就可以实现。 作为另外一种选择, 产生补全列表只有在没有可能的补全下(比如, 没有多种补全可能时), 将上面的设置语句替换成下面这条:<br />
set show-all-if-unmodified on<br />
<br />
===命令未找到时的钩子拓展(HOOKS)===<br />
包[[pkgfile]]包括一个叫做"command not found"的钩子拓展,这个钩子拓展将在你键入未识别命令时自动搜索[[官方版本库]]。然后显示下面的信息:<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<nowiki><br />
abiword may be found in the following packages:<br />
extra/abiword 2.8.6-7 usr/bin/abiword<br />
</nowiki><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
AUR包提供了另外一个"command not found"钩子拓展。[https://aur.archlinux.org/packages.php?ID=52305 command-not-found], 它会产生像这样的输出:<br />
<br />
<div style="font-family: monospace; white-space: pre; overflow: auto; margin: 1em 3em; padding: 1em; border: 3px solid #bcd; background-color: black; color: #aaa;"><span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> abiword<br />
The command 'abiword' is been provided by the following packages:<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from extra<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from staging<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="font-weight: bold">abiword</span> (2.8.6-7) from testing<nowiki><br />
</nowiki>[ <span style="color: #bb0000">abiword</span> ]<br />
<span style="color: #0a0">chiri</span> <span style="color: #00f">~/docs</span> <span style="color: #0f0">$</span> <span style="text-decoration: blink;">_</span></div><br />
<br />
=== 终端中禁用 Ctrl+z ===<br />
你可以为你的命令行界面关闭{{Keypress|Ctrl+z}} (暂停/关闭你的命令行界面程序)的功能通过在这个脚本中包装命令<br />
#!/bin/bash<br />
trap "" 20<br />
/path_to_your_application/<br />
例子:<br />
#!/bin/bash<br />
trap "" 20<br />
/usr/bin/adom<br />
<br />
有了这个例子脚本,当你在玩Adom(游戏)要按{{Keypress|Shift+z}}组合键时不小心按下了{{Keypress|Ctrl+z}}组合键,你的游戏就不会停止运行了。其实什么都会发生因为我们已经禁用了{{Keypress|Ctrl+z}}。<br />
<br />
===登出后清空屏幕===<br />
当登出虚拟终端时,为了实现清屏操作,可以加入下面的语句到{{ic|~/.bash_logout}}:<br />
clear<br />
reset<br />
<br />
===ASCII的艺术, fortunes和cowsay===<br />
Along with a colors, system info and ASCII symbols, Bash can be made to display a piece of ASCII art on login. ASCII images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, place the string <br />
cat /path/to/text/file<br />
at the top of {{ic|~/.bashrc}}.<br />
<br />
Random poignant, inspirational, silly or snide phrases can also be shown. To see an example, install the {{Pkg|fortune-mod}} package from the {{Ic|extra}} repository.<br />
<br />
{{bc|1=<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''<br />
--(</font><font color=green>~</font><font color=red>)---> </font> fortune<br />
<br/><br />
It is Texas law that when two trains meet each other at a railroad crossing,<br />
each shall come to a full stop, and neither shall proceed until the other<br />
<br />
has gone.}}<br />
<br />
To have a random phrase displayed when logging into a terminal, just set <br />
command fortune<br />
as the top line in {{ic|~/.bashrc}}.<br />
<br />
{{Note|By default, {{Ic|fortune}} displays quotes and phrases that are rather inoccuous. However, the package does contain a set of comments some will find offensive, located in {{ic|/usr/share/fortune/off}}. See the man page for more info on these.}}<br />
<br />
These two features can be combined, using the program {{Pkg|cowsay}}. Modify the line at the top of {{ic|~/.bashrc}} to read <br />
command cowsay $(fortune)<br />
<br />
or<br />
command cowthink $(fortune)<br />
<br />
<br />
The earth is like a tiny grain of sand, <br />
only much, much heavier. <br />
----------------------------------------- <br />
\ ^__^<br />
\ (oo)\_______<br />
(__)\ )\/\<br />
||----w |<br />
|| ||<br />
<br />
The ASCII images are generated by {{ic|.cow}} text files located in {{ic|/usr/share/cows}}, and all themes can be listed with the command {{Ic|cowsay -l}} These files can be edited to the user's liking; custom images can also be created from scratch or found on the net. The easiest way create a custom cow file from an image found online would be to open an existing {{ic|.cow}} file in a text editor, copy-and-paste the image from a browser and save the file as a different name. Test the custom file using<br />
<br />
# cowsay -f {{ic|cowfile}} $(fortune)<br />
<br />
This can produce some nice eye candy, and the commands used can be more complex. For a specialized example, take a look [http://bambambambam.wordpress.com/2009/07/04/futurama-ascii-with-slashdot-header-quotes-in-your-terminal/ here.] Another example, to use a random cow, random facial expression, and nicely wrap the text of long fortunes.<br />
<br />
fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n<br />
<br />
________________________________________ <br />
( Fry: I must be a robot. Why else would )<br />
( human women refuse to date me? )<br />
---------------------------------------- <br />
o<br />
o<br />
o <br />
,'``.._ ,'``.<br />
:,--._:)\,:,._,.:<br />
:`--,''@@@:`...';\ <br />
`,'@@@@@@@`---'@@`. <br />
/@@@@@@@@@@@@@@@@@:<br />
/@@@@@@@@@@@@@@@@@@@\<br />
,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.<br />
`...,---'``````-..._@@@@|:@@@@@@@\<br />
( )@@@;:@@@@)@@@\ _,-.<br />
`. (@@@//@@@@@@@@@@`'@@@@\<br />
: `.//@@)@@@@@@)@@@@@,@;<br />
|`. _,'/@@@@@@@)@@@@)@,'@,'<br />
:`.`-..____..=:.-':@@@@@.@@@@@_,@@,'<br />
,'\ ``--....-)=' `._,@@\ )@@@'``._<br />
/@_@`. (@) /@@@@@) ; / \ \`-.'<br />
(@@@`-:`. `' ___..'@@_,-' |/ `.)<br />
`-. `.`.``-----``--,@@.'<br />
|/`.\`' ,',');<br />
` (/ (/<br />
'''<font color=red>(</font><font color=green>user@host</font><font color=red>)-(</font><font color=green>10:10 AM Wed Dec 22</font><font color=red>)'''--(</font><font color=green>~</font>)<font color=red>)---></font><br />
<br />
===ASCII Historical Calendar===<br />
To install [http://www.openbsd.org/cgi-bin/man.cgi?query=calendar&sektion=1 calendar] files in your {{ic|~/.calendar}} directory:<br />
$ mkdir -p ~/.calendar<br />
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm<br />
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*<br />
<br />
This will then print out the calendar items<br />
$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);<br />
<br />
===Customise Title===<br />
<br />
The {{ic|$PROMPT_COMMAND}} variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:<br />
<br />
export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'<br />
<br />
==资源==<br />
* [http://tldp.org/LDP/abs/html/ Advanced Bash Scripting Guide] - Very good resource regarding shell scripting using bash<br />
* [http://www.gnu.org/software/bash/manual/bashref.html Bash Reference Manual] - Official reference (654K)<br />
* [http://wiki.bash-hackers.org/doku.php Bash Hackers Wiki] - Excellent Bash Wiki<br />
* [http://bashscripts.org Bashscripts.org] - Forum for bash coders.<br />
* [http://www.ibm.com/developerworks/linux/library/l-bash.html Bash Scripting by Example]<br />
* [http://www.caliban.org/bash Completion Guide]<br />
* [http://wooledge.org/mywiki/BashFaq Greg's Wiki] - Highly recommended<br />
* [http://www.gnu.org/software/bash/manual/bash.html man page]<br />
* [http://www.grymoire.com/Unix/Quote.html Quote Tutorial]<br />
* irc://irc.freenode.net#bash - Active and friendly Internet Relay Chat channel for Bash.<br />
* http://chakra-project.org/wiki/index.php/Startup_files<br />
* [http://www.aosabook.org/en/bash.html The Bourne-Again Shell] - The third chapter of ''The Architecture of Open Source Applications''<br />
* [http://tldp.org/HOWTO/Xterm-Title-4.html How to change the title of an xterm]</div>Jaurung