# Inspired by histman.py: # - https://weechat.org/scripts/source/histman.py.html/ # - https://github.com/weechatter/weechat-scripts/blob/master/python/histman.py # And this hdata_update.py test script: # - https://weechat.org/files/temp/scripts/hdata_update.py import re, os, traceback import weechat SCRIPT_NAME = 'pershistory' SCRIPT_AUTHOR = 'Lucas-C ' SCRIPT_VERSION = '1.0' SCRIPT_LICENSE = 'WTFPL' SCRIPT_DESC = 'Simply persists the command history by saving/restoring it in a file at exit/start time' IGNORE_CMD_PATTERN = '(.*password|.*nickserv|/quit)' HISTORY_FILE = 'cmd_history' def main(): try: if not weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, '', ''): raise RuntimeError('Script registration failed') weechat.hook_signal('quit', 'save_history_on_quit_cb', '') history_filename = get_fullpath_to_configfile(HISTORY_FILE) if os.path.isfile(history_filename): load_history(read_history(history_filename)) else: weechat.prnt('', '%s%s - WARNING: History not loaded, file could not be found: %s' % (weechat.prefix('error'), SCRIPT_NAME, history_filename)) except Exception: weechat.prnt('', '%s%s: %s' % (weechat.prefix('error'), SCRIPT_NAME, traceback.format_exc())) def save_history_on_quit_cb(data, signal, signal_data): history_filename = get_fullpath_to_configfile(HISTORY_FILE) history_lines = get_history() if history_lines: write_history(history_filename, history_lines) return weechat.WEECHAT_RC_OK def load_history(history_lines): ptr_buffer = weechat.buffer_search_main() hdata = weechat.hdata_get('history') for line in history_lines: if not weechat.hdata_update(hdata, '', {'buffer': ptr_buffer, 'text': line}): raise IOError("Failed to update hdata with line '{}'".format(line)) def get_history(): history_lines = [] ptr_buffer_history = weechat.infolist_get('history', '', '') while weechat.infolist_next(ptr_buffer_history): line = weechat.infolist_string(ptr_buffer_history, 'text') if not re.match(IGNORE_CMD_PATTERN, line, re.I): history_lines.append(line) weechat.infolist_free(ptr_buffer_history) return reversed(history_lines) def read_history(filename): with open(filename, 'r') as open_file: return [line.strip() for line in open_file] def write_history(filename, history_lines): with open(filename, 'w') as open_file: for line in history_lines: open_file.write(line + '\n') def get_fullpath_to_configfile(filename): return os.path.join(weechat.info_get("weechat_dir", ""), filename) if __name__ == '__main__': main()