2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
3
from __future__ import with_statement
6
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
7
__docformat__ = 'restructuredtext en'
11
BASH completion for calibre commands that are too complex for simple
15
import sys, os, shlex, glob, re
16
from functools import partial
18
from calibre import prints
20
debug = partial(prints, file=sys.stderr)
24
return shlex.split(src)
27
return shlex.split(src+'"')
29
return shlex.split(src+"'")
32
def files_and_dirs(prefix, allowed_exts=[]):
33
for i in glob.iglob(prefix+'*'):
34
_, ext = os.path.splitext(i)
35
ext = ext.lower().replace('.', '')
38
elif allowed_exts is None or ext in allowed_exts:
41
def get_opts_from_parser(parser, prefix):
43
for x in opt._long_opts:
44
if x.startswith(prefix):
46
for x in opt._short_opts:
47
if x.startswith(prefix):
49
for o in parser.option_list:
50
for x in do_opt(o): yield x
51
for g in parser.option_groups:
52
for o in g.option_list:
53
for x in do_opt(o): yield x
56
pat = re.compile('([^0-9a-zA-Z_./-])')
57
for x in sorted(set(ans)):
58
x = pat.sub(lambda m : '\\'+m.group(1), x)
65
class EbookConvert(object):
67
def __init__(self, comp_line, pos):
68
words = split(comp_line[:pos])
69
char_before = comp_line[pos-1]
70
prefix = words[-1] if words[-1].endswith(char_before) else ''
76
self.previous = words[-2 if prefix else -1]
79
def complete(self, wc):
83
self.complete_output()
85
from calibre.ebooks.conversion.cli import create_option_parser
86
from calibre.utils.logging import Log
90
if not self.prefix or self.prefix.startswith('-'):
92
parser, _ = create_option_parser(self.words[:3], log)
93
ans += list(get_opts_from_parser(parser, self.prefix))
96
if self.previous.startswith('-'):
97
ans += list(files_and_dirs(self.prefix, None))
100
def complete_input(self):
101
from calibre.ebooks.conversion.plumber import supported_input_formats
102
ans = list(files_and_dirs(self.prefix, supported_input_formats()))
103
from calibre.web.feeds.recipes import recipes
104
ans += [t.title+'.recipe ' for t in recipes if
105
(t.title+'.recipe').startswith(self.prefix)]
108
def complete_output(self):
109
from calibre.customize.ui import available_output_formats
110
fmts = available_output_formats()
111
ans = list(files_and_dirs(self.prefix, fmts))
112
ans += ['.'+x+' ' for x in fmts if ('.'+x).startswith(self.prefix)]
120
def main(args=sys.argv):
121
comp_line, pos = os.environ['COMP_LINE'], int(os.environ['COMP_POINT'])
122
module = split(comp_line)[0].split(os.sep)[-1]
123
if module == 'ebook-convert':
124
EbookConvert(comp_line, pos)
129
if __name__ == '__main__':
130
raise sys.exit(main())