my shell and tool configurations
1# -*- coding: utf-8 -*-
2###
3# Copyright (c) 2010 by Elián Hanisch <lambdae2@gmail.com>
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 3 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program. If not, see <http://www.gnu.org/licenses/>.
17###
18
19###
20#
21# This scripts adds word completion, like irssi's /completion
22# (depends on WeeChat 0.3.1 or newer)
23#
24# Commands:
25# * /completion: see /help completion
26#
27#
28# Settings:
29# * plugins.var.python.completion.replace_values:
30# Completion list, it shouldn't be edited by hand.
31#
32#
33# History:
34# 2019-08-20
35# version 0.3: Ben Harris (benharri)
36# * port for python3
37#
38# 2010-05-08
39# version 0.2:
40# * complete any word behind the cursor, not just the last one in input line.
41# * change script display name 'completion' to 'cmpl'.
42#
43# 2010-01-26
44# version 0.1: release
45#
46###
47
48try:
49 import weechat
50 WEECHAT_RC_OK = weechat.WEECHAT_RC_OK
51 import_ok = True
52except ImportError:
53 print("This script must be run under WeeChat.")
54 print("Get WeeChat now at: http://www.weechat.org/")
55 import_ok = False
56
57SCRIPT_NAME = "completion"
58SCRIPT_AUTHOR = "Elián Hanisch <lambdae2@gmail.com>"
59SCRIPT_VERSION = "0.3"
60SCRIPT_LICENSE = "GPL3"
61SCRIPT_DESC = "Word completions for WeeChat"
62SCRIPT_COMMAND = "completion"
63
64### Config ###
65settings = {
66'replace_values':''
67}
68
69### Messages ###
70def debug(s, prefix='', buffer=None):
71 """Debug msg"""
72 #if not weechat.config_get_plugin('debug'): return
73 if buffer is None:
74 buffer_name = 'DEBUG_' + SCRIPT_NAME
75 buffer = weechat.buffer_search('python', buffer_name)
76 if not buffer:
77 buffer = weechat.buffer_new(buffer_name, '', '', '', '')
78 weechat.buffer_set(buffer, 'nicklist', '0')
79 weechat.buffer_set(buffer, 'time_for_each_line', '0')
80 weechat.buffer_set(buffer, 'localvar_set_no_log', '1')
81 weechat.prnt(buffer, '%s\t%s' %(prefix, s))
82
83def error(s, prefix=None, buffer='', trace=''):
84 """Error msg"""
85 prefix = prefix or script_nick
86 weechat.prnt(buffer, '%s%s %s' %(weechat.prefix('error'), prefix, s))
87 if weechat.config_get_plugin('debug'):
88 if not trace:
89 import traceback
90 if traceback.sys.exc_type:
91 trace = traceback.format_exc()
92 not trace or weechat.prnt('', trace)
93
94def say(s, prefix=None, buffer=''):
95 """normal msg"""
96 prefix = prefix or script_nick
97 weechat.prnt(buffer, '%s\t%s' %(prefix, s))
98
99print_replace = lambda k,v : say('%s %s=>%s %s' %(k, color_delimiter, color_reset, v))
100
101### Config functions ###
102def get_config_dict(config):
103 value = weechat.config_get_plugin(config)
104 if not value:
105 return {}
106 values = [s.split('=>') for s in value.split(';;')]
107 #debug(values)
108 return dict(values)
109
110def load_replace_table():
111 global replace_table
112 replace_table = dict(get_config_dict('replace_values'))
113
114def save_replace_table():
115 global replace_table
116 weechat.config_set_plugin('replace_values',
117 ';;'.join(['%s=>%s' %(k, v) for k, v in replace_table.items()]))
118
119### Commands ###
120def cmd_completion(data, buffer, args):
121 global replace_table
122 if not args:
123 if replace_table:
124 for k, v in replace_table.items():
125 print_replace(k, v)
126 else:
127 say('No completions.')
128 return WEECHAT_RC_OK
129 cmd, space, args = args.partition(' ')
130 if cmd == 'add':
131 word, space, text = args.partition(' ')
132 k, v = word.strip(), text.strip()
133 replace_table[k] = v
134 save_replace_table()
135 say('added: %s %s=>%s %s' %(k, color_delimiter, color_reset, v))
136 elif cmd == 'del':
137 k = args.strip()
138 try:
139 del replace_table[k]
140 save_replace_table()
141 say("completion for '%s' deleted." %k)
142 save_replace_table()
143 except KeyError:
144 error("completion for '%s' not found." %k)
145 return WEECHAT_RC_OK
146
147### Completion ###
148def completion_replacer(data, completion_item, buffer, completion):
149 global replace_table
150 pos = weechat.buffer_get_integer(buffer, 'input_pos')
151 input = weechat.buffer_get_string(buffer, 'input')
152 #debug('%r %s %s' %(input, len(input), pos))
153 if pos > 0 and (pos == len(input) or input[pos] == ' '):
154 n = input.rfind(' ', 0, pos)
155 word = input[n+1:pos]
156 #debug(repr(word))
157 if word in replace_table:
158 replace = replace_table[word]
159 if pos >= len(input.strip()):
160 # cursor is in the end of line, append a space
161 replace += ' '
162 n = len(word)
163 input = '%s%s%s' %(input[:pos-n], replace, input[pos:])
164 weechat.buffer_set(buffer, 'input', input)
165 weechat.buffer_set(buffer, 'input_pos', str(pos - n + len(replace)))
166 return WEECHAT_RC_OK
167
168def completion_keys(data, completion_item, buffer, completion):
169 global replace_table
170 for k in replace_table:
171 weechat.hook_completion_list_add(completion, k, 0, weechat.WEECHAT_LIST_POS_SORT)
172 return WEECHAT_RC_OK
173
174### Main ###
175if __name__ == '__main__' and import_ok and \
176 weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, \
177 SCRIPT_DESC, '', ''):
178
179 # colors
180 color_delimiter = weechat.color('chat_delimiters')
181 color_script_nick = weechat.color('chat_nick')
182 color_reset = weechat.color('reset')
183
184 # pretty [SCRIPT_NAME]
185 script_nick = '%s[%s%s%s]%s' %(color_delimiter, color_script_nick, 'cmpl', color_delimiter,
186 color_reset)
187
188 version = weechat.info_get('version', '')
189 if version == '0.3.0':
190 error('WeeChat 0.3.1 or newer is required for this script.')
191 else:
192 # settings
193 for opt, val in settings.items():
194 if not weechat.config_is_set_plugin(opt):
195 weechat.config_set_plugin(opt, val)
196
197 load_replace_table()
198
199 completion_template = 'completion_script'
200 weechat.hook_completion(completion_template,
201 "Replaces last word in input by its configured value.", 'completion_replacer', '')
202 weechat.hook_completion('completion_keys', "Words in completion list.", 'completion_keys', '')
203
204 weechat.hook_command(SCRIPT_COMMAND, SCRIPT_DESC , "[add <word> <text>|del <word>]",
205"""
206add: adds a new completion, <word> => <text>.
207del: deletes a completion.
208Without arguments it displays current completions.
209
210<word> will be replaced by <text> when pressing tab in input line,
211where <word> is any word currently behind the cursor.
212
213Setup:
214For this script to work, you must add the template
215%%(%(completion)s) to the default completion template, use:
216/set weechat.completion.default_template "%%(nicks)|%%(irc_channels)|%%(%(completion)s)"
217
218Examples:
219/%(command)s add wee WeeChat (typing wee<tab> will replace 'wee' by 'WeeChat')
220/%(command)s add weeurl http://www.weechat.org/
221/%(command)s add test This is a test!
222""" %dict(completion=completion_template, command=SCRIPT_COMMAND),
223 'add|del %(completion_keys)', 'cmd_completion', '')
224
225# vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=100: