https://wiki.archlinux.org/api.php?action=feedcontributions&user=Kargs&feedformat=atomArchWiki - User contributions [en]2024-03-29T05:04:19ZUser contributionsMediaWiki 1.41.0https://wiki.archlinux.org/index.php?title=GnuPG&diff=339289GnuPG2014-10-08T07:15:45Z<p>Kargs: /* Rotating subkeys */ typo</p>
<hr />
<div>[[ru:GnuPG]]<br />
[[Category:Security]]<br />
[http://www.gnupg.org GnuPG] allows to encrypt and sign your data and communication, features a versatile key management system as well as access modules for all kinds of public key directories.<br />
<br />
== Installation ==<br />
<br />
[[Install]] {{Pkg|gnupg}}, available in the [[official repositories]].<br />
<br />
This will also install {{Pkg|pinentry}}, a collection of simple PIN or passphrase entry dialogs which GnuPG uses for passphrase entry. ''pinentry'' is determined by the symbolic link {{ic|/usr/bin/pinentry}}, which by default points to {{ic|/usr/bin/pinentry-gtk-2}}.<br />
<br />
== Environment Variables ==<br />
<br />
=== GNUPGHOME ===<br />
<br />
{{ic|$GNUPGHOME}} is used by {{ic|GnuPGP}} to point to the directory where all configuration files are stored. By default {{ic|$GNUPGHOME}} isn't set and your {{ic|$HOME}} is used instead, thus you will find a {{ic|~/.gnupg}} directory right after the install. You may change this default setting by putting this line in one of your regular [[startup files]]<br />
export GNUPGHOME&#61;"/path/to/gnupg/directory"<br />
<br />
{{Note| By default, the gnupg directory has its [[Permissions]] set to ''700'' and the files it contains have their permissions set to ''600''. Only the owner of the directory has permission to read, write and execute (''r'',''w'',''x''). This is for security purposes and should not be changed. In case this directory or any file inside it does not follow this security measure, you will get warnings about unsafe file and home directory permissions.}}<br />
<br />
=== GPG_AGENT_INFO ===<br />
<br />
{{ic|GPG_AGENT_INFO}} used to locate the pgp-agent. Consists of 3 colon delimited fields:<br />
<br />
# path to Unix Domain Socket<br />
# PID of gpg-agent<br />
# protocol version set to 1<br />
<br />
E.g : {{ic|GPG_AGENT_INFO&#61;/tmp/gpg-eFqmSC/S.gpg-agent:7795:1}}. When starting the gpg-agent, this variable is set to the correct value.<br />
<br />
== Configuration file ==<br />
<br />
Default is {{ic|~/.gnupg/gpg.conf}}. If you want to change the default location, either run gpg this way {{ic|$ gpg --homedir ''path/to/file''}} or use {{ic|$GNUPGHOME}} variable.<br />
<br />
Append in this file any long options you want. Do not write the two dashes, but simply the name of the option and required arguments. You will find a skeleton file {{ic|usr/share/gnupg/gpg-conf.skel}}.<br />
Following is a basic configuration file:<br />
{{hc|~/.gnupg/gpg.conf|<br />
default-key ''name'' # useful in case you manage several keys and want to set a default one<br />
keyring ''file'' # will add ''file'' to the current list of keyrings<br />
trustdb-name ''file'' # use ''file'' instead of the default trustdb<br />
homedir ''dir'' # set the name of the gnupg home dir to ''dir'' instead of ~/.gnupg<br />
display-charset utf-8 # bypass all translation and assume that the OS uses native UTF-8 encoding<br />
keyserver ''name'' # use ''name'' as your keyserver<br />
no-greeting # suppress the initial copyright message<br />
armor # create ASCII armored output. Default is binary OpenPGP format<br />
}}<br />
<br />
If you want to set up default options for a multi-user system, the configuration file of defaults is expected in {{ic|/etc/skel/.gnupg/}}. With that in place the new user configuration can be created with<br />
# addgnupghome user1 user2<br />
which will add the respective {{ic|/home/userX/.gnupg/}} and copy the files from the skeleton directory to it.<br />
<br />
== Basic keys management ==<br />
<br />
{{Note|Whenever a ''{{ic|<user-id>}}'' is required in a command, it can be specified with your key ID, fingerprint, a part of your name or email address, etc. GnuPG is flexible on this.}}<br />
<br />
=== Create key ===<br />
<br />
* Set stronger algorithms to be used first:<br />
<br />
{{hc|~/.gnupg/gpg.conf|<br />
personal-digest-preferences SHA512<br />
cert-digest-algo SHA512<br />
default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES CAST5 ZLIB BZIP2 ZIP Uncompressed<br />
personal-cipher-preferences TWOFISH CAMELLIA256 AES 3DES<br />
}}<br />
<br />
* Generate a private key by typing in a terminal:<br />
<br />
$ gpg --gen-key<br />
<br />
You will be asked several questions. In general, most users will want both a RSA (sign only) and a RSA (encrypt only) key. It is advised to use a keysize of 4096 bits (default is 2048).<br />
<br />
While having an expiration date for subkeys isn't technically necessary, it is considered good practice. A period of a year is generally good enough for the average user. This way even if you lose access to your keyring, it will allow others to know that it is no longer valid. Note that you can extend the expiry date after key creation without having to re-issue a new key.<br />
<br />
=== Manage your key ===<br />
<br />
* Running the {{ic|gpg --edit-key ''<user-id>''}} command will present a menu which enables you to do most of your key management related tasks. Following is an example to set your expiration date:<br />
<br />
$ gpg --edit-key ''<user-id>''<br />
> key ''number''<br />
> expire ''yyyy-mm-dd''<br />
> save<br />
> quit<br />
<br />
Some useful commands:<br />
> passwd # change the passphrase<br />
> clean # compact any user ID that is no longer usable (e.g revoked or expired)<br />
> revkey # revoke a key<br />
> addkey # add a subkey to this key<br />
> expire # change the key expiration time<br />
<br />
* Generate an ASCII version of your public key (e.g. to distribute it by e-mail):<br />
<br />
$ gpg --armor --output public.key --export ''<user-id>''<br />
<br />
* Register your key with a public PGP key server, so that others can retrieve your key without having to contact you directly:<br />
<br />
$ gpg --keyserver pgp.mit.edu --send-keys ''<user-id>''<br />
<br />
* Sign and encrypt for user Bob<br />
<br />
$ gpg -se -r Bob ''file''<br />
<br />
* make a clear text signature<br />
<br />
$ gpg --clearsign ''file''<br />
<br />
=== Rotating subkeys ===<br />
<br />
{{Warning|'''Never''' delete your expired or revoked subkeys unless you have a good reason. Doing so will cause you to lose the ability to decrypt files encrypted with the old subkey. Please '''only''' delete expired or revoked keys from other users to clean your keyring.}}<br />
<br />
If you have set your subkeys to expire after a set time, you can create new ones. Do this a few weeks in advance to allow others to update their keyring.<br />
<br />
{{Note|You do not need to create a new key simply because it is expired. You can extend the expiration date.}}<br />
<br />
* Create new subkey (repeat for both signing and encrypting key)<br />
<br />
$ gpg --edit-key ''<user-id>''<br />
> addkey<br />
<br />
And answer the following questions it asks (see previous section for suggested settings).<br />
<br />
* Save changes<br />
<br />
> save<br />
<br />
* Update it to a keyserver.<br />
<br />
$ gpg --keyserver pgp.mit.edu --send-keys ''<user-id>''<br />
<br />
{{Note|Revoking expired subkeys is unnecessary and arguably bad form. If you are constantly revoking keys, it may cause others to lack confidence in you.}}<br />
<br />
=== Import key ===<br />
<br />
* Import a public key to your public key ring:<br />
<br />
$ gpg --import public.key<br />
<br />
* Import a private key to your secret key ring:<br />
<br />
$ gpg --import private.key<br />
<br />
=== List keys ===<br />
<br />
* Keys in your public key ring:<br />
<br />
$ gpg --list-keys<br />
<br />
* Keys in your secret key ring:<br />
<br />
$ gpg --list-secret-keys<br />
<br />
== Encrypt and decrypt ==<br />
<br />
When encrypting or decrypting it is possible to have more than one private key in use. If this occurs you need to select the active key. This can be done by using the option {{ic|-u UID}} or by using the option {{ic|--local-user UID}}. This causes the default key to use to be replaced by wanted key.<br />
<br />
To encrypt a file, use:<br />
<br />
$ gpg --encrypt -o secret.tar.gpg secret.tar<br />
<br />
* If you want to change recipient this can be done by the option {{ic|-r}} or by the option {{ic|--recipient}}.<br />
* You can use gnupg to encrypt your sensitive documents, but only individual files at a time. If you want to encrypt directories or a whole file-system you should consider using [[TrueCrypt]] or [[EncFS]], though you can always tarball various files and then encrypt them.<br />
<br />
To decrypt a file, use:<br />
<br />
$ gpg --decrypt secret.tar.gpg<br />
<br />
You'll be prompted to enter your passphrase.<br />
<br />
=== Encrypt a password ===<br />
<br />
It can be useful to encrypt some password, so it will not be written in clear on a configuration file. A good example is your email password.<br />
<br />
First create a file with your password. You '''need''' to leave '''one''' empty line after the password, otherwise gpg will return an error message when evaluating the file.<br />
<br />
Then run:<br />
<br />
$ gpg -e -a -r ''your_GPG_key_ID'' ''your_password_file''<br />
<br />
{{ic|-e}} is for encrypt, {{ic|-a}} for armor (ASCII output), {{ic|-r}} for recipient USER-ID.<br />
<br />
You will be left with a new {{ic|''your_password_file''.asc}} file.<br />
<br />
== gpg-agent ==<br />
<br />
{{Ic|Gpg-agent}} is mostly used as daemon to request and cache the password for the keychain. This is useful if GnuPG is used from an external program like a mail client. It can be activated by adding following line in {{ic|~/.gnupg/gpg.conf}}:<br />
use-agent<br />
<br />
This tells GnuPG to use the agent whenever it needs the password. However, the agent needs to run already. To autostart it, create the following file and make it executable, and remember to change the envfile path if you changed your $GNUPGHOME:<br />
<br />
{{hc|/etc/profile.d/gpg-agent.sh|2=<nowiki><br />
if [ $EUID -ne 0 ] ; then<br />
envfile="$HOME/.gnupg/gpg-agent.env"<br />
if [[ -e "$envfile" ]] && kill -0 $(grep GPG_AGENT_INFO "$envfile" | cut -d: -f 2) 2>/dev/null; then<br />
eval "$(cat "$envfile")"<br />
else<br />
eval "$(gpg-agent --daemon --enable-ssh-support --write-env-file "$envfile")"<br />
fi<br />
export GPG_AGENT_INFO # the env file does not contain the export statement<br />
export SSH_AUTH_SOCK # enable gpg-agent for ssh<br />
fi<br />
</nowiki>}}<br />
<br />
If you don't want gpg-agent to autostart for all users or just want to keep user daemons in the users own configuration files you can add the following entry to your {{Ic|.xinitrc}} or {{Ic|.bash_profile}}.<br />
<br />
eval $(gpg-agent --daemon)<br />
<br />
Log out of your Xsession and log back in. Check if {{Ic|gpg-agent}} is activated<br />
<br />
$ pgrep gpg-agent<br />
<br />
==== Configuration ====<br />
<br />
gpg-agent can be configured via {{ic|~/.gnupg/gpg-agent.conf}} file. The configuration options are listed in {{ic|man gpg-agent}}. For example you can change cache ttl for unused keys:<br />
<br />
{{hc|~/.gnupg/gpg-agent.conf|<br />
default-cache-ttl 3600<br />
}}<br />
<br />
==== Pinentry ====<br />
<br />
Finally, the agent needs to know how to ask the user for the password. This can be set in the gpg-agent configuration file.<br />
<br />
The default uses a gtk dialog. There are other options - see {{ic|info pinentry}}. To change the dialog implementation set {{ic|pinentry-program}} configuration option:<br />
{{hc|~/.gnupg/gpg-agent.conf|<br />
<br />
# PIN entry program<br />
# pinentry-program /usr/bin/pinentry-curses<br />
# pinentry-program /usr/bin/pinentry-qt4<br />
# pinentry-program /usr/bin/pinentry-kwallet<br />
<br />
pinentry-program /usr/bin/pinentry-gtk-2<br />
}}<br />
<br />
{{Tip|For using {{ic|/usr/bin/pinentry-kwallet}} you have to install the {{Pkg|kwalletcli}} package.}}<br />
<br />
== Keysigning Parties ==<br />
<br />
To allow users to validate keys on the keyservers and in their keyrings (i.e. make sure they are from whom they claim to be), PGP/GPG uses a so-called "Web of Trust". To build this Web of Trust, many hacker events include keysigning parties.<br />
<br />
The [https://en.wikipedia.org/wiki/Zimmermann%E2%80%93Sassaman_key-signing_protocol Zimmermann-Sassaman] key-signing protocol is a way of making these very effective. [http://www.cryptnet.net/fdp/crypto/keysigning_party/en/keysigning_party.html Here] you'll find a How-To-article.<br />
<br />
=== Caff ===<br />
<br />
For an easier process of signing keys and sending signatures to the owners after a keysigning party, you can use the tool 'caff'. It can be installed from the AUR with the package {{AUR|caff-svn}} or bundled together with other useful tools in the package {{AUR|signing-party-svn}}.<br />
Either way, there will be a lot of dependencies installing from the AUR. Alternatively you can install them with<br />
cpanm Any::Moose<br />
cpanm GnuPG::Interface<br />
<br />
To send the signatures to their owners you need a working [https://en.wikipedia.org/wiki/Message_transfer_agent MTA]. If you don't have already one, install [[msmtp]].<br />
<br />
== Smartcards ==<br />
<br />
{{Note|{{Pkg|pcsclite}} and {{Pkg|libusb-compat}} have to be installed, and the contained [[systemd#Using units|systemd]] service {{ic|pcscd.service}} has to be running.}}<br />
<br />
GnuPG uses ''scdaemon'' as an interface to your smartcard reader, please refer to the [[man page]] for details.<br />
<br />
=== GnuPG only setups ===<br />
<br />
If you do not plan to use other cards but those based on GnuPG, you should check the {{Ic|reader-port}} parameter in {{ic|~/.gnupg/scdaemon.conf}}. The value '0' refers to the first available serial port reader and a value of '32768' (default) refers to the first USB reader.<br />
<br />
=== GnuPG together with OpenSC ===<br />
<br />
If you are using any smartcard with an opensc driver (e.g.: ID cards from some countries) you should pay some attention to GnuPG configuration. Out of the box you might receive a message like this when using {{Ic|gpg --card-status}}<br />
<br />
gpg: selecting openpgp failed: ec=6.108<br />
<br />
By default, scdaemon will try to connect directly to the device. This connection will fail if the reader is being used by another process. For example: the pcscd daemon used by OpenSC. To cope with this situation we should use the same underlying driver as opensc so they can work well together. In order to point scdaemon to use pcscd you should remove {{Ic|reader-port}} from {{ic|~/gnupg/scdaemon.conf}}, specify the location to {{ic|libpcsclite.so}} library and disable ccid so we make sure that we use pcscd:<br />
<br />
{{hc|~/scdaemon.conf|<nowiki><br />
pcsc-driver /usr/lib/libpcsclite.so<br />
card-timeout 5<br />
disable-ccid<br />
</nowiki>}}<br />
<br />
Please check {{Ic|man scdaemon}} if you do not use OpenSC.<br />
<br />
== Troubleshooting ==<br />
<br />
=== Su ===<br />
<br />
When using {{Ic|pinentry}}, you must have the proper permisions of the terminal device (e.g. {{Ic|/dev/tty1}}) in use. However, with {{Ic|su}} (or {{Ic|sudo}}), the ownership stays with the original user, not the new one. This means that pinentry will fail, even as root. The fix is to change the permissions of the device at some point before the use of pinentry (i.e. using gpg with an agent). If doing gpg as root, simply change the ownership to root right before using gpg<br />
chown root /dev/ttyN # where N is the current tty<br />
and then change it back after using gpg the first time. The equivalent is likely to be true with {{Ic|/dev/pts/}}.<br />
<br />
{{Note|being part of the group {{Ic|tty}} '''does not''' seem to alleviate the issue, at least as root. (Please confirm with non-superusers)}}<br />
<br />
=== Agent complains end of file ===<br />
<br />
The default pinentry program is pinentry-gtk-2, which needs a DBus session bus to run properly. See [[General troubleshooting#Session permissions]] for details.<br />
<br />
Alternatively, you can use {{ic|pinentry-qt}}. See [[GnuPG#Pinentry]].<br />
<br />
=== KGpg configuration permissions ===<br />
<br />
There have been issues with {{Pkg|kdeutils-kgpg}} being able to access the {{ic|~/.gnupg/}} options. One issue might be a result of a deprecated ''options'' file, see the [https://bugs.kde.org/show_bug.cgi?id=290221 bug] report.<br />
<br />
Another user reported that ''KGpg'' failed to start until the {{ic|~/.gnupg}} folder is set to {{ic|drwxr-xr-x}} permissions. If you require this work-around, ensure that the directory contents retain {{ic|-rw-------}} permissions! Further, report it as a bug to the [https://bugs.kde.org/buglist.cgi?quicksearch=kgpg developers].<br />
<br />
=== Conflicts betweent gnome-keyring and GPG-Agent ===<br />
<br />
When using gnome-keyring for key storage, gpg issues the warning:<br />
gpg: WARNING: The GNOME keyring manager hijacked the GnuPG agent.<br />
gpg: WARNING: GnuPG will not work proberly - please configure that tool to not interfere with the GnuPG system<br />
<br />
Although some GPG Developers consider the behaviour of Gnome Keyring dangerous (see the [http://bugs.gnupg.org/gnupg/issue1656 issue report]), users that do not want to switch to the GPG-Agent can fix this temporarily by changing the AGENT_ID string in the binary of GPG2 to a command that gnome-keyring doesn't implement, say AGENX_ID:<br />
# sed -i s/AGENT_ID/AGENX_ID/ `which gpg2`<br />
<br />
== See also ==<br />
<br />
* [http://gnupg.org/gph/en/manual.html The GNU Privacy Handbook]<br />
* [http://blog.sanctum.geek.nz/series/linux-crypto/ A more comprehensive gpg Tutorial]<br />
* [https://www.gnupg.org/faq/gnupg-faq.html GnuPG FAQ]<br />
* [https://help.riseup.net/en/security/message-security/openpgp/gpg-best-practices gpg.conf recommendations and best practices]<br />
* [https://github.com/ioerror/torbirdy/blob/master/gpg.conf Torbirdy gpg.conf]</div>Kargshttps://wiki.archlinux.org/index.php?title=Cron&diff=303760Cron2014-03-09T11:10:33Z<p>Kargs: /* Activation and autostart */ s/presents/present</p>
<hr />
<div>{{Lowercase title}}<br />
[[Category:Daemons and system services]]<br />
[[de:Cron]]<br />
[[fr:Cron]]<br />
[[ja:Cron]]<br />
[[ko:Cron]]<br />
[[sk:Cron]]<br />
[[zh-CN:Cron]]<br />
{{Related articles start}}<br />
{{Related|systemd/cron functionality}}<br />
{{Related articles end}}<br />
<br />
From [[Wikipedia:Cron|Wikipedia]]:<br />
<br />
'''''cron''' is the time-based job scheduler in Unix-like computer operating systems. cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration.''<br />
<br />
== Installation ==<br />
<br />
{{Pkg|cronie}} is installed by default as part of the {{Grp|base}} group. Other cron implementations exist if preferred, Gentoo's [http://www.gentoo.org/doc/en/cron-guide.xml cron guide] offers comparisons. For example, {{Pkg|fcron}}, {{AUR|bcron}} or {{AUR|vixie-cron}} are other alternatives. {{AUR|dcron}} used to be the default cron implementation in Arch Linux until May 2011.<br />
<br />
== Configuration ==<br />
<br />
=== Activation and autostart ===<br />
<br />
cron provided implementation {{ic|cronie}} is '''not''' enabled by default in new Arch installs. This can be checked by looking at the log in {{ic|/var/log/}} or by issuing:<br />
$ systemctl is-enabled cronie<br />
<br />
Therefore, cronie systemd service must be started and enabled via [[Systemd#Using_units|systemctl]] prior or after setting the first cron job:<br />
# systemctl start cronie<br />
# systemctl enable cronie<br />
Adapt these commands depending on your chosen implementation, e.g.:<br />
# systemctl start dcron<br />
# systemctl enable dcron<br />
<br />
{{note|Three daily jobs are present by default in {{ic|/etc/cron.daily}} for being part of the files installed by the {{Grp|base}} group: {{ic|logrotate}}, {{ic|man-db}} and {{ic|shadow}}. There is also the {{ic|0anacron}} ''hourly'' job provided by default by cronie, which allows for [[Cron#Asynchronous_job_processing|delayed runs of other jobs]] e.g. if the computer was switched off at the moment of standard execution. Activating cron service will trigger all of them.}}<br />
<br />
=== Handling errors of jobs ===<br />
<br />
cron registers the output from ''stdout'' and ''stderr'' and attempts to send it as email to the user's spools via the {{ic|sendmail}} command. Cronie disables mail output if {{ic|/usr/bin/sendmail}} is not found. To log these messages use the {{ic|-m}} option and write a script or install a rudimentary SMTP subsystem.<br />
<br />
# [[Systemd#Editing_provided_unit_files|Edit]] the {{ic|cronie.service}} unit.<br />
# Install {{Pkg|esmtp}}, {{Pkg|msmtp}}, {{Pkg|opensmtpd}} or write a custom script.<br />
<br />
==== Example with msmtp ====<br />
<br />
Here are two ways to obtain emails from cronie with msmtp:<br />
<br />
# Install the {{Pkg|msmtp-mta}} package which effectively creates a symbolic link from {{ic|/usr/bin/sendmail}} to {{ic|/usr/bin/msmtp}}. Restart {{ic|cronie}} to make sure it detects the new {{ic|sendmail}} command. You must then provide a way for msmtp to convert your username into an email address.<br />
#* Either add a {{ic|MAILTO}} line to your crontab, like so:{{bc|<nowiki>MAILTO=your@email.com</nowiki>}} '''or''':<br />
#* Add this line to {{ic|/etc/msmtprc}}: {{bc|aliases /etc/aliases}}and create {{ic|/etc/aliases}}: {{bc|your_username: your@email.com<br># Optional:<br>default: your@email.com}}<br />
# [[Systemd#Editing_provided_unit_files|Edit]] the {{ic|cronie.service}} unit. For example, create {{ic|/etc/systemd/system/cronie.service.d/msmtp.conf}}:{{bc|<nowiki>[Service]<br />
ExecStart=<br />
ExecStart=/usr/bin/crond -n -m '/usr/bin/msmtp -t'</nowiki>}}<br />
{{Note|The empty {{ic|<nowiki>ExecStart=</nowiki>}} cancels any previous {{ic|ExecStart}} commands.}}<br />
<br />
==== Example with esmtp ====<br />
<br />
Install {{Pkg|esmtp}} and {{Pkg|procmail}}.<br />
<br />
After installation configure the routing:<br />
{{hc|/etc/esmtprc|<br />
identity ''myself''@myisp.com<br />
hostname mail.myisp.com:25<br />
username ''"myself"''<br />
password ''"secret"''<br />
starttls enabled<br />
default<br />
mda "/usr/bin/procmail -d%T"<br />
}}<br />
<br />
Procmail needs root privileges to work in delivery mode but it is not an issue if you are running the cronjobs as root anyway.<br />
<br />
To test that everything works correctly, create a file {{ic|message.txt}} with {{ic|"test message"}} in it. <br />
<br />
From the same directory run:<br />
<br />
$ sendmail ''user_name'' < message.txt <br />
<br />
then:<br />
<br />
$ cat /var/spool/mail/''user_name''<br />
<br />
You should now see the test message and the time and date it was sent.<br />
<br />
The error output of all jobs will now be redirected to {{ic|/var/spool/mail/''user_name''}}.<br />
<br />
Due to the privileged issue, it is hard to create and send emails to root (e.g. {{ic|su -c ""}}). You can ask {{ic|esmtp}} to forward all root's email to an ordinary user with:<br />
{{hc|/etc/esmtprc|<br />
2=force_mda="''user-name''"<br />
}}<br />
<br />
{{Note|If the above test didn't work, you may try creating a local configuration in {{ic|~/.esmtprc}} with the same content.<br />
<br />
Run the following command to make sure it has the correct permission: <br />
<br />
$ chmod 710 ~/.esmtprc<br />
<br />
Then repeat the test with {{ic|message.txt}} exactly as before.}}<br />
<br />
==== Example with opensmtpd ====<br />
<br />
Install {{Pkg|opensmtpd}}.<br />
<br />
Edit {{ic|/etc/smtpd/smtpd.conf}}. The following configuration allows for local delivery:<br />
<br />
listen on localhost<br />
accept for local deliver to mbox<br />
<br />
You can proceed to test it:<br />
# systemctl start smtpd<br />
$ echo test | sendmail user<br />
<br />
''user'' can check his/her mail in with any [[:Category:Email_Client|reader]] able to handle mbox format, or just have a look at the file {{ic|/var/spool/mail/''user''}}. If everything goes as expected, you can enable opensmtpd for future boots:<br />
# systemctl enable smtpd<br />
<br />
This approach has the advantage of not sending local cron notifications to a remote server. Not even network connection is needed. On the downside, you need a new daemon running.<br />
<br />
{{Note|<br />
* At the moment of writing the Arch opensmtpd package does not create all needed directories under {{ic|/var/spool/smtpd}}, but the daemon will warn about that specifying the required ownerships and permissions. Just create them as suggested.<br />
* Even though the suggested configuration does not accept remote connections, it's a healthy precaution to add an additional layer of security blocking port 25 with [[iptables]] or similar.<br />
}}<br />
<br />
==== Long cron job ====<br />
<br />
Suppose this program is invoked by cron :<br />
<br />
#!/bin/sh<br />
echo "I had a recoverable error!"<br />
sleep 1h<br />
<br />
What happens is this:<br />
# cron runs the script<br />
# as soon as cron sees some output, it runs your MTA, and provides it with the headers. It leaves the pipe open, because the job hasn't finished and there might be more output.<br />
# the MTA opens the connection to postfix and leaves that connection open while it waits for the rest of the body.<br />
# postfix closes the idle connection after less than an hour and you get an error like this :<br />
smtpmsg='421 … Error: timeout exceeded' errormsg='the server did not accept the mail'<br />
<br />
To solve this problem you can use the command chronic or sponge from {{Pkg|moreutils}}.<br />
From their respective man page:<br />
; chronic: chronic runs a command, and arranges for its standard out and standard error to only be displayed if the command fails (exits nonzero or crashes). If the command succeeds, any extraneous output will be hidden.<br />
; sponge: sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before opening the output file… If no output file is specified, sponge outputs to stdout.<br />
<br />
Even if it's not said chronic buffer the command output before opening its standard output (like sponge does).<br />
<br />
== Crontab format ==<br />
<br />
The basic format for a crontab is:<br />
<br />
''minute'' ''hour'' ''day_of_month'' ''month'' ''day_of_week'' ''command''<br />
<br />
* ''minute'' values can be from 0 to 59.<br />
* ''hour'' values can be from 0 to 23.<br />
* ''day_of_month'' values can be from 1 to 31.<br />
* ''month'' values can be from 1 to 12.<br />
* ''day_of_week'' values can be from 0 to 6, with 0 denoting Sunday.<br />
<br />
Multiple times may be specified with a comma, a range can be given with a hyphen, and the asterisk symbol is a wildcard character. Spaces are used to separate fields. For example, the line:<br />
<br />
*0,*5 9-16 * 1-5,9-12 1-5 ~/bin/i_love_cron.sh<br />
<br />
Will execute the script {{ic|i_love_cron.sh}} at five minute intervals from 9 AM to 4:55 PM on weekdays except during the summer months (June, July, and August). More examples and advanced configuration techniques can be found below.<br />
<br />
== Basic commands ==<br />
<br />
Crontabs should never be edited directly; instead, users should use the {{ic|crontab}} program to work with their crontabs. To be granted access to this command, user must be a member of the users group (see the {{ic|gpasswd}} command).<br />
<br />
To view their crontabs, users should issue the command:<br />
<br />
$ crontab -l<br />
<br />
To edit their crontabs, they may use:<br />
<br />
$ crontab -e<br />
<br />
To remove their crontabs, they should use:<br />
<br />
$ crontab -r<br />
<br />
If a user has a saved crontab and would like to completely overwrite their old crontab, he or she should use:<br />
<br />
$ crontab ''saved_crontab_filename''<br />
<br />
To overwrite a crontab from the command line ([[Wikipedia:stdin]]), use<br />
<br />
$ crontab - <br />
<br />
To edit somebody else's crontab, issue the following command as root:<br />
<br />
# crontab -u ''username'' -e<br />
<br />
This same format (appending {{ic|-u ''username''}} to a command) works for listing and deleting crontabs as well.<br />
<br />
== Examples ==<br />
<br />
The entry:<br />
<br />
01 * * * * /bin/echo Hello, world!<br />
<br />
runs the command {{ic|/bin/echo Hello, world!}} on the first minute of every hour of every day of every month (i.e. at 12:01, 1:01, 2:01, etc.).<br />
<br />
Similarly:<br />
<br />
*/5 * * jan mon-fri /bin/echo Hello, world!<br />
<br />
runs the same job every five minutes on weekdays during the month of January (i.e. at 12:00, 12:05, 12:10, etc.).<br />
<br />
The line (as noted in "man 5 crontab"):<br />
<br />
*0,*5 9-16 * 1-5,9-12 1-5 /home/user/bin/i_love_cron.sh<br />
<br />
will execute the script {{Ic|i_love_cron.sh}} at five minute intervals from 9 AM to 5 PM (excluding 5 PM itself) every weekday (Mon-Fri) of every month except during the summer (June, July, and August).<br />
<br />
Periodical settings can also be entered as in this crontab template:<br />
<br />
<pre># Chronological table of program loadings <br />
# Edit with "crontab" for proper functionality, "man 5 crontab" for formatting<br />
# User: johndoe<br />
<br />
# mm hh DD MM W /path/progam [--option]... ( W = weekday: 0-6 [Sun=0] )<br />
21 01 * * * /usr/bin/systemctl hibernate<br />
@weekly $HOME/.local/bin/trash-empty<br />
</pre><br />
<br />
== Default editor ==<br />
<br />
To use an alternate default editor, define the {{ic|EDITOR}} environment variablee it in a shell initialization script ({{AUR|vim-default-editor}} is available for vim users). For example:<br />
<br />
{{hc|/etc/profile.d/nano-default-editor|2=<nowiki><br />
#!/bin/sh<br />
<br />
export EDITOR=/usr/bin/nano<br />
</nowiki>}}<br />
<br />
As a regular user, {{ic|su}} will need to be used instead of {{ic|sudo}} for the environment variable to be pulled correctly:<br />
<br />
$ su -c "crontab -e"<br />
<br />
To have an alias to this {{ic|printf}} is required to carry the arbitrary string because {{ic|su}} launches in a new shell:<br />
<br />
alias scron="su -c $(printf "%q " "crontab -e")"<br />
<br />
== run-parts issue ==<br />
<br />
cronie uses {{ic|run-parts}} to carry out script in {{ic|cron.daily}}/{{ic|cron.weekly}}/{{ic|cron.monthly}}. Be careful that the script name in these won't include a dot (.), e.g. {{ic|backup.sh}}, since {{ic|run-parts}} without options will ignore them (see: {{ic|man run-parts}}).<br />
<br />
== Running X.org server-based applications ==<br />
<br />
Cron does not run under the X.org server therefore it cannot know the environmental variable necessary to be able to start an X.org server application so they will have to be defined. One can use a program like {{AUR|xuserrun}} to do it:<br />
<br />
17 02 * ... /usr/bin/xuserrun /usr/bin/xclock<br />
<br />
Or then can be defined manually ({{ic|echo $DISPLAY}} will give the current DISPLAY value):<br />
<br />
17 02 * ... env DISPLAY=:0 /usr/bin/xclock<br />
<br />
If done through say SSH, permission will need be given:<br />
<br />
# xhost +si:localuser:$(whoami)<br />
<br />
== Asynchronous job processing ==<br />
<br />
If you regularly turn off your computer but do not want to miss jobs, there are some solutions available (easiest to hardest):<br />
<br />
=== Cronie ===<br />
<br />
Cronie comes with anacron included.<br />
<br />
=== Dcron ===<br />
<br />
Vanilla {{AUR|dcron}} supports asynchronous job processing. Just put it with @hourly, @daily, @weekly or @monthly with a jobname, like this:<br />
<br />
@hourly ID=greatest_ever_job echo This job is very useful.<br />
<br />
=== Cronwhip ===<br />
<br />
{{AUR|cronwhip}} is a script to automatically run missed cron jobs; it works with the former default cron implementation, ''dcron''.<br />
See also the [https://bbs.archlinux.org/viewtopic.php?id=57973 forum thread].<br />
<br />
=== Anacron ===<br />
<br />
{{AUR|anacron}} is a full replacement for ''dcron'' which processes jobs asynchronously.<br />
<br />
=== Fcron ===<br />
<br />
Like ''anacron'', {{Pkg|fcron}} assumes the computer is not always running and, unlike ''anacron'', it can schedule events at intervals shorter than a single day. Like cronwhip, it can run jobs that should have been run during the computer's downtime.<br />
See also the [https://bbs.archlinux.org/viewtopic.php?id=140497 forum thread]<br />
<br />
== Ensuring exclusivity ==<br />
<br />
If you run potentially long-running jobs (e.g., a backup might all of a sudden run for a long time, because of many changes or a particular slow network connection), then {{AUR|lockrun}} can ensure that the cron job won't start a second time.<br />
<br />
5,35 * * * * /usr/bin/lockrun -n /tmp/lock.backup /root/make-backup.sh<br />
<br />
== Dcron ==<br />
<br />
The cron daemon parses a configuration file known as {{ic|crontab}}. Each user on the system can maintain a separate crontab file to schedule commands individually. The root user's crontab is used to schedule system-wide tasks (though users may opt to use {{ic|/etc/crontab}} or the {{ic|/etc/cron.d}} directory, depending on which cron implementation they choose).<br />
<br />
{{hc|/var/spool/cron/root<br />
|2=<nowiki><br />
# Run command at a scheduled time<br />
# Edit this 'crontab -e' for error checking, man 1 crontab for acceptable format<br />
<br />
# <@freq> <tags and command><br />
@hourly ID=sys-hourly /usr/sbin/run-cron /etc/cron.hourly<br />
@daily ID=sys-daily /usr/sbin/run-cron /etc/cron.daily<br />
@weekly ID=sys-weekly /usr/sbin/run-cron /etc/cron.weekly<br />
@monthly ID=sys-monthly /usr/sbin/run-cron /etc/cron.monthly<br />
<br />
# mm hh DD MM W /path/command (or tags) # W = week: 0-6, Sun=0<br />
21 01 * * * /usr/bin/systemctl suspend<br />
</nowiki>}}<br />
<br />
These lines exemplify one of the formats that crontab entries can have, namely whitespace-separated fields specifying:<br />
<br />
# @period<br />
# ID=jobname (this tag is specific to dcron)<br />
# command<br />
<br />
The other standard format for crontab entries is:<br />
<br />
# minute<br />
# hour<br />
# day<br />
# month<br />
# day of week<br />
# command<br />
<br />
The crontab files themselves are usually stored as {{ic|/var/spool/cron/username}}. For example, root's crontab is found at {{ic|/var/spool/cron/root}}<br />
<br />
See the crontab [[man page]] for further information and configuration examples.<br />
<br />
== See also ==<br />
<br />
* [http://www.gentoo.org/doc/en/cron-guide.xml Gentoo Linux Cron Guide]</div>Kargshttps://wiki.archlinux.org/index.php?title=Xpra&diff=302789Xpra2014-03-01T20:04:51Z<p>Kargs: s/first at all/first of all</p>
<hr />
<div>[[Category:X Server]]<br />
From the [http://xpra.org/ Xpra website]:<br />
<br />
Xpra is '[[screen]] for X': it allows you to run X programs, usually on a remote host, direct their display to your local machine, and then to disconnect from these programs and reconnect from the same or another machine, without losing any state. It gives you remote access to individual applications. <br />
<br />
* Xpra is "rootless" or "seamless": programs you run under it show up on your desktop as regular programs, managed by your regular window manager. <br />
* Sessions can be accessed over SSH, or password protected over plain TCP sockets. <br />
* Xpra is usable over reasonably slow links and does its best to adapt to changing network bandwidth limits. (see also adaptive JPEG mode) <br />
* Xpra is open-source (GPLv2+), multi-platform and multi-language, with current clients written in Python and Java.<br />
<br />
==Installation==<br />
Install the package {{AUR|xpra-winswitch}} from the [[AUR]], in the server and client(s) machines.<br />
<br />
{{Tip|1=If you intend to run Xpra locally under a existing Xorg session with graphic drivers such as {{ic|<nowiki>nvidia</nowiki>}} or {{ic|<nowiki>ATi</nowiki>}} you will need to modify the default xpra config. Xpra fetches {{ic|-configdir}} from {{ic|xorg-server-xvfb}} which will be {{ic|/etc/X11/xorg.conf.d}}, there for you need to change this by following the three bottom steps of [https://bbs.archlinux.org/viewtopic.php?pid=1333056#p1333056 1333056#p1333056] in order to run xpra locally.}}<br />
<br />
==Use==<br />
Start an xpra server on the machine where you want to run the applications (we are using display number '''7''' here):<br />
<br />
{{bc|$ xpra start :7}}<br />
<br />
Now you can start an application, e.g. firefox:<br />
{{bc|1=$ DISPLAY=:7 firefox}}<br />
<br />
Or, if you want to start a screen session and execute the programs from there to be able to close the console:<br />
{{bc|1=<br />
$ DISPLAY=:7 screen<br />
[screen starts]<br />
$ firefox<br />
}}<br />
Note that if you start {{ic|screen}} like this you don't have to specify the display number when executing programs. They will be running on the xpra display automatically.<br />
<br />
After running these commands, you don't see any windows yet. To actually see the applications on your display, you have to connect to the xpra server. If you are connecting to an xpra display on the same machine, start the xpra client like this:<br />
{{bc|$ xpra attach :7}}<br />
<br />
Or, if you are connecting to a remote machine over ssh:<br />
{{bc|$ xpra attach ssh:user@example.com:7}}<br />
<br />
After starting the client, any programs running on the remote server display are displayed on your local screen. To detach, type {{ic|ctrl-c}} or use the command:<br />
{{bc|$ xpra detach ssh:user@example.com:7}}<br />
Programs continue to run on the server and you can reattach again later.<br />
<br />
You can stop the server with:<br />
{{bc|$ xpra stop :7}}<br />
on the machine where the server is running, or remotely:<br />
{{bc|$ xpra stop ssh:user@example.com:7}}<br />
<br />
For a complete manual, check {{ic|man xpra}}.<br />
<br />
==Tips and tricks==<br />
=== Start at boot ===<br />
==== Server ====<br />
It is possible to start the xpra server at boot using a [[systemd]] unit.<br />
<br />
Create the unit file:<br />
{{hc|/etc/systemd/system/xpra@.service|<nowiki><br />
[Unit]<br />
Description=xpra display<br />
<br />
[Service]<br />
Type=simple<br />
User=%i<br />
EnvironmentFile=/etc/conf.d/xpra<br />
ExecStart=/usr/bin/xpra --no-daemon start ${%i}<br />
<br />
[Install]<br />
WantedBy=multi-user.target<br />
</nowiki>}}<br />
<br />
Now create the configuration, adding a line for each username you want to have an xpra display:<br />
{{hc|/etc/conf.d/xpra|<nowiki><br />
myusername=:7<br />
</nowiki>}}<br />
[[Daemons|Enable the service]] for each username that owns a display. In this example, the service would be {{ic|xpra@myusername.service}}.<br />
==== Client ====<br />
{{Note|If the client is a remote machine, first of all use SSH keys to be able to connect to the server without typing a password. Read [[SSH Keys]] for more details.}}<br />
<br />
===== Method 1: .xinitrc =====<br />
Add to your {{ic|~/.xinitrc}} file the line necessary to start the connection, adding an '''&''' at the end of the line.<br />
<br />
Make sure to add such line '''before''' the {{ic|exec}} line.<br />
<br />
For example, on a remote client it could be:<br />
{{hc|~/.xinitrc|<br />
xpra attach ssh:user@example.com:7 &<br />
}}<br />
===== Method 2: systemd user session =====<br />
Configure your session to use '''systemd user session'''. Read [[Systemd/User]] for details.<br />
{{Note|Make sure you understand the difference between '''systemd user session''' services, and regular '''systemd''' services. Again, read the [[Systemd/User]] for details.}}<br />
<br />
Create the following service unit:<br />
{{hc|$HOME/.config/systemd/user/xpra-client@.service|<nowiki><br />
[Unit]<br />
Description=xpra client<br />
<br />
[Service]<br />
Type=simple<br />
EnvironmentFile=%h/.config/conf/xpra_client<br />
ExecStart=/usr/bin/xpra attach %i $OPTS<br />
<br />
[Install]<br />
WantedBy=default.target<br />
</nowiki>}}<br />
Create the configuration file, using the options you want:<br />
{{hc|$HOME/.config/conf/xpra_client|<nowiki><br />
OPTS=--encoding=jpeg --quality=90<br />
</nowiki>}}<br />
The service name would be in the format of {{ic|xpra-client@''ssh:username@hostname''':<display number>'''''.service}}.<br />
<br />
Example:<br />
{{bc|xpra-client@ssh:myuser@example.com:7.service}}<br />
[[Daemons|Enable that service]], and remember to use the {{ic|--user}} flag on {{ic|systemctl}}.<br />
<br />
==See also==<br />
* [http://xpra.org/ Xpra website]</div>Kargshttps://wiki.archlinux.org/index.php?title=Vim&diff=296603Vim2014-02-08T18:52:56Z<p>Kargs: Search and replace in the current line</p>
<hr />
<div>[[Category:Development]]<br />
[[Category:Text editors]]<br />
[[es:Vim]]<br />
[[de:Vim]]<br />
[[it:Vim]]<br />
[[lt:Vim]]<br />
[[ru:Vim]]<br />
[[zh-CN:Vim]]<br />
[[zh-TW:Vim]]<br />
''"[http://www.vim.org/about.php Vim] is an advanced text editor that seeks to provide the power of the de-facto UNIX editor ‘vi’, with a more complete feature set."'' <br />
<br />
Vim focuses on keyboard usage, and offers useful features such as syntax highlighting and scripting capabilities. Vim is not a simple text editor, like nano or pico. It does require some time to learn, and a great amount of time to master.<br />
<br />
== Installation ==<br />
<br />
[[pacman|Install]] the command line version with the {{Pkg|vim}} package, or you can install the GUI version (which also provides {{ic|vim}}) by installing the {{Pkg|gvim}} package.<br />
<br />
{{Note|<br />
* The {{Pkg|vim}} package is meant to be as lightweight as possible; hence, it does not support Python, Lua, and Ruby interpreters, nor does it support X server options (this means that it will not support copy and paste from the X clipboard). If you require these options, install the {{Pkg|gvim}} package instead (it includes the {{ic|vim}} binary as well). The {{ic|herecura-stable}} unofficial repository also provides a couple different Vim / gVim variants:<br />
{{hc|$ pacman -Slq herecura-stable &#124; grep vim|<br />
vim-cli<br />
vim-gvim-gtk<br />
vim-gvim-motif<br />
vim-gvim-qt<br />
vim-gvim-x11<br />
vim-rt<br />
vim-tiny<br />
}}<br />
<br />
* There are some visualization problems in KDE using {{Pkg|gvim}} from official repositories. In that case you can install {{ic|vim-gvim-qt}} from {{ic|herecura-stable}} or {{AUR|vim-qt}}<br />
}}<br />
<br />
==Usage==<br />
<br />
This is a basic overview on how to use Vim. Alternately, running {{Ic|vimtutor}} or {{Ic|gvimtutor}} will launch vim's tutorial, which takes about 25-30 minutes.<br />
<br />
Vim has four different modes:<br />
<br />
* Command mode: keystrokes are interpreted as commands.<br />
* Insert mode: keystrokes are entered into the file.<br />
* Visual mode: keystrokes select, cut, or copy text<br />
* Ex mode: input mode for additional commands (e.g. saving a file, replacing text...)<br />
<br />
===Basic editing===<br />
<br />
If you start Vim with:<br />
<br />
$ vim somefile.txt<br />
<br />
you will see a blank document (providing that somefile.txt does not exist. If it does, you will see what is in there). You will not be able to edit right away – you are in Command Mode. In this mode you are able to issue commands to Vim with the keyboard.<br />
<br />
{{Note|Vim is an example of classic Unix-style ware. It has a difficult learning curve, but once you get started, you will find that it is extremely powerful. Also, all commands are case sensitive. Sometimes the uppercase versions are “blunter” versions ({{ic|s}} will replace a character, {{ic|S}} will replace a line), other times they are completely different commands ({{ic|j}} will move down, {{ic|J}} will join two lines).}}<br />
<br />
You insert text (stick it before the cursor) with the {{ic|i}} command. {{ic|I}} (uppercase '''i''') inserts text at the beginning of the line. You append text (place text after the cursor, what most people expect) with {{ic|a}}. Typing {{ic|A}} will place the cursor at the end of the line.<br />
<br />
Return to command mode at any time by pressing {{ic|Esc}}.<br />
<br />
===Moving around===<br />
<br />
In Vim, you can move the cursor with the arrow keys, but this isn't the '''Vim way'''. You’d have to move your right hand all the way from the standard typing position all the way to the arrow keys, and then back. Not fun.<br />
<br />
In Vim you can move down by pressing {{ic|j}}. You can remember this because the “j” hangs down. You move the cursor back up by pressing {{ic|k}}. Left is {{ic|h}} (it's left of the “j”), and right is {{ic|l}} (lowercase '''L''').<br />
<br />
{{ic|^}} will put the cursor at the beginning of the line, and {{ic|$}} will place it at the end.<br />
<br />
{{Note|{{ic|^}} and {{ic|$}} are commonly used in regular expressions to match the beginning and ending of the line. Regular expressions are very powerful and are commonly used in *nix environment, so maybe it is a little bit tricky now, but later you will notice “the idea” behind the use of most of these key mappings.}}<br />
<br />
To advance a word, press the {{ic|w}} key. {{ic|W}} will include more characters in what it thinks is a word (e.g. underscores and dashes as a part of a word). To go back a word, {{ic|b}} is used. Once again, {{ic|B}} will include more characters in what Vim considers a word. To advance to the end of a word, use {{ic|e}}, {{ic|E}} includes more characters.<br />
<br />
To advance to the beginning of a sentence, {{ic|(}} will get the job done. {{ic|)}} will do the opposite, moving to the end of a sentence. For an even bigger jump, {{ic|{}} will move the the beginning a whole paragraph. {{ic|<nowiki>}</nowiki>}} will advance to the end of a whole paragraph.<br />
<br />
To advance to the header (top) of the screen, {{ic|H}} will get the job done. {{ic|M}} will advance to the middle of the screen, and {{ic|L}} will advance to the last (bottom). {{ic|gg}} will go to the beginning of the file, {{ic|G}} will go to the end of the file. {{ic|Ctrl+D}} will let you scroll page by page.<br />
<br />
===Repeating commands===<br />
<br />
If a command is prefixed by a number, then that command will be executed that number of times over (there are exceptions, but they still make sense, like the {{ic|s}} command). For example, pressing {{ic|3i}} then “Help! ” then {{ic|Esc}} will print “Help! Help! Help!“. Pressing {{ic|<nowiki>2}</nowiki>}} will advance you two paragraphs. This comes in handy with the next few commands…<br />
<br />
===Deleting===<br />
<br />
The {{ic|x}} command will delete the character under the cursor. {{ic|X}} will delete the character before the cursor. This is where those number functions get fun. {{ic|6x}} will delete 6 characters. Pressing {{ic|.}} (dot) will repeat the previous command. So, lets say you have the word "foobar" in a few places, but after thinking about it, you’d like to see just “foo”. Move the cursor under the "b", hit {{ic|3x}}, move to the next "foobar" and hit {{ic|.}} (dot).<br />
<br />
The {{ic|d}} will tell Vim that you want to delete something. After pressing {{ic|d}}, you need to tell Vim what to delete. Here you can use the movement commands. {{ic|dW}} will delete up to the next word. {{ic|d^}} will delete up unto the beginning of the line. Prefacing the delete command with a number works well too: {{ic|3dW}} will delete the next three words. {{ic|D}} (uppercase) is a shortcut to delete until the end of the line (basically {{ic|d$}}). Pressing {{ic|dd}} will delete the whole line.<br />
<br />
To delete then replace the current word, place the cursor on the word and execute the command {{ic|cw}}. This will delete the word and change to insert mode. To replace only a single letter use {{ic|r}}.<br />
<br />
===Undo and redo===<br />
<br />
Vim has a built-in clipboard (also known as a buffer). Actions can be undone with {{ic|u}} and redone with {{ic|Ctrl+r}}.<br />
<br />
===Visual mode===<br />
<br />
Pressing {{ic|v}} will put you in visual mode . Here you can move around to select text, when you’re done, you press {{ic|y}} to yank the text into the buffer (copy), or you may use {{ic|c}} to cut. {{ic|p}} pastes after the cursor, {{ic|P}} pastes before. {{ic|V}}, Visual Line mode, is the same for entire lines. {{ic|Ctrl+v}} is for blocks of text.<br />
<br />
{{Note|Whenever you delete something, that something is placed inside a buffer and is available for pasting.}}<br />
<br />
===Search and replace===<br />
<br />
To search for a word or character in the file, simply use {{ic|/}} and then the characters your are searching for and press enter. To view the next match in the search press {{ic|n}}, press {{ic|N}} for the previous match.<br />
<br />
To search and replace use the substitute {{ic|:s/}} command. The syntax is: {{Ic|[range]s///[arguments]}}. For example:<br />
<br />
{{bc|<br />
Command Outcome<br />
:s/xxx/yyy/ Replace xxx with yyy at the first occurrence<br />
:s/xxx/yyy/g Replace xxx with yyy, every occurrence in the current line<br />
:s/xxx/yyy/gc Replace xxx with yyy global with confirm<br />
:%s/xxx/yyy/g Replace xxx with yyy global in the whole file<br />
}}<br />
<br />
You can use the global {{ic|:g/}} command to search for patterns and then execute a command for each match. The syntax is: {{Ic|[range]:g//[cmd]}}.<br />
<br />
{{bc|<br />
Command Outcome<br />
:g/^#/d Delete all lines that begins with #<br />
:g/^$/d Delete all lines that are empty<br />
}}<br />
<br />
===Saving and quitting===<br />
<br />
To save and/or quit, you will need to use Ex mode. Ex mode commands are preceded by a {{ic|:}}. To write a file use {{ic|:w}} or if the file doesn’t have a name {{ic|''':w''' filename}}. Quitting is done with {{ic|:q}}. If you choose not to save your changes, use {{ic|:q!}}. To save and quit {{ic|:x}}.<br />
<br />
=== Additional commands ===<br />
<br />
# Pressing {{ic|s}} will erase the current letter under the cursor, and place you in insert mode. {{ic|S}} will erase the whole line, and place you in insert mode.<br />
# {{ic|o}} will create a newline below the line and put you insert mode, {{ic|O}} will create a newline above the line and put you in insert mode.<br />
# {{ic|yy}} will yank an entire line<br />
# {{ic|cc}} will delete the current line and place you in insert mode.<br />
# {{ic|*}} will highlight the current word and {{ic|n}} will search it<br />
<br />
==Configuration==<br />
<br />
Vim's user-specific configuration file is located in the home directory: {{ic|~/.vimrc}}, and files are located inside {{ic|~/.vim/}} The global configuration file is located at {{ic|/etc/vimrc}}. Global files are located inside {{ic|/usr/share/vim/}}.<br />
<br />
The Vim global configuration in Arch Linux is very basic and differs from many other distributions' default Vim configuration file. To get some commonly expected behaviors (such as syntax highlighting, returning to the last known cursor position), consider using Vim's example configuration file:<br />
<br />
# mv /etc/vimrc /etc/vimrc.bak<br />
# cp /usr/share/vim/vim74/vimrc_example.vim /etc/vimrc<br />
<br />
===Wrap searches===<br />
<br />
With this option the ''search next'' behaviour allows to jump to the beginning of the file, when the end of file is reached. Similarly, ''search previous'' jumps to the end of the file when the start is reached. <br />
<br />
set wrapscan<br />
<br />
=== Spell checking ===<br />
<br />
set spell<br />
<br />
With this setting, Vim will highlight incorrectly spelled words. Place the cursor on a misspelled word and enter {{ic|1=z=}} to view spelling suggestions.<br />
<br />
Only English language dictionaries are installed by default, more can be found in the [[Official Repositories|official repositories]]. To get the list of available languages type:<br />
<br />
# pacman -Ss vim-spell<br />
<br />
Language dictionaries can also be found at the [http://ftp.vim.org/vim/runtime/spell/ Vim FTP archive]. Put the downloaded dictionar(y/ies) into the {{ic|~/.vim/spell}} folder and set the dictionary by typing: {{ic|1=:setlocal spell spelllang=LL}}<br />
<br />
{{Tip|<br />
* To enable spell checking for LaTeX (or TeX) documents only, add {{ic|1=autocmd FileType tex setlocal spell spelllang=en_us}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart Vim. For spell checking of languages other than English, simply replace {{ic|en_us}} with the value appropriate for your language.<br />
* To enable spelling in two languages (for instance English and German), add {{ic|1=set spelllang=en,de}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart Vim.<br />
* You can enable spell checking for arbitrary file types (e.g. *.txt) by using the FileType plugin and a custom rule for file type detection. To enable spell checking for any file ending in {{ic|*.txt}}, create the file {{ic|/usr/share/vim/vimfiles/ftdetect/plaintext.vim}}, and insert the line {{ic|autocmd BufRead,BufNewFile *.txt setfiletype plaintext}} into that file. Next, insert the line {{ic|1=autocmd FileType plaintext setlocal spell spelllang=en_us}} into your {{ic|~/.vimrc}} or {{ic|/etc/vimrc}}, and then restart Vim.}}<br />
<br />
===Syntax highlighting===<br />
<br />
To enable syntax highlighting (Vim supports a huge list of programming languages):<br />
<br />
:filetype plugin on<br />
:syntax on<br />
<br />
===Using the mouse===<br />
<br />
Vim has the ability to make use of the mouse, but requires xterm's mouse reporting feature.<br />
<br />
# See the example .vimrc below to enable the mouse.<br />
# Use xterm. In your console: {{ic|1=export TERM=xterm-256color}} or {{ic|1=export TERM=xterm}}<br />
<br />
Notes:<br />
* This even works in PuTTY over SSH.<br />
* In PuTTY, the normal highlight/copy behaviour is changed because Vim enters visual mode when the mouse is used. To select text with the mouse normally, hold down the {{ic|Shift}} key while selecting text.<br />
<br />
===Traverse line breaks with arrow keys===<br />
<br />
By default, pressing {{ic|←}} at the beginning of a line, or pressing {{ic|→}} at the end of a line, will not let the cursor traverse to the previous, or following, line.<br />
<br />
The default behavior can be changed by adding {{ic|1=set whichwrap=b,s,<,>,[,]}} to your {{ic|~/.vimrc}} file.<br />
<br />
=== Example ~/.vimrc ===<br />
<br />
An example [[Vim/.vimrc|Vim configuration]].<br />
<br />
==Plugins==<br />
Adding plugins to vim can increase your productivity. The group vim-plugins has many plugins to choose from(there are more in the repos though ie: vim-supertab).<br />
pacman -Ss vim-plugins<br />
===cscope===<br />
[http://cscope.sourceforge.net/ Cscope] is a tool for browsing a project. By navigating to a word/symbol/function and calling cscope(usually with shortcut keys) it can find: functions calling the function, the function definition, and more. Multiple steps are required to search a code base.<br />
<br />
Install the {{Pkg|cscope}} package.<br />
<br />
Copy the cscope default file where it will be automatically read by vim:<br />
mkdir -p ~/.vim/plugin<br />
wget -P ~/.vim/plugin http://cscope.sourceforge.net/cscope_maps.vim <br />
<br />
Create a file which contains the files you wish cscope to index(Cscope can handle many languages but this example finds .c, .cpp, and .h files):<br />
cd ''/path/to/projectfolder/''<br />
find . -type f -print | grep -E '\.(c(pp)?|h)$' > cscope.files<br />
Create database files that cscope will read:<br />
cscope -bq<br />
{{note|You must browse your project files from this location or set and export the $CSCOPE_DB variable, pointing it to the cscope.out file.}}<br />
<br />
Default keyboard shortcuts<br />
Ctrl-\ and<br />
c: Find functions calling this function<br />
d: Find functions called by this function<br />
e: Find this egrep pattern<br />
f: Find this file<br />
g: Find this definition<br />
i: Find files #including this file<br />
s: Find this C symbol<br />
t: Find assignments to<br />
<br />
Feel free to change the shortcuts.<br />
#Maps ctrl-c to find functions calling the function <br />
nnoremap <C-c> :cs find c <C-R>=expand("<cword>")<CR><CR><br />
<br />
===Taglist===<br />
[http://vim-taglist.sourceforge.net/ Taglist] provides an overview of the structure of source code files and allows you to efficiently browse through source code files in different programming languages.<br />
<br />
Install the {{Pkg|vim-taglist}} package.<br />
<br />
Usefull options to be put in ~/.vimrc<br />
let Tlist_Compact_Format = 1<br />
let Tlist_GainFocus_On_ToggleOpen = 1<br />
let Tlist_Close_On_Select = 1<br />
nnoremap <C-l> :TlistToggle<CR><br />
<br />
==Merging files (vimdiff)==<br />
<br />
Vim includes a diff editor, a program that aids the merging of differences between two (or more, with limited usefulness) files. {{ic|vimdiff}} opens a horizontally multi-paned view that colorfully highlights differences, each pane containing one of the files to be examined/edited. Vim has [[#Usage|several modes]], two important ones being '''Insert mode''', which lets text be edited, and '''Command mode''', which lets the cursor be moved move across windows and lines. Begin by running {{ic|vimdiff file1 file2}}. Some example commands follow.<br />
<br />
;{{ic|]c}} : next difference<br />
;{{ic|[c}} : previous difference<br />
;{{ic|Ctrl+w+w}} : switch windows<br />
;{{ic|i}} : enter Insert mode<br />
;{{ic|Esc}} : exit Insert mode<br />
;{{ic|p}} : paste<br />
;{{ic|do}} : diff obtain. When the cursor is on a (highlighted) difference, copies the changes from the other window to the current one.<br />
;{{ic|dp}} : diff put. Inverse of diff obtain; copies the changes from current windows to the other one.<br />
;{{ic|zo}} : open folded text<br />
;{{ic|zc}} : close folded text<br />
;{{ic|<nowiki>:</nowiki>diffupdate}} : re-scan the files for differences<br />
;{{ic|yy}} : copy a line<br />
;{{ic|dd}} : cut a line<br />
;{{ic|:wq}} : save and exit the current window<br />
;{{ic|:wqa}} : save and exit both windows<br />
;{{ic|:q!}} : exit without saving<br />
<br />
Once your file has been correctly edited, taking into account changes in file.pacnew:<br />
# mv file file.bck<br />
# mv file.pacnew file<br />
Check whether your new file is correct, then remove your backup:<br />
# rm file.bck<br />
<br />
==Vim tips==<br />
<br />
Specific user tricks to accomplish tasks.<br />
<br />
===Line numbers===<br />
<br />
# Show line numbers by {{Ic|:set number}}.<br />
# Jump to line number {{Ic|:<line number>}}.<br />
<br />
===Substitute on lines===<br />
<br />
To only substitute between certain lines:<br />
<br />
:''n'',''n''s/one/two/g<br />
<br />
For example, to replace instances of 'one' with 'two' between lines 3 and 4, one would execute:<br />
<br />
:3,4s/one/two/g<br />
<br />
===Make Vim restore cursor position in files===<br />
<br />
If you want the cursor to appear in its previous position after you open a file, add the following to your {{ic|~/.vimrc}}:<br />
<br />
{{bc|<nowiki><br />
if has("autocmd")<br />
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g`\"" | endif<br />
endif<br />
</nowiki>}}<br />
<br />
See also [http://vim.wikia.com/wiki/Restore_cursor_to_file_position_in_previous_editing_session this] tip in Vim Wiki.<br />
<br />
===Empty space at the bottom of gVim windows===<br />
When using a [[window manager]] configured to ignore window size hints, gVim will fill the non-functional area with the GTK theme background color. <br />
<br />
The solution is to adjust how much space gVim reserves at the bottom of the window. Take note that if you set it to zero, you won't be able to see the bottom horizontal scrollbar, if you have one. Put the following line in {{ic|~/.vimrc}}:<br />
<br />
set guiheadroom=0<br />
<br />
===Replace vi command with vim===<br />
<br />
Create an [[Bash#Aliases|alias]] for {{ic|vi}} to {{ic|vim}}.<br />
<br />
==Troubleshooting==<br />
<br />
==="^M"===<br />
There is a "^M" at the end of each line. This usually happens when you are editing a text file which was created in MS-DOS or Windows.<br />
<br />
Solution:<br />
Replace all "^M" using the command:<br />
<br />
{{bc|:%s/^M//g}}<br />
<br />
Pay attention, "^" is the control letter, press {{ic|Ctrl+Q}} to get the right "^".<br />
<br />
Alternatively, install the package {{pkg|dos2unix}} from the official repositories, and run {{ic|dos2unix <file name here>}}.<br />
<br />
==See also==<br />
<br />
===Official===<br />
* [http://www.vim.org/ Homepage]<br />
* [http://vimdoc.sourceforge.net/ Documentation]<br />
* [http://vim.wikia.com Tips Wiki]<br />
<br />
===Tutorials===<br />
* [http://usalug.org/vi.html vi Tutorial and Reference Guide]<br />
* [http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html Graphical vi-Vim Cheat Sheet and Tutorial]<br />
* [http://blog.interlinked.org/tutorials/vim_tutorial.html Vim Introduction and Tutorial]<br />
* [http://www.openvim.com/ Open Vim] - Collection of Vim learning tools<br />
* [http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/ Learn Vim Progressively]<br />
* [http://www.knowvim.com/ know vim]<br />
<br />
====Videos====<br />
* [http://vimcasts.org/ Vimcasts] - Screencasts in .ogg format.<br />
* [http://www.derekwyatt.org/vim/vim-tutorial-videos/vim-novice-tutorial-videos/ Tutorial Videos] - Covering the basics up to advanced topics.<br />
<br />
====Games====<br />
* [http://vim-adventures.com/ Vim Adventures]<br />
* [http://vimgolf.com/ VimGolf]<br />
<br />
===Example configurations===<br />
* [http://nion.modprobe.de/setup/vimrc nion's]<br />
* [http://amix.dk/vim/vimrc.html A detailed configuration from Amir Salihefendic]<br />
* [http://www.jukie.net/~bart/conf/vimrc Bart Trojanowski]<br />
* [https://github.com/spf13/spf13-vim Steve Francia's Vim Distribution]<br />
* [https://github.com/W4RH4WK/dotVim W4RH4WK's Vim configuration]<br />
* [http://www.askapache.com/linux/fast-vimrc.html Fast vimrc/colorscheme from askapache]<br />
<br />
===Other===<br />
* [http://www.gentoo-wiki.info/HOWTO_VIM HOWTO Vim] - Gentoo wiki article which this article was based on (author unknown).<br />
* [http://bytefluent.com/vivify/ Vivify] - A ColorScheme Editor for Vim</div>Kargs