10 August 2011

Wikipedia OpenSearch and semantic bash completion

I wrote a tool that use the opensearch API for mediawiki to display the results of a query in wikipedia:

$ opensearch Charles Darw
Charles_Darwin Charles Robert Darwin FRS (12 February 1809 – 19 April 1882) was an English...
Charles_Darwin_University Charles Darwin University (CDU) is an Australian public university wi...
Charles_Darwin%27s_health For much of his adult life, Charles Darwin's health was repeatedly co...
Charles_Darwin_Foundation The Charles Darwin Foundation was founded in 1959, under the auspices...
Charles_Darwin_National_Park Charles Darwin National Park is in the Northern Territory of Austr...
Charles_Darwin_Research_Station The Charles Darwin Research Station (CDRS) is a biological rese...
Charles_Darwin%27s_education Charles Darwin's education gave him a foundation in the doctrine o...
Charles_Darwin_%281758%E2%80%931778%29 Charles Darwin (3 September 1758–15 May 1778) was the ...
Charles_Darwin%27s_religious_views Charles Darwin's views on religion have been the subject of ...
Charles_Darwin_and_the_Tree_of_Life Charles Darwin and the Tree of Life is a 2009 television do...
Charles_Darwin_School Charles Darwin School is the only secondary school in the Biggin Hill area.
Charles_Darwin_%28aviator%29 Major Charles John Wharton Darwin was a First World War flying ace...
Charles_Darwin_Reserve Charles Darwin Reserve is a 686 km2 nature reserve in Western Australia.
Charles_Darwin_bibliography This is a partial list of the writings of Charles Darwin, including...
Darwin Darwin may refer to:


This tool is available on github at:

Bash completion

Now I want to use this tool for bash completion. Say, I wrote a tool named 'foo' that expects the title of a wikipedia article as an argument. In ~/.bash_completion.d/, I wrote a file named opensearch:
_opensearch()

{
local cur choice reply
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
choice=$(opensearch -d -c ${cur})
reply=$(compgen -W "${choice}" -- ${cur})
COMPREPLY=( $reply )
return 0
} &&

complete -F _opensearch foo

This script is activated when a new terminal is loaded in ${HOME}/.bashrc:
(...)
if [ -f ${HOME}/.bash_completion.d/opensearch ]; then
. ${HOME}/.bash_completion.d/opensearch
fi
Now, typing 'foo', a keyword and <TAB> activates this new completion:
$ foo Charles_D <TAB> <TAB>

Charles_Dance Charles_Darwin_University Charles_Doolittle_Walcott Charles_Dutoit
Charles_Darwin Charles_Dickens Charles_Durning
$ foo Charles_D


That's it,

Pierre

No comments: