Welcome to khard’s documentation!¶
Command line usage¶
The following subsections give an overview of khard’s main features.
You may get general help and all available actions with
khard --help
If you need help on a specific action, use:
khard action --help
Beware, that the order of the command line parameters matters.
Show contacts¶
After you have created a new address book or calendar and you have synced it to your local machine, you can list all available contacts with the following command:
khard list
or if you have more than one address book and you want to filter the output:
khard list -a addressbook1,addressbook2
The resulting contact table only contains the first phone number and email address. If you want to view all contact details you can pick one from the list:
khard details
or search for it:
khard details [--strict-search] name of contact
or select the contact by it’s uid, which you can find at the contacts table:
khard details -u ID
The parameters -a and -u from the examples above are always optional. If you don’t use them or your input produces unambiguous results, you may pick the contacts from a list instead.
The search parameter searches in all data fields. Therefore you aren’t limited to the contact’s name but you also could for example search for a part of a phone number, email address or post address. However if you explicitly want to narrow your search to the name field, you may use the –strict-search parameter instead.
Create contact¶
Add new contact with the following command:
khard new [-a "address book name"]
The template for the new contact opens in the text editor, which you can set in the khard.conf file. It follows the yaml syntax.
Alternatively you can create the contact from stdin:
echo """
First name : John
Last name  : Smith
Email :
    work : john.smith@example.org
Phone :
    home : xxx 555 1234
Categories :
    - cat1
    - cat2
    - cat3
""" | khard new [-a "address book name"]
or create from input template file:
khard new -i contact.yaml [-a "address book name"]
You may get an empty contact template with the following command:
khard export --empty-contact-template -o empty.yaml
Per default khard creates vcards of version 3.0. If your other contact applications support vcards of the more recent version 4.0, you may change this with the option –vcard-version. Example:
khard new --vcard-version=4.0 [-a "address book name"]
For a more permanent solution you may set the preferred_version parameter in the vcard section of the khard config file (see misc/khard/khard.conf.example for more details). But beware, that khard cannot convert already existing contacts from version 3.0 to 4.0. Therefore this setting is not applicable to the modify action.
Edit contacts¶
Use the following to modify the contact after successful creation:
khard modify [-a addr_name] [-u uid|search terms [search terms ...]]
If you want to edit the contact elsewhere, you can export the filled contact template:
khard export -o contact.yaml [-a addr_name] [-u uid|search terms [search terms ...]]
Edit the yaml file and re-import either through stdin:
cat contact.yaml | khard modify [-a addr_name] [-u uid|search terms [search terms ...]]
or file name:
khard modify -i contact.yaml [-a addr_name] [-u uid|search terms [search terms ...]]
If you want to merge contacts use the following to select a first and then a second contact:
khard merge [-a source_abook] [-u uid|search terms [search terms ...]] [-A target_abook] [-U target_uid|-t target_search_terms]
You will be launched into your merge_editor ( see the “merge_editor” option in khard.conf) where you can merge all changes from the first selected contact onto the second. Once you are finished, the first contact is deleted and the second one updated.
Copy or move contact:
khard copy [-a source_abook] [-u uid|search terms [search terms ...]] [-A target_abook]
khard move [-a source_abook] [-u uid|search terms [search terms ...]] [-A target_abook]
Remove contact:
khard remove [-a addr_name] [-u uid|search terms [search terms ...]]
Davcontroller¶
Khard also contains a helper script called davcontroller. It’s designed to create and remove address books and calendars at the server. I have created davcontroller cause my previously used CalDAV server (Darwin calendarserver) offered no simple way to create new address books and calendars. But davcontroller should be considered as a hacky solution and it’s only tested against the Darwin calendarserver. So if your CalDAV server offers a way to create new address books and calendars I recommend to prefer that method over davcontroller.
If you nonetheless want to try davcontroller, you have to install the CalDAVClientLibrary first. Unfortunately that library isn’t compatible to python3 so you have to create an extra python2 virtual environment and install in there:
# create python2 virtual environment
virtualenv -p python2 ~/.virtualenvs/davcontroller
# get library from svn repository
sudo aptitude install subversion
svn checkout http://svn.calendarserver.org/repository/calendarserver/CalDAVClientLibrary/trunk CalDAVClientLibrary
cd CalDAVClientLibrary
# install library
~/.virtualenvs/davcontroller/bin/python setup.py install
# start davcontroller script
~/.virtualenvs/davcontroller/bin/python /path/to/khard-x.x.x/misc/davcontroller/davcontroller.py
This small script helps to create and remove new address books and calendars at the carddav and caldav server.
List available resources:
davcontroller -H example.com -p 11111 -u USERNAME -P PASSWORD list
Possible actions are: list, new-addressbook, new-calendar and remove. After creating or removing you must adapt your vdirsyncer config.
Contributing¶
Thank you for considering contributing to khard!
Benchmarking, profiling and performance¶
When benchmarking code it is important to reduce other load on the system
(music player, web browser for example).  One can use the python timeit
module or a command line utility like hyperfine:
python -m timeit -s 'from khard.khard import main' 'main(["list"])'
hyperfine 'python -m khard list'
For profiling the cProfile python module works well.  With the help of
gprof2dot one can generate quite useful graphs:
python -m cProfile -o output.file -m khard list
gprof2dot -f pstats --show-samples output.file | dot -T png > graph.png
xdg-open graph.png
Khard is developed on Github where you are welcome to post bug reports, feature requests or join the discussion in general.
Bug reports¶
If you want to report a bug keep in mind that the following things make it much easier for maintainers to help:
- update to the latest version if possible and verify the bug there 
- report the version(s) that are affected 
- state the python version you are using 
- if there are stack tracebacks post them with your bug report 
- supply a minimal configuration (config file and vcards) to reproduce the error 
Feature requests¶
Please stick to the following standards when you open pull requests:
- Khard’s development tries to follow Vincent’s branching model so normal pull requests should be made against the develop branch. Only important bug fixes that affect the current release should be opened against master. 
- Write “good” commit messages, especially a proper subject line. This is also explained in the Git book. 
- Format your python code according to PEP 8. 
- Khard has a test suite, please provide tests for bugs that you fix and also for new code and new features that are introduced. 
- Please verify all tests pass before sending a pull request, they will be checked again by travis but it might be a lot faster to check locally first: 
Development¶
In order to start coding you need to fetch the develop branch:
git clone https://github.com/scheibler/khard
cd khard
git fetch --all
git checkout develop
python -m kard --help
# or
pip3 install --editable .
khard --help
Alternatively you can use the setup.py script directly.  If you want to
isolate khard from your system Python environment you can use a virtualenv
to do so.
Manpages¶
The following man pages are available for khard:
khard¶
Synopsis¶
khard [-c CONFIG] [–debug] [–skip-unparsable] SUBCOMMAND …
khard -h|–help
khard -v|–version
Description¶
Khard is an address book for the Linux command line. It can read, create, modify and delete carddav address book entries. Khard only works with a local store of VCARD files. It is intended to be used in conjunction with other programs like an email client, text editor, vdir synchronizer or VOIP client.
Options¶
- -c CONFIG, --config CONFIG
- configuration file (default: ~/.config/khard/khard.conf) 
- --debug
- output debugging information 
- --skip-unparsable
- skip unparsable vcards when reading the address books 
Subcommands¶
The functionality of khard is divided into several subcommands.  All of these
have their own help text which can be seen with khard SUBCOMMAND --help.
Listing subcommands¶
These subcommands list information of several contacts who match a search query.
- list
- list all (selected) contacts 
- birthdays
- list birthdays (sorted by month and day) 
- list email addresses 
- phone
- list phone numbers 
- postaddress
- list postal addresses 
- filename
- list filenames of all matching contacts 
Detailed display¶
These subcommands display detailed information about one subcommand.
- details
- display detailed information about one contact 
- export
- export a contact to the custom yaml format that is also used for editing and creating contacts 
Modifying subcommands¶
These subcommands are used to modify contacts.
- source
- edit the vcard file of a contact directly 
- new
- create a new contact 
- add-email
- Extract email address from the “From:” field of an email header and add to an existing contact or create a new one 
- merge
- merge two contacts 
- modify
- edit the data of a contact 
- copy
- copy a contact to a different addressbook 
- move
- move a contact to a different addressbook 
- remove
- remove a contact 
Other subcommands¶
- addressbooks
- list all address books 
Configuration¶
See khard.conf(5).
khard.conf¶
Summary¶
The config file for khard is a plain text file with an ini-like syntax. Many options have a corresponding command line option. The only mandatory section in the config file is the definition of the available address books.
Location¶
The file is looked up at $XDG_CONFIG_HOME/khard/khard.conf. If the
environment variable $XDG_CONFIG_HOME is unset ~/.config/ is
used in its stead.
The location can be changed with the environment variable $KHARD_CONFIG
or the command line option -c (which takes precedence).
Syntax¶
The syntax of the config file is ini-style dialect. It is parsed with the configobj library. The precise definition of the corresponding ini syntax can be found at https://configobj.readthedocs.io/en/latest/configobj.html#the-config-file-format .
It supports sections marked with square brackets and nested sections with more square brackets. Each section contains several keys with values delimited by equal signs. The values are typed and type checked.
Options¶
The config file consists of these four sections:
- adressbooks
- This section contains several subsections, but at least one. Each subsection can have an arbitrary name which will be the name of an addressbook known to khard. Each of these subsections must have a path key with the path to the folder containing the vcard files for that addressbook. 
- general
- This section allows one to configure some general features about khard. The following keys are available in this section: - debug: a boolean indication weather the logging level should be set to debug by default (same effect as the - --debugoption on the command line)
- default_action: the default action/subcommand to use if the first non option argument does not match any of the available subcommands 
- editor: the text editor to use to edit address book entries, if not given - $EDITORwill be used
- merge_editor: a command used to merge two cards interactively, if not given, - $MERGE_EDITORwill be used
 
- contact table
- This section is used to configure the behaviour of different output listings of khard. The following keys are available: - display: which part of the name to use in listings; this can be one of - first_name,- last_nameor- formatted_name
- group_by_addressbook: weather or not to group contacts by address book in listings 
- localize_dates: weather to localize dates or to use ISO date formats 
- preferred_email_address_type: labels of email addresses to prefer 
- preferred_phone_number_type: labels of telephone numbers to prefer 
- reverse: weather to reverse the order of contact listings or not 
- show_nicknames: weather to show nick names 
- show_uids: weather to show uids 
- sort: field by which to sort contact listings 
 
- vcard
- private_objects: a list of strings, these are the names of private vCard fields (starting with - X-) that will be loaded and displayed by khard
- search_in_source_files: weather to search in the vcard files before parsing them in order to speed up searches 
- skip_unparsable: weather to skip unparsable vcards, otherwise khard exits on the first unparsable card it encounters 
- preferred_version: the preferred vcard version to use for new cards 
 
Example¶
This is the example config file:
# example configuration file for khard version > 0.14.0
# place it under ~/.config/khard/khard.conf
[addressbooks]
[[family]]
path = ~/.contacts/family/
[[friends]]
path = ~/.contacts/friends/
[general]
debug = no
default_action = list
# These are either strings or comma seperated lists
editor = vim, -i, NONE
merge_editor = vimdiff
[contact table]
# display names by first or last name: first_name / last_name / formatted_name
display = first_name
# group by address book: yes / no
group_by_addressbook = no
# reverse table ordering: yes / no
reverse = no
# append nicknames to name column: yes / no
show_nicknames = no
# show uid table column: yes / no
show_uids = yes
# sort by first or last name: first_name / last_name / formatted_name
sort = last_name
# localize dates: yes / no
localize_dates = yes
# set a comma separated list of preferred phone number types in descending priority
# or nothing for non-filtered alphabetical order
preferred_phone_number_type = pref, cell, home
# set a comma separated list of preferred email address types in descending priority
# or nothing for non-filtered alphabetical order
preferred_email_address_type = pref, work, home
[vcard]
# extend contacts with your own private objects
# these objects are stored with a leading "X-" before the object name in the vcard files
# every object label may only contain letters, digits and the - character
# example:
#   private_objects = Jabber, Skype, Twitter
private_objects = Jabber, Skype, Twitter
# preferred vcard version: 3.0 / 4.0
preferred_version = 3.0
# Look into source vcf files to speed up search queries: yes / no
search_in_source_files = no
# skip unparsable vcard files: yes / no
skip_unparsable = no
khard¶
khard package¶
Submodules¶
khard.actions module¶
Names and aliases for the subcommands on the command line
- 
class khard.actions.Actions¶
- Bases: - object- A class to manage the names and aliases of the command line subcommands. - 
action_map= {'add-email': [], 'addressbooks': ['abooks'], 'birthdays': ['bdays'], 'copy': ['cp'], 'edit': ['modify', 'ed'], 'email': [], 'export': [], 'filename': ['file'], 'list': ['ls'], 'merge': [], 'move': ['mv'], 'new': ['add'], 'phone': [], 'postaddress': ['post', 'postaddr'], 'remove': ['delete', 'del', 'rm'], 'show': ['details'], 'source': ['src'], 'template': []}¶
 - 
classmethod get_action(alias)¶
- Find the name of the action for the supplied alias. If no action is asociated with the given alias, None is returned. - Parameters
- alias (str) – the alias to look up 
- Rturns
- the name of the corresponding action or None 
- Return type
- str or NoneType 
 
 - 
classmethod get_actions()¶
- Find the names of all defined actions. - Returns
- all action names 
- Return type
- iterable(str) 
 
 - 
classmethod get_aliases(action)¶
- Find all aliases for the given action. If there is no such action, None is returned. - Parameters
- action (str) – the action name to look up 
- Returns
- the list of aliases corresponding to the action or None 
- Return type
- list(str) or NoneType 
 
 - 
classmethod get_all()¶
- Find the names of all defined actions and their aliases. - Returns
- the names of all actions and aliases 
- Return type
- generator(str) 
 
 
- 
khard.address_book module¶
A simple class to load and manage the vcard files from disk.
- 
class khard.address_book.AddressBook(name, private_objects=(), localize_dates=True, skip=False)¶
- Bases: - object- The base class of all address book implementations. - 
get_short_uid(uid)¶
- Get the shortend UID for the given UID. - Parameters
- uid (str) – the full UID to shorten 
- Returns
- the shortend uid or the empty string 
- Return type
- str 
 
 - 
get_short_uid_dict(query=None)¶
- Create a dictionary of shortend UIDs for all contacts. - All arguments are only used if the address book is not yet initialized and will just be handed to self.load(). - Parameters
- query (str) – see self.load() 
- Returns
- the contacts mapped by the shortes unique prefix of their UID 
- Return type
- dict(str: CarddavObject) 
 
 - 
abstract load(query=None)¶
- Load the vCards from the backing store. - If a query is given loading is limited to entries which match the query. If the query is None all entries will be loaded. - Parameters
- query (str) – the query to limit loading to matching entries 
- Returns
- the number of loaded contacts and the number of errors 
- Return type
- (int, int) 
 
 - 
search(query, method='all')¶
- Search this address book for contacts matching the query. - The method can be one of “all”, “name” and “uid”. The backend for this address book migth be load()ed if needed. - Parameters
- query (str) – the query to search for 
- method (str) – the type of fileds to use when seaching 
 
