commit 34c247d3c2a7961aeac7e51715454233a8c84474 Author: Roman Dobosz Date: Sat Jul 30 19:18:48 2016 +0200 Initial commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..68c771a --- /dev/null +++ b/LICENSE @@ -0,0 +1,176 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..fccd94f --- /dev/null +++ b/README.rst @@ -0,0 +1,50 @@ +weechat-replacer +================ + +Weechat plugin for replacing user defined keywords with specified text. + +Installation and configuration +------------------------------ + +In order to use it, you have to have Weechat with Python plugin support compiled +in. Than, copy ``replacer.py`` to ``~/.weechat/python/``. You can optionally +create symbolic link to this script: + +.. code:: shell-session + + ln -s ~/.weechat/python/replacer.py ~/.weechat/python/autoload/replacer.py + +Next, you need to add this *replacer_plugin* to Weechat completion template, so +it'll looks similar to: + +.. code:: + + /set weechat.completion.default_template "%(nicks)|%(irc_channels)|%(replacer_plugin)" + +Next, load the plugin (if you choose to not load it automatically): + +.. code:: + + /python load replacer.py + +Now you all set. + + +Usage +----- + +Abbreviations will be stored as json file ``~/.weechat/replacement_map.json``, +which role is to simply persist dictionary object on the filesystem. To add some +replacement words, and text which would those words replaced with: + +.. code:: + + /replacer add foo bar + +and than, when you type ``foo`` word and press ``tab`` key, you should get +``bar`` word instead. + +License +------- + +This plugin is on Apache 2 license. See LICENSE for details. diff --git a/replacer.py b/replacer.py new file mode 100644 index 0000000..eeb802b --- /dev/null +++ b/replacer.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +""" +Simple replacer for substitution one keyword with some text using completion +mechanism from weechat. + +add: add new replacement to table +del: remove key from table + +Without any argument list of defined substitution will be displayed. + +Script will replace any defined keyword with the text using tab completion. To +make this work, weechat.completion.default_template should be modified: + +/set weechat.completion.default_template "%%(nicks)|%%(irc_channels)|%%(replacer_plugin)" + +Examples: +/%(command)s add foo foobar +/%(command)s add testutf ½°C +/%(command)s del testutf +""" + +import os +import json + +import weechat + + +NAME = 'replacer' +AUTHOR = 'Roman Dobosz ' +VERSION = '1.0' +LICENSE = 'Apache 2' +DESC = 'Word replacer for WeeChat' +COMMAND = 'replacer' +REPLACE_FILE = os.path.expandvars("$HOME/.weechat/replacement_map.json") + +COLOR_DELIMITERS = weechat.color('chat_delimiters') +COLOR_NICK = weechat.color('chat_nick') +COLOR_RESET = weechat.color('reset') + + +class Replacer(object): + """Replacer""" + + # This will keep reference to created Replacer object. We need it only + # one, so it also could be global, but globals are bad, mkay? + self_object = None + + def __init__(self, path=None): + """Initialize plugin""" + self.replacement_map = {} + self._path = path + if not path: + self._path = REPLACE_FILE + self._get_replacement_map() + + def _get_replacement_map(self): + """Read json file, and assign it to the replacement_map attr""" + try: + with open(self._path) as fobj: + self.replacement_map = json.load(fobj) + except (IOError, ValueError): + pass + + def add(self, key, value): + """Add item to dict""" + self.replacement_map[key] = value + self._write_replacement_map() + + def delete(self, key): + """remove item from dict""" + try: + del self.replacement_map[key] + except KeyError: + return False + + self._write_replacement_map() + return True + + def _write_replacement_map(self): + """Write replacement table to json file""" + with open(self._path, "w") as fobj: + json.dump(self.replacement_map, fobj) + + +def echo(msg, weechat_buffer, prefix=False, **kwargs): + """ + Print preformated message. Note, that msg and arguments should be str not + unicode. + """ + display_msg = msg + + arg_dict = {'color_delimiters': COLOR_DELIMITERS, + 'color_nick': COLOR_NICK, + 'name': NAME, + 'color_reset': COLOR_RESET} + + if prefix: + display_msg = "%(symbol)s" + display_msg + arg_dict['symbol'] = weechat.prefix(prefix) + + arg_dict.update(kwargs) + weechat.prnt(weechat_buffer, display_msg % arg_dict) + + +def inject_replacer_object(fun): + """ + Decorator for injecting replacer object into weechat callback functions, + since weechat doesn't support assignment of object method + """ + def wrapper(*args, **kwargs): + """Wrapper""" + if not Replacer.self_object: + Replacer.self_object = Replacer() + return fun(Replacer.self_object, *args, **kwargs) + return wrapper + + +@inject_replacer_object +def replace_cmd(replacer_obj, _, weechat_buffer, args): + """/replacer command implementation""" + if not args: + if not replacer_obj.replacement_map: + echo("No replacements defined", weechat_buffer, 'error') + else: + echo("Defined replacements:", weechat_buffer, 'network') + + for key, value in sorted(replacer_obj.replacement_map.items()): + + echo('%(key)s %(color_delimiters)s->%(color_reset)s %(val)s', + weechat_buffer, key=key.encode('utf-8'), + val=value.encode('utf-8')) + + return weechat.WEECHAT_RC_OK + + cmd = args.split(' ')[0] + + if cmd not in ('add', 'del'): + echo('Error in command /%(command)s %(args)s (help on command: /help ' + '%(command)s)', weechat_buffer, 'error', args=args, + command=COMMAND) + return weechat.WEECHAT_RC_OK + + if cmd == 'add': + key = args.split(' ')[1].strip() + value = ' '.join(args.split(' ')[2:]).strip() + replacer_obj.add(key.decode('utf-8'), value.decode('utf-8')) + echo('added: %(key)s %(color_delimiters)s->%(color_reset)s %(val)s', + weechat_buffer, 'network', key=key, val=value) + + if cmd == 'del': + key = ' '.join(args.split(' ')[1:]).strip() + if not replacer_obj.delete(key.decode('utf-8')): + echo('No such keyword in replacement table: %(key)s', + weechat_buffer, 'error', key=key) + else: + echo('Successfully removed key: %(key)s', weechat_buffer, + 'network', key=key.encode('utf-8')) + + return weechat.WEECHAT_RC_OK + + +@inject_replacer_object +def completion_cb(replacer_obj, data, completion_item, weechat_buffer, + completion): + """Complete keys from replacement table for add/del command""" + for key in replacer_obj.replacement_map: + weechat.hook_completion_list_add(completion, key.encode('utf-8'), 0, + weechat.WEECHAT_LIST_POS_SORT) + return weechat.WEECHAT_RC_OK + + +@inject_replacer_object +def replace_cb(replacer_obj, data, completion_item, weechat_buffer, + completion): + """replace keyword with value from replacement table, if found""" + position = weechat.buffer_get_integer(weechat_buffer, 'input_pos') + + input_line = weechat.buffer_get_string(weechat_buffer, 'input') + input_line = input_line.decode('utf-8') + + if len(input_line) == 0: + return weechat.WEECHAT_RC_OK + + if input_line[position - 1] == ' ': + return weechat.WEECHAT_RC_OK + + if position > 0: + left_space_index = input_line.rfind(' ', 0, position - 1) + if left_space_index == -1: + left_space_index = 0 + word = input_line[left_space_index:position].strip() + + if word in replacer_obj.replacement_map: + + replacement = replacer_obj.replacement_map[word] + if position >= len(input_line.strip()): + replacement += ' ' + + new_line = u'' + if left_space_index: + new_line += input_line[:left_space_index] + u' ' + new_line += replacement + new_position = len(new_line) + new_line += input_line[position:] + + weechat.buffer_set(weechat_buffer, 'input', + new_line.encode('utf-8')) + weechat.buffer_set(weechat_buffer, 'input_pos', str(new_position)) + + return weechat.WEECHAT_RC_OK + + +def main(): + """Main entry""" + + weechat.register(NAME, AUTHOR, VERSION, LICENSE, DESC, '', '') + weechat.hook_completion('replacer_plugin', 'Try to match last word with ' + 'those in replacement map keys, and replace it ' + 'with value.', 'replace_cb', '') + weechat.hook_completion('completion_cb', 'Complete replacement map keys', + 'completion_cb', '') + + weechat.hook_command(COMMAND, DESC, "[add |del ]", + __doc__ % {"command": COMMAND}, + 'add|del %(completion_cb)', 'replace_cmd', '') + +if __name__ == "__main__": + main() diff --git a/test_replacer.py b/test_replacer.py new file mode 100644 index 0000000..f188c1f --- /dev/null +++ b/test_replacer.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import sys +import os +import unittest +import tempfile + + +class Weechat(object): + """Mock weechat interface""" + ACTION = '*' + ERROR = '=!=' + NETWORK = '--' + JOIN = '-->' + QUIT = '<--' + WEECHAT_RC_OK = 0 + WEECHAT_LIST_POS_SORT = 1 + + def __init__(self): + self.wbuffer = '' + self.completions = [] + self.position = 0 + self.line = '' + + def register(self, *args, **kwargs): + pass + + def color(self, color): + return color + + def prnt(self, we_buff, msg): + self.wbuffer = msg + + def prefix(self, arg): + _map = {'action': Weechat.ACTION, + 'error': Weechat.ERROR, + 'network': Weechat.NETWORK, + 'join': Weechat.JOIN, + 'quit': Weechat.QUIT} + return _map[arg] + + def hook_completion(self, *args, **kwargs): + pass + + def hook_command(self, *args, **kwargs): + pass + + def hook_completion_list_add(self, completion, item, index, sort): + self.completions.append(item) + + def buffer_get_integer(self, *args, **kwargs): + return self.position + + def buffer_get_string(self, *args, **kwargs): + return self.line + + def buffer_set(self, wbuffer, what, value): + _map = {'input': self._set_line, + 'input_pos': self._set_position} + _map[what](value) + + def _set_line(self, val): + self.line = val + + def _set_position(self, val): + self.position = val + + +weechat = Weechat() +sys.modules['weechat'] = weechat + + +import replacer + + +class TestReplacer(unittest.TestCase): + def setUp(self): + fd, fname = tempfile.mkstemp() + os.close(fd) + self._path = fname + self.repl = replacer.Replacer(self._path) + + def tearDown(self): + self.repl = None + try: + os.unlink(self._path) + except OSError: + pass + + def test_init(self): + self.assertDictEqual(self.repl.replacement_map, {}) + + def test_add(self): + self.repl.add('foo', 'bar') + self.assertDictEqual(self.repl.replacement_map, {'foo': 'bar'}) + + def test_delete(self): + self.repl.add('foo', 'bar') + self.assertFalse(self.repl.delete('baz')) + self.assertTrue(self.repl.delete('foo')) + self.assertDictEqual(self.repl.replacement_map, {}) + +class TestDummyTests(unittest.TestCase): + """ + This, somehow stupid test ensures, that process of reading default + replacer config file works + """ + def tearDown(self): + replacer.Replacer.self_object = None + + def test_init(self): + repl = replacer.Replacer() + self.assertIsInstance(repl.replacement_map, dict) + + def test_main(self): + replacer.Replacer.self_object = replacer.Replacer() + replacer.main() + + def test_injector(self): + + def fun(first, *args, **kwargs): + return first + + self.assertIsNone(replacer.Replacer.self_object) + robj = replacer.inject_replacer_object(fun)() + self.assertIsNotNone(replacer.Replacer.self_object) + self.assertIsInstance(robj, replacer.Replacer) + + +class TestFunctions(unittest.TestCase): + def setUp(self): + fd, fname = tempfile.mkstemp() + os.close(fd) + self._path = fname + replacer.Replacer.self_object = replacer.Replacer(self._path) + self.rc = replacer.Replacer + + def tearDown(self): + self.rc.self_object = None + try: + os.unlink(self._path) + except OSError: + pass + weechat.completions = [] + + def test_echo(self): + replacer.echo('a', None) + self.assertEqual(weechat.wbuffer, 'a') + + replacer.echo('a', None, 'action') + self.assertEqual(weechat.wbuffer, '%sa' % Weechat.ACTION) + replacer.echo('something', None, 'network') + self.assertEqual(weechat.wbuffer, '%ssomething' % Weechat.NETWORK) + + def test_replace_cmd(self): + replacer.replace_cmd(None, None, None) + self.assertIn(Weechat.ERROR, weechat.wbuffer) + self.assertIn('No replacements defined', weechat.wbuffer) + + self.rc.self_object.replacement_map = {'foo': 'bar'} + + replacer.replace_cmd(None, None, None) + self.assertEqual(weechat.wbuffer, 'foo chat_delimiters->reset bar') + + args = 'foo bar bazz' + replacer.replace_cmd(None, None, args) + self.assertIn(Weechat.ERROR, weechat.wbuffer) + self.assertIn('Error in command', weechat.wbuffer) + + args = 'add baz bazz' + replacer.replace_cmd(None, None, args) + self.assertEqual(weechat.wbuffer, + '--added: baz chat_delimiters->reset bazz') + self.assertDictEqual(self.rc.self_object.replacement_map, + {'foo': 'bar', 'baz': 'bazz'}) + + args = 'del baz' + replacer.replace_cmd(None, None, args) + self.assertEqual(weechat.wbuffer, '--Successfully removed key: baz') + + args = 'del baz' + replacer.replace_cmd(None, None, args) + self.assertIn(Weechat.ERROR, weechat.wbuffer) + self.assertIn('No such keyword', weechat.wbuffer) + + def test_completion_cb(self): + replacer.completion_cb(None, None, None, None) + + self.rc.self_object.replacement_map = {'foo': 'bar'} + + replacer.completion_cb(None, None, None, None) + self.assertEqual(weechat.completions, ['foo']) + + def test_replace_cb(self): + replacer.replace_cb(None, None, None, None) + self.assertEqual(weechat.position, 0) + self.assertEqual(weechat.line, '') + + self.rc.self_object.replacement_map = {'foo': 'Vestibulum ante'} + + # quis foo cursus + # ^ + weechat.line = 'quis foo cursus' + weechat.position = 8 + replacer.replace_cb(None, None, None, None) + self.assertEqual(weechat.line, 'quis Vestibulum ante cursus') + + # quis cursus foo + # ^ + weechat.line = 'quis cursus foo' + weechat.position = 15 + replacer.replace_cb(None, None, None, None) + self.assertEqual(weechat.line, 'quis cursus Vestibulum ante ') + + # foo quis cursus + # ^ + weechat.line = 'foo quis cursus' + weechat.position = 3 + replacer.replace_cb(None, None, None, None) + self.assertEqual(weechat.line, 'Vestibulum ante quis cursus') + + # quis cursus + # ^ + weechat.line = 'quis cursus' + weechat.position = 5 + replacer.replace_cb(None, None, None, None) + self.assertEqual(weechat.line, 'quis cursus') + + +if __name__ == '__main__': + unittest.main()