- Returns
- all found contacts 
- Return type
 
 
- 
- 
class khard.address_book.AddressBookCollection(name, abooks, **kwargs)¶
- Bases: - khard.address_book.AddressBook- A collection of several address books. - This represents a temporary merege of the contact collections provided by the underlying adress books. On load all contacts from all subadressbooks are copied into a dict in this address book. This allow this class to use all other methods from the parent AddressBook class. - 
get_abook(name)¶
- Get one of the backing abdress books by its name, - Parameters
- name (str) – the name of the address book to get 
- Returns
- the matching address book or None 
- Return type
- AddressBook or NoneType 
 
 - 
load(query=None)¶
- Load the vCards from the backing store. - If a query is given loading is limited to entries which match the query. If the query is None all entries will be loaded. - Parameters
- query (str) – the query to limit loading to matching entries 
- Returns
- the number of loaded contacts and the number of errors 
- Return type
- (int, int) 
 
 
- 
- 
exception khard.address_book.AddressBookParseError(filename, abook, reason, *args, **kwargs)¶
- Bases: - Exception- Indicate an error while parsing data from an address book backend. 
- 
class khard.address_book.VdirAddressBook(name, path, **kwargs)¶
- Bases: - khard.address_book.AddressBook- An AddressBook implementation based on a vdir. - This address book can load contacts from vcard files that reside in one direcotry on disk. - 
load(query=None, search_in_source_files=False)¶
- Load all vcard files in this address book from disk. - If a search string is given only files which contents match that will be loaded. - Parameters
- query (str) – a regular expression to limit the results 
- search_in_source_files (bool) – apply search regexp directly on the .vcf files to speed up parsing (less accurate) 
 
- Returns
- the number of successfully loaded cards and the number of errors 
- Return type
- int, int 
- Throws
- AddressBookParseError 
 
 
- 
khard.carddav_object module¶
Classes and logic to handle vCards in khard.
This module explicitly supports the vCard specifications version 3.0 and 4.0 which can be found here: - version 3.0: https://tools.ietf.org/html/rfc2426 - version 4.0: https://tools.ietf.org/html/rfc6350
- 
class khard.carddav_object.CarddavObject(vcard, address_book, filename, supported_private_objects=None, vcard_version=None, localize_dates=False)¶
- Bases: - khard.carddav_object.YAMLEditable- 
classmethod clone_with_yaml_update(contact, yaml, localize_dates=False)¶
- Use this if you want to clone an existing contact and replace its data with new user input in one step. 
 - 
delete_vcard_file()¶
 - 
classmethod from_file(address_book, filename, query, supported_private_objects=None, localize_dates=False)¶
- Load a CarddavObject object from a .vcf file if the plain file matches the query. - Parameters
- address_book (address_book.AddressBook) – the address book where this contact is stored 
- filename (str) – the file name of the .vcf file 
- query (re.Pattern|str|NoneType) – the regex to search in the source file or None to load the file unconditionally 
- supported_private_objects (list(str)|NoneType) – the list of private property names that will be loaded from the actual vcard and represented in this pobject 
- vcard_version (str|NoneType) – the version of the RFC to use 
- localize_dates (bool) – should the formatted output of anniversary and birthday be localized or should the isoformat be used instead 
 
- Returns
- the loaded CarddavObject or None if the file didn’t match 
- Return type
- CarddavObject or NoneType 
 
 - 
classmethod from_yaml(address_book, yaml, supported_private_objects=None, version=None, localize_dates=False)¶
- Use this if you want to create a new contact from user input. 
 - 
classmethod new(address_book, supported_private_objects=None, version=None, localize_dates=False)¶
- Create a new CarddavObject from scratch 
 - 
print_vcard(show_address_book=True, show_uid=True)¶
 - 
write_to_file(overwrite=False)¶
 
- 
classmethod 
- 
class khard.carddav_object.VCardWrapper(vcard, version=None)¶
- Bases: - object- Wrapper class around a vobject.vCard object. - This class can wrap a single vCard and presents its data in a manner suitable for khard. Additionally some details of the vCard specifications in RFC 2426 (version 3.0) and RFC 6350 (version 4.0) that are not enforced by the vobject library are enforced here. - 
add_email(type, address)¶
 - 
address_types_v3= ('dom', 'intl', 'home', 'parcel', 'postal', 'work')¶
 - 
address_types_v4= ('home', 'work')¶
 - 
property anniversary¶
- Returns
- contacts anniversary or None if not available 
- Return type
- datetime.datetime or str 
 
 - 
property birthday¶
- Return the birthday as a datetime object or a string depending on weather it is of type text or not. If no birthday is present in the vcard None is returned. - Returns
- contacts birthday or None if not available 
- Return type
- datetime.datetime or str or NoneType 
 
 - 
property categories¶
- Return type
- list(str) or list(list(str)) 
 
 - 
email_types_v3= ('home', 'internet', 'work', 'x400')¶
 - 
email_types_v4= ('home', 'internet', 'work')¶
 - 
property emails¶
- Returns
- dict of type and email address list 
- Return type
- dict(str, list(str)) 
 
 - 
property formatted_name¶
 - 
get_first_name_last_name()¶
- Return type
- str 
 
 - 
get_formatted_post_addresses()¶
 - 
get_last_name_first_name()¶
- Return type
- str 
 
 - 
property nicknames¶
- Return type
- list(str or dict(str)) 
 
 - 
property notes¶
- Return type
- list(str or dict(str)) 
 
 - 
property organisations¶
- Returns
- list of organisations, sorted alphabetically 
- Return type
- list(list(str) or dict(list(str))) 
 
 - 
property phone_numbers¶
- Returns
- dict of type and phone number list 
- Return type
- dict(str, list(str)) 
 
 - 
phone_types_v3= ('bbs', 'car', 'cell', 'fax', 'home', 'isdn', 'msg', 'modem', 'pager', 'pcs', 'video', 'voice', 'work')¶
 - 
phone_types_v4= ('text', 'voice', 'fax', 'cell', 'video', 'pager', 'textphone', 'home', 'work')¶
 - 
property post_addresses¶
- Returns
- dict of type and post address list 
- Return type
- dict(str, list(dict(str,list|str))) 
 
 - 
property roles¶
- Return type
- list(str or dict(str)) 
 
 - 
property titles¶
- Return type
- list(str or dict(str)) 
 
 - 
property uid¶
 - 
property version¶
 - 
property webpages¶
- Return type
- list(str or dict(str)) 
 
 
- 
- 
class khard.carddav_object.YAMLEditable(vcard, supported_private_objects=None, version=None, localize_dates=False)¶
- Bases: - khard.carddav_object.VCardWrapper- Conversion of vcards to YAML and updateing the vcard from YAML - 
get_formatted_anniversary()¶
 - 
get_formatted_birthday()¶
 - 
get_template()¶
 - 
update(input)¶
- Update this vcard with some yaml input - Parameters
- input (str) – a yaml string to parse and then use to update self 
- Returns
- None 
 
 
- 
- 
khard.carddav_object.convert_to_vcard(name, value, allowed_object_type)¶
- converts user input into vcard compatible data structures - Parameters
- name (str) – object name, only required for error messages 
- value (str or list(str)) – user input 
- allowed_object_type (enum of type ObjectType) – set the accepted return type for vcard attribute 
 
- Returns
- cleaned user input, ready for vcard or a ValueError 
- Return type
- str or list(str) 
 
- 
khard.carddav_object.multi_property_key(item)¶
- key function to pass to sorted(), allowing sorting of dicts with lists and strings. Dicts will be sorted by their label, after other types. - Parameters
- item (a dict with a single entry or any sortable type) – member of the list being sorted 
- Returns
- a list with two members. The first is int(isinstance(item, dict). The second is either the key from the dict or the unchanged item if it is not a dict. 
 - :rtype list(int, type(item)) or list(int, str) 
khard.cli module¶
Command line parsing and configuration logic for khard
- 
khard.cli.create_parsers()¶
- Create two argument parsers. - The first parser is manly used to find the config file which can than be used to set some default values on the second parser. The second parser can parse the remainder of the command line with the subcommand and all further options and arguments. - Returns
- the two parsers for the first and the second parsing pass 
- Return type
- (argparse.ArgumentParser, argparse.ArgumentParser) 
 
- 
khard.cli.init(argv)¶
- Initialize khard by parsing the command line and reading the config file - Parameters
- argv (list(str)) – the command line arguments 
- Returns
- the parsed command line and the fully initialized config 
- Return type
- (argparse.Namespace, Config) 
 
- 
khard.cli.merge_args_into_config(args, config)¶
- Merge the parsed arguments from argparse into the config object. - Parameters
- args (argparse.Namespace) – the parsed command line arguments 
- config (config.Config) – the parsed config file 
 
- Returns
- the merged config object 
- Return type
 
- 
khard.cli.parse_args(argv)¶
- Parse the command line arguments and return the namespace that was creates by argparse.ArgumentParser.parse_args(). - Parameters
- argv (list(str)) – the command line arguments 
- Returns
- the namespace parsed from the command line 
- Return type
- argparse.Namespace 
 
khard.config module¶
Loading and validation of the configuration file
- 
class khard.config.Config(config_file=None)¶
- Bases: - object- 
load_address_books()¶
 - 
merge(other)¶
- Merge the config with some other dict or ConfigObj - Parameters
- other – the other dict or ConfigObj to merge into self 
- Returns
- None 
 
 - 
supported_vcard_versions= ('3.0', '4.0')¶
 
- 
- 
khard.config.exit(message, prefix='Error in config file\n')¶
- Exit with a message and a return code indicating an error in the config file. - This function doesn’t return, it calls sys.exit. - Parameters
- message (str) – the message to print 
- prefix (str) – the prefix to put in front of the message 
 
- Returns
- does not return 
 
- 
khard.config.validate_action(value)¶
- Check that the given value is a valid action. - Parameters
- value – the config value to check 
- Returns
- the same value 
- Return type
- str 
- Raises
- validate.ValidateError 
 
- 
khard.config.validate_command(value)¶
- Special validator to check shell commands - The input must either be a list of strings or a string that shlex.split can parse into such. - Parameters
- value – the config value to validate 
- Returns
- the command after validation 
- Return type
- list(str) 
- Raises
- validate.ValidateError 
 
- 
khard.config.validate_private_objects(value)¶
- Check that the private objects are reasonable - Parameters
- value – the config value to check 
- Returns
- the list of private objects 
- Return type
- list(str) 
- Raises
- validate.ValidateError 
 
khard.helpers module¶
Some helper functions for khard
- 
khard.helpers.convert_to_yaml(name, value, indentation, index_of_colon, show_multi_line_character)¶
- converts a value list into yaml syntax - Parameters
- name (str) – name of object (example: phone) 
- value (str, list(str), list(list(str)), list(dict)) – object contents 
- indentation (int) – indent all by number of spaces 
- index_of_colon (int) – use to position : at the name string (-1 for no space) 
- show_multi_line_character (bool) – option to hide “|” 
 
- Returns
- yaml formatted string array of name, value pair 
- Return type
- list(str) 
 
- 
khard.helpers.file_modification_date(filename)¶
- 
khard.helpers.get_new_contact_template(supported_private_objects=None)¶
- 
khard.helpers.get_random_uid()¶
- 
khard.helpers.indent_multiline_string(input, indentation, show_multi_line_character)¶
- 
khard.helpers.list_to_string(input, delimiter)¶
- converts list to string recursively so that nested lists are supported - Parameters
- input (list) – a list of strings and lists of strings (and so on recursive) 
- delimiter (str) – the deimiter to use when joining the items 
 
- Returns
- the recursively joined list 
- Return type
- str 
 
- 
khard.helpers.pretty_print(table, justify='L')¶
- 
khard.helpers.string_to_date(string)¶
- Convert a date string into a date object. - Parameters
- string (str) – the date string to parse 
- Returns
- the parsed datetime object 
- Return type
- datetime.datetime 
 
- 
khard.helpers.string_to_list(input, delimiter)¶
khard.khard module¶
Main application logic of khard includeing command line handling
- 
khard.khard.add_email_subcommand(text, abooks)¶
- Add a new email address to contacts, creating new contacts if necessary. - Parameters
- text (str) – the input text to search for the new email 
- abooks (list of address_book.AddressBook) – the addressbooks that were selected on the command line 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.birthdays_subcommand(vcard_list, parsable)¶
- Print birthday contact table. - Parameters
- vcard_list (list of carddav_object.CarddavObject) – the vcards to search for matching entries which should be printed 
- parsable (bool) – machine readable output: columns devided by tabulator ( ) 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.choose_address_book_from_list(header_string, address_book_list)¶
- 
khard.khard.choose_vcard_from_list(header_string, vcard_list, include_none=False)¶
- 
khard.khard.copy_contact(contact, target_address_book, delete_source_contact)¶
- 
khard.khard.copy_or_move_subcommand(action, vcard_list, target_address_book_list)¶
- Copy or move a contact to a different address book. - Action
- the string “copy” or “move” to indicate what to do 
- Parameters
- vcard_list (list of carddav_object.CarddavObject) – the contact list from which to select one for the action 
- target_address_book_list (list(addressbook.AddressBook)) – the list of target address books 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.create_new_contact(address_book)¶
- 
khard.khard.edit(*filenames, merge=False)¶
- Edit the given files with the configured editor or merge editor 
- 
khard.khard.email_subcommand(search_terms, vcard_list, parsable, remove_first_line)¶
- Print a mail client friendly contacts table that is compatible with the default format used by mutt. Output format: - single line of text email_address name type email_address name type [...] - Parameters
- search_terms (str) – used as search term to filter the contacts before printing 
- vcard_list (list of carddav_object.CarddavObject) – the vcards to search for matching entries which should be printed 
- parsable (bool) – machine readable output: columns devided by tabulator ( ) 
- remove_first_line (bool) – remove first line (searching for ‘’ …) 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.generate_contact_list(args)¶
- TODO: Docstring for generate_contact_list. - Parameters
- args (argparse.Namespace) – the command line arguments 
- Returns
- the contacts for further processing (TODO) 
- Return type
- list(TODO) 
 
- 
khard.khard.get_contact_list_by_user_selection(address_books, search, strict_search)¶
- returns a list of CarddavObject objects :param address_books: list of selected address books :type address_books: list(address_book.AddressBook) :param search: filter contact list :type search: str :param strict_search: if True, search only in full name field :type strict_search: bool :returns: list of CarddavObject objects :rtype: list(CarddavObject) 
- 
khard.khard.get_contacts(address_books, query, method='all', reverse=False, group=False, sort='first_name')¶
- Get a list of contacts from one or more address books. - Parameters
- address_books (list(address_book.AddressBook)) – the address books to search 
- query (str) – a search query to select contacts 
- method (str) – the search method, one of “all”, “name” or “uid” 
- reverse (bool) – reverse the order of the returned contacts 
- group (bool) – group results by address book 
- sort (str) – the field to use for sorting, one of “first_name”, “last_name”, “formatted_name” 
 
- Returns
- contacts from the address_books that match the query 
- Return type
- list(CarddavObject) 
 
- 
khard.khard.list_address_books(address_book_list)¶
- 
khard.khard.list_birthdays(birthday_list)¶
- 
khard.khard.list_contacts(vcard_list)¶
- 
khard.khard.list_email_addresses(email_address_list)¶
- 
khard.khard.list_phone_numbers(phone_number_list)¶
- 
khard.khard.list_post_addresses(post_address_list)¶
- 
khard.khard.list_subcommand(vcard_list, parsable)¶
- Print a user friendly contacts table. - Parameters
- vcard_list (list of carddav_object.CarddavObject) – the vcards to print 
- parsable (bool) – machine readable output: columns devided by tabulator ( ) 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.load_address_books(names, config, search_queries)¶
- Load all address books with the given names from the config. - Parameters
- names (list(str)) – the address books to load 
- config (config.Config) – the config instance to use when looking up address books 
- search_queries (dict) – a mapping of address book names to search queries 
 
- Yields
- the loaded address books 
- Ytype
- addressbook.AddressBook 
 
- 
khard.khard.main(argv=['-M', 'singlehtml', 'source', 'build'])¶
- 
khard.khard.merge_existing_contacts(source_contact, target_contact, delete_source_contact)¶
- 
khard.khard.merge_subcommand(vcard_list, selected_address_books, search_terms, target_uid)¶
- Merge two contacts into one. - Parameters
- vcard_list (list of carddav_object.CarddavObject) – the vcards from which to choose contacts for mergeing 
- selected_address_books (list(addressbook.AddressBook)) – the addressbooks to use to find the target contact 
- search_terms (str) – the search terms to find the target contact 
- target_uid (str) – the uid of the target contact or empty 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.modify_existing_contact(old_contact)¶
- 
khard.khard.modify_subcommand(selected_vcard, input_from_stdin_or_file, open_editor, source=False)¶
- Modify a contact in an external editor. - Parameters
- selected_vcard (carddav_object.CarddavObject) – the contact to modify 
- input_from_stdin_or_file (str) – new data from stdin (or a file) that should be incorperated into the contact, this should be a yaml formatted string 
- open_editor (bool) – whether to open the new contact in the edior after creation 
- source (bool) – edit the source file or a yaml version? 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.new_subcommand(selected_address_books, input_from_stdin_or_file, open_editor)¶
- Create a new contact. - Parameters
- selected_address_books (list of address_book.AddressBook) – a list of addressbooks that were selected on the command line 
- input_from_stdin_or_file (str) – the data for the new contact as a yaml formatted string 
- open_editor (bool) – whether to open the new contact in the edior after creation 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.phone_subcommand(search_terms, vcard_list, parsable)¶
- Print a phone application friendly contact table. - Parameters
- search_terms (str) – used as search term to filter the contacts before printing 
- vcard_list (list of carddav_object.CarddavObject) – the vcards to search for matching entries which should be printed 
- parsable (bool) – machine readable output: columns devided by tabulator ( ) 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.post_address_subcommand(search_terms, vcard_list, parsable)¶
- Print a contact table. with all postal / mailing addresses - Parameters
- search_terms (str) – used as search term to filter the contacts before printing 
- vcard_list (list of carddav_object.CarddavObject) – the vcards to search for matching entries which should be printed 
- parsable (bool) – machine readable output: columns devided by tabulator ( ) 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.prepare_search_queries(args)¶
- Prepare the search query string from the given command line args. - Each address book can get a search query string to filter vcards befor loading them. Depending on the question if the address book is used for source or target searches different regexes have to be combined into one search string. - Parameters
- args (argparse.Namespace) – the parsed command line 
- Returns
- a dict mapping abook names to their loading queries, if the query is None it means that all cards should be loaded 
- Return type
- dict(str:str or None) 
 
- 
khard.khard.remove_subcommand(selected_vcard, force)¶
- Remove a contact from the addressbook. - Parameters
- selected_vcard (carddav_object.CarddavObject) – the contact to delete 
- force (bool) – delete without confirmation 
 
- Returns
- None 
- Return type
- None 
 
- 
khard.khard.write_temp_file(text='')¶
- Create a new temporary file and write some initial text to it. - Parameters
- text (str) – the text to write to the temp file 
- Returns
- the file name of the newly created temp file 
- Return type
- str 
 
khard.object_type module¶
Helper module for validating typed vcard properties
khard.version module¶
Indices and tables¶
Khard is an address book for the Linux command line. It can read, create, modify and delete carddav address book entries. Khard only works with a local store of VCARD files. It is intended to be used in conjunction with other programs like an email client, text editor, vdir synchronizer or VOIP client.
Installation¶
Khard is available as a native package for some Linux distributions so you should check your package manager first. If you want or need to install manually you can use the release from PyPi:
pip3 install khard
If you want to help the development or need more advanced installation instructions see Contributing.
Configuration¶
The configuration file of khard is stored in the XDG conform config directory.
If the environment variable $XDG_CONFIG_HOME is set, it is
$XDG_CONFIG_HOME/khard/khard.conf and it defaults to
~/.config/khard/khard.conf otherwise.
A minimal configuration is provided in the source tree. It looks like this:
# example configuration file for khard version > 0.14.0
# place it under ~/.config/khard/khard.conf
[addressbooks]
[[family]]
path = ~/.contacts/family/
[[friends]]
path = ~/.contacts/friends/
[general]
debug = no
default_action = list
# These are either strings or comma seperated lists
editor = vim, -i, NONE
merge_editor = vimdiff
[contact table]
# display names by first or last name: first_name / last_name / formatted_name
display = first_name
# group by address book: yes / no
group_by_addressbook = no
# reverse table ordering: yes / no
reverse = no
# append nicknames to name column: yes / no
show_nicknames = no
# show uid table column: yes / no
show_uids = yes
# sort by first or last name: first_name / last_name / formatted_name
sort = last_name
# localize dates: yes / no
localize_dates = yes
# set a comma separated list of preferred phone number types in descending priority
# or nothing for non-filtered alphabetical order
preferred_phone_number_type = pref, cell, home
# set a comma separated list of preferred email address types in descending priority
# or nothing for non-filtered alphabetical order
preferred_email_address_type = pref, work, home
[vcard]
# extend contacts with your own private objects
# these objects are stored with a leading "X-" before the object name in the vcard files
# every object label may only contain letters, digits and the - character
# example:
#   private_objects = Jabber, Skype, Twitter
private_objects = Jabber, Skype, Twitter
# preferred vcard version: 3.0 / 4.0
preferred_version = 3.0
# Look into source vcf files to speed up search queries: yes / no
search_in_source_files = no
# skip unparsable vcard files: yes / no
skip_unparsable = no
Integration with other programs¶
Khard can be used together with email or SIP clients or a synchronisation program like vdirsyncer.
mutt¶
Khard may be used as an external address book for the email client mutt. To
accomplish that, add the following to your mutt config file (mostly
~/.mutt/muttrc):
set query_command= "khard email --parsable %s"
bind editor <Tab> complete-query
bind editor ^T    complete
Then you can complete email addresses by pressing the Tab-key in mutt’s new
mail dialog. If your address books contain hundreds or even thousands of
contacts and the query process is very slow, you may try the
--search-in-source-files option to speed up the search:
set query_command= "khard email --parsable --search-in-source-files %s"
If you want to complete multi-word search strings like “john smith” then you may try out the following instead:
set query_command = "echo %s | xargs khard email --parsable --"
To add email addresses to khard’s address book, you may also add the following lines to your muttrc file:
macro index,pager A \
  "<pipe-message>khard add-email<return>" \
  "add the sender email address to khard"
Then navigate to an email message in mutt’s index view and press “A” to start the address import dialog.
Alot¶
Add the following lines to your alot config file:
[accounts]
    [[youraccount]]
        [[[abook]]]
            type = shellcommand
            command = khard email --parsable
            regexp = '^(?P<email>[^@]+@[^\t]+)\t+(?P<name>[^\t]+)'
            ignorecase = True
Twinkle¶
For those who also use the SIP client twinkle to take phone calls, khard can be used to query incoming numbers. The plugin tries to find the incoming caller id and speaks it together with the phone’s ring tone. The plugin needs the following programs:
sudo aptitude install ffmpeg espeak sox mpc
sox and ffmpeg are used to cut and convert the new ring tone and espeak speaks
the caller id.  mpc is a client for the music player daemon (mpd). It’s
required to stop music during an incoming call. Skip the last, if you don’t use
mpd. Don’t forget to set the “stop_music”-parameter in the config.py file
to False, too.
After the installation, copy the scripts and sounds folders to your twinkle config folder:
cp -R misc/twinkle/* ~/.twinkle/
Then edit your twinkle config file (mostly ~/.twinkle/twinkle.cfg) like
this:
# RING TONES
# We need a default ring tone. Otherwise the phone would not ring at all, if
# something with the custom ring tone creation goes wrong.
ringtone_file=/home/USERNAME/.twinkle/sounds/incoming_call.wav
ringback_file=/home/USERNAME/.twinkle/sounds/outgoing_call.wav
# SCRIPTS
script_incoming_call=/home/USERNAME/.twinkle/scripts/incoming_call.py
script_in_call_answered=
script_in_call_failed=/home/USERNAME/.twinkle/scripts/incoming_call_failed.py
script_outgoing_call=
script_out_call_answered=
script_out_call_failed=
script_local_release=/home/USERNAME/.twinkle/scripts/incoming_call_ended.py
script_remote_release=/home/USERNAME/.twinkle/scripts/incoming_call_ended.py
Zsh¶
The file misc/zsh/_khard contains a khard cli completion function for the
zsh and misc/zsh/_email-khard completes email addresses.
Install by copying to a directory where zsh searches for completion functions
(the $fpath array). If you, for example, put all completion functions into
the folder ~/.zsh/completions you must add the following to your zsh main
config file:
fpath=( $HOME/.zsh/completions $fpath )
autoload -U compinit
compinit
sdiff¶
Use the wrapper script misc/sdiff/sdiff_khard_wrapper.sh if you want to use
sdiff as your contact merging tool. Just make the script executable and set it
as your merge editor in khard’s config file:
merge_editor = /path/to/sdiff_khard_wrapper.sh