Example #1
0
def urlbar_print_cb(data, buffer, time, tags, displayed, highlight, prefix, message):


    buffer_name = get_buffer_name(buffer, long=True)
    # Skip ignored buffers
    for ignored_buffer in weechat.config_get_plugin('ignore').split(','):
        if ignored_buffer.lower() == buffer_name.lower():
            return weechat.WEECHAT_RC_OK

    # Clean list of URLs
    for i in range(len(urls) - int(weechat.config_get_plugin('remember_amount'))):
        # Delete the oldest
        urls.pop(0)

    for url in urlRe.findall(message):
        urlobject = URL(url, get_buffer_name(buffer), time, prefix)
        # Do not add duplicate URLs
        if urlobject in urls:
            continue
        urls.append(urlobject)
        if weechat.config_get_plugin('use_popup') == 'on':
            # Check if URL is in current buffer
            if weechat.config_get_plugin('display_current_only') == 'on' and weechat.current_buffer() == buffer:
                popup()
            if weechat.config_get_plugin('display_current_only') != 'on':
                popup()

        weechat.bar_item_update("urlbar_urls")

    return weechat.WEECHAT_RC_OK
def input_move_cb(data, signal, signal_data):
    buffer = signal

    if OPTIONS['replace_mode'].lower() == "on" and weechat.buffer_get_string(buffer,'localvar_inline_replace_mode') == "1":
        delete_localvar_replace_mode(buffer)
        weechat.buffer_set(buffer, 'localvar_del_spell_correction_suggest_item', '')
#        tab_complete,position,aspell_suggest_items = weechat.buffer_get_string(buffer,'localvar_inline_suggestions').split(':',2)
#        weechat.buffer_set(buffer, 'localvar_set_inline_suggestions', '%s:%s:%s' % ('1',position,aspell_suggest_items))
        return weechat.WEECHAT_RC_OK

    tab_complete,position,aspell_suggest_item = get_position_and_suggest_item(buffer)

    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
    if not localvar_aspell_suggest:
        return weechat.WEECHAT_RC_OK

    misspelled_word,aspell_suggestions = localvar_aspell_suggest.split(':')

    if not aspell_suggest_item in aspell_suggestions:
        aspell_suggestion_list = aspell_suggestions.split(',',1)
        weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:%s' % ('1',0,aspell_suggestion_list[0]))
        weechat.bar_item_update('spell_correction')
        return weechat.WEECHAT_RC_OK

    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:%s' % ('1',position,aspell_suggest_item))

    return weechat.WEECHAT_RC_OK
def urlbar_cmd(data, buffer, args):
    """ Callback for /url command. """
    global urls, DISPLAY_ALL

    if args == "list":
        if urls:
            DISPLAY_ALL = True
            weechat.command("", '/bar show urlbar')
            weechat.bar_item_update("urlbar_urls")
        else:
            weechat.prnt('', 'URL list empty.')
    if args == "show":
        weechat.command('', '/bar show urlbar')
    elif args == 'hide':
        weechat.command("", "/bar hide urlbar")
    elif args == 'toggle':
        weechat.command("", "/bar toggle urlbar")
    elif args == 'clear':
        urls = []
    elif args.startswith('load'):
        urlbar_load_url(*args.split())
    else:
        weechat.command("", "/help %s" % SCRIPT_COMMAND)

    return weechat.WEECHAT_RC_OK
Example #4
0
def message_out_cb(data, modifier, modifier_data, string):
    """Outgoing message callback."""
    result = ''

    # If any exception is raised in this function, WeeChat will send the
    # outgoing message, which could be something that the user intended to be
    # encrypted. This paranoid exception handling ensures that the system
    # fails closed and not open.
    try:
        debug(('message_out_cb', data, modifier, modifier_data, string))

        parsed = parse_irc_privmsg(utf8_decode(string))
        debug(('parsed message', parsed))

        # skip processing messages to public channels
        if parsed['to_channel']:
            return string

        server = utf8_decode(modifier_data)

        to_user = irc_user(parsed['to_nick'], server)
        local_user = current_user(server)

        context = ACCOUNTS[local_user].getContext(to_user)

        if parsed['text'].startswith(potr.proto.OTRTAG) and \
                not OTR_QUERY_RE.match(parsed['text']):
            if not has_otr_end(parsed['text']):
                debug('in OTR message')
                context.in_otr_message = True
            else:
                debug('complete OTR message')
            result = string
        elif context.in_otr_message:
            if has_otr_end(parsed['text']):
                context.in_otr_message = False
                debug('in OTR message end')
            result = string
        else:
            debug(('context send message', parsed['text'], parsed['to_nick'],
                   server))

            try:
                ret = context.sendMessage(
                    potr.context.FRAGMENT_SEND_ALL,
                    utf8_encode(parsed['text']))

                if ret:
                    debug(('sendMessage returned', ret))
                    result = utf8_encode('PRIVMSG %s :%s' % (
                            parsed['to_nick'], utf8_decode(ret)))
            except potr.context.NotEncryptedError, err:
                if err.args[0] == potr.context.EXC_FINISHED:
                    context.print_buffer(
                        """Your message was not sent. End your private conversation:\n/otr finish %s %s""" % (
                            parsed['to_nick'], server))
                else:
                    raise

        weechat.bar_item_update(SCRIPT_NAME)
def aspell_suggest_cb(data, signal, signal_data):
    buffer = signal_data
    if OPTIONS["auto_pop_up_item"].lower() == "on":
        auto_suggest_cmd_cb("", buffer, "")
        weechat.buffer_set(buffer, "localvar_del_spell_correction_suggest_input_line", "")
    weechat.bar_item_update("spell_suggest")
    return weechat.WEECHAT_RC_OK
Example #6
0
def tc_bar_item_update (data=None, signal=None, signal_data=None):
    '''Updates bar item'''
    '''May be used as a callback or standalone call.'''
    global length, cursor_pos, tc_input_text

    w.bar_item_update('tc')
    return w.WEECHAT_RC_OK
def responsive_cb(data, signal, signal_data):
    term_height = int(weechat.info_get("term_height", ""))
    term_width = int(weechat.info_get("term_width", ""))

    try:
        apply_layout = None
        for layout, width, height in LAYOUT_LIST:
            if term_height <= int(height) or term_width <= int(width):
                apply_layout = layout
                break

        if apply_layout is None:
            # Always apply the last layout if term width/height is larger than configured layouts
            apply_layout = LAYOUT_LIST[-1][0]

        if layout_exist(apply_layout) and not layout_current(apply_layout):
            _print("Applying layout %s" % apply_layout)
            weechat.command("", "/layout apply %s" % apply_layout)
            toggle_nick_list(apply_layout)

        weechat.bar_item_update("rlayout")
    except ValueError:
        _print("Height or width is not in number form, ignoring.")

    return weechat.WEECHAT_RC_OK
def input_delete_cb(data, signal, signal_data):
    buffer = signal
    delete_localvar_replace_mode(buffer)
    weechat.buffer_set(buffer, 'localvar_del_spell_correction_suggest_item', '')
    weechat.buffer_set(buffer, 'localvar_del_spell_correction_suggest_input_line', '')
    weechat.bar_item_update('spell_correction')
    return weechat.WEECHAT_RC_OK
Example #9
0
def slack_websocket_cb(data, fd):
    server = data
    try:
        data = servers.find(server).ws.recv()
        message_json = json.loads(data)
        #this magic attaches json that helps find the right dest
        message_json['myserver'] = server
    except:
        return w.WEECHAT_RC_OK
    #dispatch here
    if message_json.has_key("type"):
        function_name = message_json["type"]
    else:
        function_name = "unknown"
    try:
        proc[function_name](message_json)
        dbg(function_name)
    except KeyError:
        pass
        if function_name:
            dbg("Function not implemented: %s\n%s" % (function_name, message_json))
        else:
            dbg("Function not implemented\n%s" % (message_json))
    w.bar_item_update("slack_typing_notice")
    return w.WEECHAT_RC_OK
Example #10
0
def urlbar_print_cb(data, buffer, time, tags, displayed, highlight, prefix, message):


    buffer_name = get_buffer_name(buffer, long=True)
    # Skip ignored buffers
    for ignored_buffer in weechat.config_get_plugin('ignore').split(','):
        if ignored_buffer.lower() == buffer_name.lower():
            return weechat.WEECHAT_RC_OK

    # Clean list of URLs
    for i in range(len(urls) - int(weechat.config_get_plugin('remember_amount'))):
        # Delete the oldest
        urls.pop(0)

    for url in urlRe.findall(message):
        urlobject = URL(url, get_buffer_name(buffer), time, prefix)
        # Do not add duplicate URLs
        if urlobject in urls:
            continue
        urls.append(urlobject)
        if weechat.config_get_plugin('use_popup') == 'on':
            weechat.command("", "/bar show urlbar")
            # auto hide bar after delay
            try:
                weechat.command('', '/wait %s /bar hide urlbar' %
                        int(weechat.config_get_plugin('visible_seconds')))
            except ValueError:
                weechat.prnt('', 'Invalid visible_seconds')

        weechat.bar_item_update("urlbar_urls")

    return weechat.WEECHAT_RC_OK
def delete_localvar_replace_mode(buffer):
    if OPTIONS['replace_mode'].lower() == "on":
        weechat.buffer_set(buffer, 'localvar_del_inline_replace_mode', '')
        weechat.buffer_set(buffer, 'localvar_del_inline_suggestions', '')
        weechat.buffer_set(buffer, 'localvar_del_save_position_of_word', '')
        weechat.buffer_set(buffer, 'localvar_del_current_cursor_pos', '')
        weechat.bar_item_update('spell_suggestion')
Example #12
0
def timeline_prompt_cb(data, signal, signal_data):
    """Tweets from the timeline buffer, also shows how long your tweet is."""
    global buffers
    if  wc.current_buffer() != buffers['__TIMELINE']:
        return wc.WEECHAT_RC_OK
    wc.bar_item_update('tweet_counter')
    return wc.WEECHAT_RC_OK
Example #13
0
def timer_cb(data, remaining_calls):
    """Timer callback."""
    global cmdhelp_hooks
    if cmdhelp_hooks['modifier']:
        unhook(('modifier',))
        weechat.bar_item_update('input_text')
    return weechat.WEECHAT_RC_OK
Example #14
0
def command_cb(data, buf, args):
    try:
        args = shlex.split(args)
    except:
        return weechat.WEECHAT_RC_ERROR

    if len(args) == 2 and args[0] == b'enable':
        server, channel = get_buffer_info(buf)
        channel_data[u'{0}.{1}'.format(server, channel)] = WeeSodiumChannel(
            args[1])

        weechat.prnt(buf, "This conversation is now encrypted.")
        weechat.bar_item_update(SCRIPT_NAME)

        return weechat.WEECHAT_RC_OK
    elif len(args) == 1 and args[0] == b'disable':
        server, channel = get_buffer_info(buf)
        del channel_data[u'{0}.{1}'.format(server, channel)]

        weechat.prnt(buf, "This conversation is no longer encrypted.")
        weechat.bar_item_update(SCRIPT_NAME)

        return weechat.WEECHAT_RC_OK
    else:
        return weechat.WEECHAT_RC_ERROR
def input_text_changed_cb(data, signal, signal_data):
    global multiline_input

    if multiline_input == "1":
        return weechat.WEECHAT_RC_OK

    buffer = signal_data
    if not buffer:
        return weechat.WEECHAT_RC_OK

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(buffer)
    if not position or not aspell_suggest_item:
        return weechat.WEECHAT_RC_OK

    # 1 = cursor etc., 2 = TAB
    if tab_complete != "0":
        if not aspell_suggest_item:
            aspell_suggest_item = ""
        weechat.buffer_set(
            buffer, "localvar_set_spell_correction_suggest_item", "%s:%s:%s" % ("0", position, aspell_suggest_item)
        )
        weechat.bar_item_update("spell_correction")
        return weechat.WEECHAT_RC_OK

    if OPTIONS["auto_replace"].lower() == "on":
        replace_misspelled_word(buffer)  # also remove localvar_suggest_item
        return weechat.WEECHAT_RC_OK

    #    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:' % ('0','-1'))
    weechat.bar_item_update("spell_correction")
    return weechat.WEECHAT_RC_OK
def stop_typing(data, signal, signal_data):
    msg_hash = w.info_get_hashtable(
        "irc_message_parse", {"message": signal_data } )
    if msg_hash["nick"] in typing:
        del typing[msg_hash["nick"]]
    w.bar_item_update("bitlbee_typing_notice")
    return w.WEECHAT_RC_OK
Example #17
0
def filtered_update_cb(data, signal, signal_data):
    global filter_status
    if signal == "filters_disabled":
        filter_status = 0
    if signal == "filters_enabled":
        filter_status = 1
    weechat.bar_item_update(SCRIPT_NAME)
    return weechat.WEECHAT_RC_OK
Example #18
0
def updateTimer(data, cals):
    # Write out time spent online to file, first the last reset time and then the number of seconds spent connected
    counter_file = open(filename, 'w')
    counter_file.writelines([last_reset_ctime, str(write_value), '\n'])
    counter_file.close()
    # Update weechat bar
    weechat.bar_item_update('irctimer')
    return weechat.WEECHAT_RC_OK
def buffer_switch_cb(data, signal, signal_data):
    """Callback for buffer switched.

    Used for updating the status bar item when it is in a root bar.
    """
    weechat.bar_item_update(SCRIPT_NAME)

    return weechat.WEECHAT_RC_OK
def auto_suggest_cmd_cb(data, buffer, args):

    input_line = weechat.buffer_get_string(buffer, "input")
    weechat.buffer_set(buffer, "localvar_set_spell_correction_suggest_input_line", "%s" % input_line)

    if args.lower() == "replace":
        replace_misspelled_word(buffer)
        return weechat.WEECHAT_RC_OK

    #    if not weechat.buffer_get_string(buffer,'localvar_spell_correction_suggest_item'):
    #        return weechat.WEECHAT_RC_OK

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(buffer)
    if not position:
        position = -1

    # get localvar for misspelled_word and suggestions from buffer or return
    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
    if not localvar_aspell_suggest:
        return weechat.WEECHAT_RC_OK

    misspelled_word, aspell_suggestions = localvar_aspell_suggest.split(":")

    aspell_suggestions = aspell_suggestions.replace("/", ",")
    aspell_suggestion_list = aspell_suggestions.split(",")
    if len(aspell_suggestion_list) == 0:
        position = -1
        weechat.bar_item_update("spell_correction")
        return weechat.WEECHAT_RC_OK

    # append an empty entry to suggestions to quit without changes.
    if OPTIONS["auto_replace"].lower() == "on":
        aspell_suggestion_list.append("")

    position = int(position)
    # cycle backwards through suggestions
    if args == "/input complete_previous" or args == "previous":
        # position <= -1? go to last suggestion
        if position <= -1:
            position = len(aspell_suggestion_list) - 1
        position -= 1
    # cycle forward through suggestions
    else:
        if position >= len(aspell_suggestion_list) - 1:
            position = 0
        else:
            position += 1

    # 2 = TAB or command is called
    weechat.buffer_set(
        buffer,
        "localvar_set_spell_correction_suggest_item",
        "%s:%s:%s" % ("2", str(position), aspell_suggestion_list[position]),
    )

    weechat.bar_item_update("spell_correction")
    return weechat.WEECHAT_RC_OK
Example #21
0
def gweather_data_cb(data, command, rc, stdout, stderr):
    '''
    Callback for the data fetching process.
    '''
    global last_city, last_lang, last_run, last_format
    global gweather_hook_process, gweather_stdout, gweather_output

    if rc == weechat.WEECHAT_HOOK_PROCESS_ERROR or stderr != '':
        weechat.prnt('', '%sgweather: Weather information fetching failed: %s' % (\
            weechat.prefix("error"), stderr))
        return weechat.WEECHAT_RC_ERROR

    if stdout:
        gweather_stdout += stdout

    if int(rc) < 0:
        # Process not ready
        return weechat.WEECHAT_RC_OK

    # Update status variables for succesful run
    last_run = time()
    last_city = weechat.config_get_plugin('city')
    last_lang = weechat.config_get_plugin('language')
    last_format = weechat.config_get_plugin('format')
    gweather_hook_process = ''

    if not gweather_stdout:
        return weechat.WEECHAT_RC_OK

    try:
        # The first row should contain "content-type" from HTTP header
        content_type, xml_response = gweather_stdout.split('\n', 1)
    except:
        # Failed to split received data in two at carridge return
        weechat.prnt('', '%sgweather: Invalid data received' % (weechat.prefix("error")))
        gweather_stdout = ''
        return weechat.WEECHAT_RC_ERROR

    gweather_stdout = ''

    # Determine the used character set in the response
    try:
        charset = content_type.split('charset=')[1]
    except:
        charset = 'utf-8'

    if charset.lower() != 'utf-8':
        xml_response = xml_response.decode(charset).encode('utf-8')

    # Feed the respose to parser and parsed data to formatting
    weather_data = parse_google_weather(xml_response)
    gweather_output = format_weather(weather_data)

    # Request bar item to update to the latest "gweather_output" 
    weechat.bar_item_update('gweather')

    return weechat.WEECHAT_RC_OK
def tc_bar_item_update (data=None, signal=None, signal_data=None):
    '''Updates bar item'''
    '''May be used as a callback or standalone call.'''
    global length, cursor_pos, tc_input_text

    current_buffer = w.current_buffer()
    length = w.buffer_get_integer(current_buffer,'input_length')
    cursor_pos = w.buffer_get_integer(current_buffer,'input_pos') + 1
    w.bar_item_update('tc')
    return w.WEECHAT_RC_OK
Example #23
0
def hlpv_timer_cb(data, remaining_calls):
    """ Called when a message must be removed from list. """
    global hlpv_messages

    if len(hlpv_messages):
        hlpv_messages.pop(0)
        weechat.bar_item_update("hlpv")
        if len(hlpv_messages) > 0:
            hlpv_timer()
    return weechat.WEECHAT_RC_OK
Example #24
0
def buffer_closing_cb(data, signal, signal_data):
    server, channel = get_buffer_info(signal_data)

    if server is not None and channel is not None:
        dict_key = u'{0}.{1}'.format(server, channel)
        if dict_key in channel_data:
            del channel_data[dict_key]
            weechat.bar_item_update(SCRIPT_NAME)
        return weechat.WEECHAT_RC_OK

    return weechat.WEECHAT_RC_ERROR
Example #25
0
def buffer_input(data, buffer, string):

    global cached_folder_list, active_folder_line

    for i, folder in enumerate(cached_folder_list):
        if string in folder:
            active_folder_line = i
            w.bar_item_update('imap_folders')
            

    return w.WEECHAT_RC_OK
Example #26
0
def set_mode(arg):
    """Set the current mode and update the bar mode indicator."""
    global mode
    mode = arg
    # If we're going to Normal mode, the cursor must move one character to the
    # left.
    if mode == "NORMAL":
        buf = weechat.current_buffer()
        input_line = weechat.buffer_get_string(buf, "input")
        cur = weechat.buffer_get_integer(buf, "input_pos")
        set_cur(buf, input_line, cur - 1, False)
    weechat.bar_item_update("mode_indicator")
def auto_suggest_cmd_cb(data, buffer, args):
        
    input_line = weechat.buffer_get_string(buffer, 'input')
    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_input_line', '%s' % input_line)

    if args.lower() == 'replace':
        replace_misspelled_word(buffer)
        return weechat.WEECHAT_RC_OK

#    if not weechat.buffer_get_string(buffer,'localvar_spell_correction_suggest_item'):
#        return weechat.WEECHAT_RC_OK

    tab_complete,position,aspell_suggest_item = get_position_and_suggest_item(buffer)
    if not position:
        position = -1

    # get localvar for misspelled_word and suggestions from buffer or return
    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
    if not localvar_aspell_suggest:
        return weechat.WEECHAT_RC_OK

    misspelled_word,aspell_suggestions = localvar_aspell_suggest.split(':')

    aspell_suggestions = aspell_suggestions.replace('/',',')
    aspell_suggestion_list = aspell_suggestions.split(',')
    if len(aspell_suggestion_list) == 0:
        position = -1
        weechat.bar_item_update('spell_correction')
        return weechat.WEECHAT_RC_OK

    # append an empty entry to suggestions to quit without changes.
    if OPTIONS['auto_replace'].lower() == "on":
        aspell_suggestion_list.append('')

    position = int(position)
    # cycle backwards through suggestions
    if args == '/input complete_previous' or args == 'previous':
        # position <= -1? go to last suggestion
        if position <= -1:
            position = len(aspell_suggestion_list)-1
        position -= 1
    # cycle forward through suggestions
    else:
        if position >= len(aspell_suggestion_list)-1:
            position = 0
        else:
            position += 1

    # 2 = TAB or command is called
    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:%s' % ('2',str(position),aspell_suggestion_list[position]))

    weechat.bar_item_update('spell_correction')
    return weechat.WEECHAT_RC_OK
Example #28
0
def hook_timer():
    global hooks
    hooks["timer"] = weechat.hook_timer(int(OPTIONS["refresh"]) * 1000, 0, 0, 'item_update', '')
    hooks["bar_item"] = weechat.bar_item_new(SCRIPT_NAME, 'show_item','')

    if hooks["timer"] == 0:
        weechat.prnt('',"%s: can't enable %s, hook failed" % (weechat.prefix("error"), SCRIPT_NAME))
        weechat.bar_item_remove(hooks["bar_item"])
        hooks["bar_item"] = ""
        return 0
    weechat.bar_item_update(SCRIPT_NAME)
    return 1
Example #29
0
def cb_check_esc(data, remaining_calls):
    """Check if the Esc key was pressed and change the mode accordingly."""
    global esc_pressed, vi_buffer, cmd_text, catching_keys_data
    if last_signal_time == float(data):
        esc_pressed += 1
        set_mode("NORMAL")
        # Cancel any current partial commands.
        vi_buffer = ""
        cmd_text = ""
        weechat.command("", "/bar hide vi_cmd")
        catching_keys_data = {"amount": 0}
        weechat.bar_item_update("vi_buffer")
    return weechat.WEECHAT_RC_OK
Example #30
0
def hlpv_item_add(buffer, highlight, prefix, message):
    """ Add message to list of messages (will be displayed by item). """
    global hlpv_messages

    if highlight == "1":
        color_type = weechat.config_string(
            weechat.config_get("weechat.color.status_data_highlight"))
        color_string_highlight = weechat.config_get_plugin(
            "color_string_highlight")
        if color_string_highlight == "":
            color_string_highlight = color_type
        string_prefix = "%s%s" % (
            weechat.color(color_string_highlight),
            weechat.config_get_plugin("string_highlight"))
    else:
        color_type = weechat.config_string(
            weechat.config_get("weechat.color.status_data_private"))
        color_string_private = weechat.config_get_plugin(
            "color_string_private")
        if color_string_private == "":
            color_string_private = color_type
        string_prefix = "%s%s" % (weechat.color(color_string_private),
                                  weechat.config_get_plugin("string_private"))
    color_delimiter = weechat.color(
        weechat.config_get_plugin("color_delimiter"))
    if weechat.config_get_plugin("buffer_number") == "on":
        color_buffer_number = weechat.config_get_plugin("color_buffer_number")
        if color_buffer_number == "":
            color_buffer_number = color_type
        buffer_number = "%s%s%s:" % (weechat.color(color_buffer_number),
                                     weechat.buffer_get_integer(
                                         buffer, "number"), color_delimiter)
    else:
        buffer_number = ""
    color_buffer_name = weechat.color(
        weechat.config_get_plugin("color_buffer_name"))
    if weechat.config_get_plugin("buffer_short_name") == "on":
        buffer_name = weechat.buffer_get_string(buffer, "short_name")
    else:
        buffer_name = weechat.buffer_get_string(buffer, "name")
    color_prefix = weechat.color(weechat.config_get_plugin("color_prefix"))
    string_delimiter = weechat.config_get_plugin("string_delimiter")
    color_message = weechat.color(weechat.config_get_plugin("color_message"))
    string = "%s%s%s%s: %s%s%s%s%s%s" % (
        string_prefix, buffer_number, color_buffer_name, buffer_name,
        color_prefix, prefix, color_delimiter, string_delimiter, color_message,
        message)
    if len(hlpv_messages) == 0:
        hlpv_timer()
    hlpv_messages.append(string)
    weechat.bar_item_update("hlpv")
Example #31
0
def replace_misspelled_word(buffer):
    input_line = weechat.buffer_get_string(
        buffer, 'localvar_spell_correction_suggest_input_line')
    if not input_line:
        # remove spell_correction item
        weechat.buffer_set(buffer,
                           'localvar_del_spell_correction_suggest_item', '')
        weechat.bar_item_update('spell_correction')
        weechat.bar_item_update('spell_suggestion')
        return
    if OPTIONS['eat_input_char'].lower() == 'off' or input_line == '':
        input_pos = weechat.buffer_get_integer(buffer, 'input_pos')
        # check cursor position
        if len(input_line) < int(input_pos) or input_line[
                int(input_pos) - 1] == ' ' or input_line == '':
            input_line = weechat.buffer_get_string(buffer, 'input')

    weechat.buffer_set(buffer,
                       'localvar_del_spell_correction_suggest_input_line', '')

    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)

    # localvar_aspell_suggest = word,word2/wort,wort2
    if localvar_aspell_suggest:
        misspelled_word, aspell_suggestions = localvar_aspell_suggest.split(
            ':')
        aspell_suggestions = aspell_suggestions.replace('/', ',')
        aspell_suggestion_list = aspell_suggestions.split(',')
    else:
        return

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(
        buffer)
    if not position or not aspell_suggest_item:
        return

    position = int(position)

    input_line = input_line.replace(misspelled_word,
                                    aspell_suggestion_list[position])
    if input_line[-2:] == '  ':
        input_line = input_line.rstrip()
        input_line = input_line + ' '

    weechat.buffer_set(buffer, 'input', input_line)

    # set new cursor position. check if suggestion is longer or smaller than misspelled word
    input_pos = weechat.buffer_get_integer(buffer, 'input_pos') + 1
    length_misspelled_word = len(misspelled_word)
    length_suggestion_word = len(aspell_suggestion_list[position])

    if length_misspelled_word < length_suggestion_word:
        difference = length_suggestion_word - length_misspelled_word
        new_position = input_pos + difference + 1
        weechat.buffer_set(buffer, 'input_pos', str(new_position))

    weechat.buffer_set(buffer, 'localvar_del_spell_correction_suggest_item',
                       '')
    weechat.bar_item_update('spell_suggestion')
    weechat.bar_item_update('spell_correction')
def replace_misspelled_word(buffer):
    input_line = weechat.buffer_get_string(buffer, "localvar_spell_correction_suggest_input_line")
    if not input_line:
        # remove spell_correction item
        weechat.buffer_set(buffer, "localvar_del_spell_correction_suggest_item", "")
        weechat.bar_item_update("spell_correction")
        return
    if OPTIONS["eat_input_char"].lower() == "off" or input_line == "":
        input_pos = weechat.buffer_get_integer(buffer, "input_pos")
        # check cursor position
        if len(input_line) < int(input_pos) or input_line[int(input_pos) - 1] == " " or input_line == "":
            input_line = weechat.buffer_get_string(buffer, "input")

    weechat.buffer_set(buffer, "localvar_del_spell_correction_suggest_input_line", "")

    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)

    # localvar_aspell_suggest = word,word2/wort,wort2
    if localvar_aspell_suggest:
        misspelled_word, aspell_suggestions = localvar_aspell_suggest.split(":")
        aspell_suggestions = aspell_suggestions.replace("/", ",")
        aspell_suggestion_list = aspell_suggestions.split(",")
    else:
        return

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(buffer)
    if not position or not aspell_suggest_item:
        return

    position = int(position)

    input_line = input_line.replace(misspelled_word, aspell_suggestion_list[position])
    if input_line[-2:] == "  ":
        input_line = input_line.rstrip()
        input_line = input_line + " "

    weechat.buffer_set(buffer, "input", input_line)
    weechat.bar_item_update("spell_correction")

    # set new cursor position. check if suggestion is longer or smaller than misspelled word
    input_pos = weechat.buffer_get_integer(buffer, "input_pos") + 1
    length_misspelled_word = len(misspelled_word)
    length_suggestion_word = len(aspell_suggestion_list[position])

    if length_misspelled_word < length_suggestion_word:
        difference = length_suggestion_word - length_misspelled_word
        new_position = input_pos + difference + 1
        weechat.buffer_set(buffer, "input_pos", str(new_position))

    weechat.buffer_set(buffer, "localvar_del_spell_correction_suggest_item", "")
Example #33
0
def countdown(data, timer):
    global acount, ccount, scount, lcount
    if data == "attack":
        acount = timer
    if data == "challenge":
        ccount = timer
    if data == "slay":
        scount = timer
    if data == "level":
        lcount = timer
    if int(timer) == 0:
        callbot()
    else:
        weechat.bar_item_update("mrpgcounters")
    return weechat.WEECHAT_RC_OK
Example #34
0
def hook_timer():
    global hooks
    hooks["timer"] = weechat.hook_timer(
        int(OPTIONS["refresh"]) * 1000, 0, 0, 'item_update', '')
    hooks["bar_item"] = weechat.bar_item_new(SCRIPT_NAME, 'show_item', '')

    if hooks["timer"] == 0:
        weechat.prnt(
            '', "%s: can't enable %s, hook failed" %
            (weechat.prefix("error"), SCRIPT_NAME))
        weechat.bar_item_remove(hooks["bar_item"])
        hooks["bar_item"] = ""
        return 0
    weechat.bar_item_update(SCRIPT_NAME)
    return 1
Example #35
0
def toggle_refresh(pointer, name, value):
    option_name = name[len('plugins.var.python.' + SCRIPT_NAME + '.'):]      # get optionname

    # option was removed? remove bar_item from struct
    if not weechat.config_get_plugin(option_name):
        ptr_bar = weechat.bar_item_search(option_name)
        if ptr_bar:
            weechat.bar_item_remove(ptr_bar)
        return weechat.WEECHAT_RC_OK

    # check if option is new or changed
    if not weechat.bar_item_search(option_name):
        weechat.bar_item_new(option_name,'update_item',option_name)

    weechat.bar_item_update(option_name)
    return weechat.WEECHAT_RC_OK
Example #36
0
def bar_item_update(signal, callback, callback_data):
    ptr_infolist_option = weechat.infolist_get('option','','plugins.var.python.' + SCRIPT_NAME + '.*')

    if not ptr_infolist_option:
        return

    while weechat.infolist_next(ptr_infolist_option):
        option_full_name = weechat.infolist_string(ptr_infolist_option, 'full_name')
        option_name = option_full_name[len('plugins.var.python.' + SCRIPT_NAME + '.'):]      # get optionname

        # check if item exists in a bar and if we have a hook for it
        if weechat.bar_item_search(option_name) and option_name in hooks:
            weechat.bar_item_update(option_name)

    weechat.infolist_free(ptr_infolist_option)
    return weechat.WEECHAT_RC_OK
Example #37
0
def clear_vi_buffers(data=None, remaining_calls=None):
    """Clear both pressed_keys and vi_buffer.

    If data is set to 'check_time', they'll only be cleared if enough time has
    gone by since they've been last set.
    This is useful as this function is called using a timer, so other keys
    might've been pressed before the timer is activated.

    """
    global pressed_keys, vi_buffer
    if data == "check_time" and time.time() < last_time + 1.0:
        return weechat.WEECHAT_RC_OK
    pressed_keys = ''
    vi_buffer = ''
    weechat.bar_item_update("vi_buffer")
    return weechat.WEECHAT_RC_OK
Example #38
0
def toggle_refresh(pointer, name, value):
    global hooks
    option = name[len('plugins.var.python.' + SCRIPT_NAME + '.'):]        # get optionname
    OPTIONS[option] = value                                               # save new value

    if option == 'refresh':                                               # option "refresh" changed by user?
        if hooks["timer"] != "":                                          # timer currently running?
            if OPTIONS['refresh'] != "0":                                 # new user setting not zero?
                unhook_timer()
                hook_timer()
            else:
                unhook_timer()                                            # user switched timer off
        elif hooks["timer"] == "":                                        # hook is empty
            if OPTIONS['refresh'] != "0":                                 # option is not zero!
                hook_timer()                                              # install hook
    weechat.bar_item_update(SCRIPT_NAME)
    return weechat.WEECHAT_RC_OK
Example #39
0
def cmd_help_toggle():
    """Toggle help on/off."""
    global cmdhelp_hooks, cmdhelp_settings
    if cmdhelp_hooks['modifier']:
        unhook(('timer', 'modifier'))
    else:
        cmdhelp_hooks['modifier'] = weechat.hook_modifier(
            'input_text_display_with_cursor', 'input_modifier_cb', '')
        timer = cmdhelp_settings['timer']
        if timer and timer != '0':
            try:
                value = float(timer)
                if value > 0:
                    weechat.hook_timer(value * 1000, 0, 1, 'timer_cb', '')
            except:
                pass
    weechat.bar_item_update('input_text')
Example #40
0
def create_bar_items():
    ptr_infolist_option = weechat.infolist_get('option','','plugins.var.python.' + SCRIPT_NAME + '.*')

    if not ptr_infolist_option:
        return

    while weechat.infolist_next(ptr_infolist_option):
        option_full_name = weechat.infolist_string(ptr_infolist_option, 'full_name')
        option_name = option_full_name[len('plugins.var.python.' + SCRIPT_NAME + '.'):]      # get optionname

        if weechat.bar_item_search(option_name):
            weechat.bar_item_update(option_name)
        else:
            weechat.bar_item_new(option_name,'update_item',option_name)
        weechat.bar_item_update(option_name)

    weechat.infolist_free(ptr_infolist_option)
Example #41
0
def input_text_changed_cb(data, signal, signal_data):
    global multiline_input

    if multiline_input == '1':
        return weechat.WEECHAT_RC_OK

    buffer = signal_data
    if not buffer:
        return weechat.WEECHAT_RC_OK

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(
        buffer)
    if not position or not aspell_suggest_item:
        cursor_pos = weechat.buffer_get_integer(buffer, 'input_pos')
        if get_localvar_aspell_suggest(
                buffer
        ) and cursor_pos > 0:  # save cursor position of misspelled word
            weechat.buffer_set(buffer, 'localvar_set_current_cursor_pos',
                               '%s' % cursor_pos)
        else:
            saved_cursor_pos = weechat.buffer_get_string(
                buffer, 'localvar_current_cursor_pos')
            if saved_cursor_pos != '':
                if int(cursor_pos) > int(saved_cursor_pos) + int(
                        OPTIONS['complete_near']) + 3:  # +3 to be sure!
                    delete_localvar_replace_mode(buffer)
        return weechat.WEECHAT_RC_OK

    # 1 = cursor etc., 2 = TAB, 3 = replace_mode
    if tab_complete != '0':
        if not aspell_suggest_item:
            aspell_suggest_item = ''
        weechat.buffer_set(buffer,
                           'localvar_set_spell_correction_suggest_item',
                           '%s:%s:%s' % ('0', position, aspell_suggest_item))
        return weechat.WEECHAT_RC_OK

    if OPTIONS['auto_replace'].lower() == "on":
        replace_misspelled_word(buffer)
        return weechat.WEECHAT_RC_OK

#    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:' % ('0','-1'))
    weechat.bar_item_update('spell_correction')
    weechat.bar_item_update('spell_suggestion')
    return weechat.WEECHAT_RC_OK
def ctcp_cb(data, modifier, modifier_data, string):
    if modifier_data != w.config_get_plugin("server"):
        return string
    msg_hash = w.info_get_hashtable("irc_message_parse", {"message": string})
    if msg_hash["command"] != "PRIVMSG":
        return string
    match = re.search('\001TYPING ([0-9])\001', msg_hash["arguments"])
    if match:
        nick = msg_hash["nick"]
        typing_level = int(match.groups()[0])
        if typing_level == 0 and nick in typing:
            del typing[nick]
        elif typing_level > 0:
            typing[nick] = typing_level
        w.bar_item_update("bitlbee_typing_notice")
        return ""
    else:
        return string
def aspell_suggest_cb(data, signal, signal_data):
    buffer = signal_data
    if OPTIONS['replace_mode'].lower() == 'on':
        localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
        if localvar_aspell_suggest:
            # aspell says, suggested word is also misspelled. check out if we already have a suggestion list and don't use the new misspelled word!
            if weechat.buffer_get_string(buffer,'localvar_inline_suggestions'):
                return weechat.WEECHAT_RC_OK
            if not ":" in localvar_aspell_suggest:
                return weechat.WEECHAT_RC_OK
            misspelled_word,aspell_suggestions = localvar_aspell_suggest.split(':')
            aspell_suggestions = aspell_suggestions.replace('/',',')
            weechat.buffer_set(buffer, 'localvar_set_inline_suggestions', '%s:%s:%s' % ('2','0',aspell_suggestions))
            weechat.bar_item_update('spell_suggestion')
            return weechat.WEECHAT_RC_OK

    if OPTIONS['auto_pop_up_item'].lower() == 'on':
        auto_suggest_cmd_cb('', buffer, '')
        weechat.buffer_set(buffer, 'localvar_del_spell_correction_suggest_input_line', '')
    weechat.bar_item_update('spell_suggestion')
    return weechat.WEECHAT_RC_OK
Example #44
0
def input_text_changed_cb(data, signal, signal_data):
    global multiline_input

    if multiline_input == '1':
        return weechat.WEECHAT_RC_OK

    buffer = signal_data
    if not buffer:
        return weechat.WEECHAT_RC_OK

        #    if OPTIONS['replace_mode'].lower() == "on" and weechat.buffer_get_string(buffer,'localvar_inline_replace_mode'):
        #        tab_complete,position,aspell_suggest_items = weechat.buffer_get_string(buffer,'localvar_inline_suggestions').split(':',2)
        #        weechat.buffer_set(buffer, 'localvar_set_inline_suggestions', '%s:%s:%s' % ('0',position,aspell_suggest_items))
        #        return weechat.WEECHAT_RC_OK

        return weechat.WEECHAT_RC_OK

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(
        buffer)
    if not position or not aspell_suggest_item:
        return weechat.WEECHAT_RC_OK

    # 1 = cursor etc., 2 = TAB, 3 = replace_mode
    if tab_complete != '0':
        if not aspell_suggest_item:
            aspell_suggest_item = ''
        weechat.buffer_set(buffer,
                           'localvar_set_spell_correction_suggest_item',
                           '%s:%s:%s' % ('0', position, aspell_suggest_item))
        weechat.bar_item_update('spell_correction')
        return weechat.WEECHAT_RC_OK

    if OPTIONS['auto_replace'].lower() == "on":
        replace_misspelled_word(buffer)
        return weechat.WEECHAT_RC_OK

#    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:' % ('0','-1'))
    weechat.bar_item_update('spell_correction')
    return weechat.WEECHAT_RC_OK
Example #45
0
def buffer_update(buffer):
	"""
	Refresh filtering in "buffer" by updating (or removing) the filter and update the bar item.
	"""

	hdata = weechat.hdata_get("buffer")

	buffers = ",".join(get_merged_buffers(buffer))
	name = "%s_%s" % (SCRIPT_NAME, buffers)

	if buffer_searching(buffer):
		if buffer_filtering(buffer):
			filter_addreplace(name, buffers, "*", buffer_build_regex(buffer))
		elif not buffer_filtering(buffer) and filter_exists(name):
			filter_del(name)
	elif filter_exists(name):
		filter_del(name)

	where = weechat.hdata_integer(hdata, buffer, "text_search_where")
	weechat.buffer_set(buffer, "localvar_set_%s_warn" % SCRIPT_LOCALVAR, "1" if where == 3 else "0") # warn about incorrect filter

	weechat.bar_item_update(SCRIPT_BAR_ITEM)
Example #46
0
def urlbar_cmd(data, buffer, args):
    """ Callback for /url command. """
    global urls, DISPLAY_ALL

    if args == "list":
        if urls:
            DISPLAY_ALL = True
            weechat.command("", '/bar show urlbar')
            weechat.bar_item_update("urlbar_urls")
        else:
            weechat.prnt('', 'URL list empty.')
    if args == "show":
        weechat.command('', '/bar show urlbar')
    elif args == 'hide':
        weechat.command("", "/bar hide urlbar")
    elif args == 'toggle':
        weechat.command("", "/bar toggle urlbar")
    elif args == 'clear':
        urls = []
    elif not args.startswith('url '):
        weechat.command("", "/help %s" % SCRIPT_COMMAND)

    return weechat.WEECHAT_RC_OK
def input_move_cb(data, signal, signal_data):
    buffer = signal

    if OPTIONS['replace_mode'].lower() == "on" and weechat.buffer_get_string(buffer,'localvar_inline_replace_mode') == "1":
        delete_localvar_replace_mode(buffer)
        weechat.buffer_set(buffer, 'localvar_del_spell_correction_suggest_item', '')
        return weechat.WEECHAT_RC_OK

    tab_complete,position,aspell_suggest_item = get_position_and_suggest_item(buffer)

    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
    if not localvar_aspell_suggest or not ":" in localvar_aspell_suggest:
        return weechat.WEECHAT_RC_OK

    misspelled_word,aspell_suggestions = localvar_aspell_suggest.split(':')

    if not aspell_suggest_item in aspell_suggestions:
        aspell_suggestion_list = aspell_suggestions.split(',',1)
        weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:%s' % ('1',0,aspell_suggestion_list[0]))
        weechat.bar_item_update('spell_correction')
        return weechat.WEECHAT_RC_OK

    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item', '%s:%s:%s' % ('1',position,aspell_suggest_item))
    return weechat.WEECHAT_RC_OK
Example #48
0
def mute(arg_list):
    """Depending on the args passed from the user, either toggle the mute state
    Or set mute to True for N minutes"""
    # Unhook any previous timers, because we are either unmuting, muting
    # indefinitely or setting a new timer
    prev_timer_hook = STATE.get('mute_timer')
    if prev_timer_hook:
        weechat.unhook(prev_timer_hook)
        weechat.prnt(
            '', 'unhooking previous mute timer, since this is a new '
            'mute')
        # If we had a previous timer, also zero out the countdown time
        STATE['mute_time'] = 0

    if len(arg_list) == 1:
        # Just toggle the mute state
        STATE['is_muted'] = not STATE['is_muted']
    elif len(arg_list) == 2:
        # A second arg, the time to remain muted, was provided
        time_to_mute = int(arg_list[1])

        STATE['is_muted'] = True

        # Store the mute time to be displayed in the status bar item, also
        # decrement it periodically so the bar item displays a countdown until
        # notifications will be unmuted
        STATE['mute_time'] = time_to_mute
        schedule_decrement(1)

        # Schedule alibnotify to be unmuted after we've hit the requested time
        timer_hook = weechat.hook_timer(time_to_mute * 1000 * 60, 0, 1,
                                        'unmute_cb', str(time_to_mute))
        STATE['mute_timer'] = timer_hook

    # update bar item to show the current mute state
    weechat.bar_item_update(SCRIPT_NAME)
Example #49
0
def cb_key_combo_default(data, signal, signal_data):
    """Eat and handle key events when in Normal mode, if needed.

    The key_combo_default signal is sent when a key combo is pressed. For
    example, alt-k will send the "\x01[k" signal.

    Esc is handled a bit differently to avoid delays, see `cb_key_pressed()`.
    """
    global esc_pressed, vi_buffer, cmd_text

    # If Esc was pressed, strip the Esc part from the pressed keys.
    # Example: user presses Esc followed by i. This is detected as "\x01[i",
    # but we only want to handle "i".
    keys = signal_data
    if esc_pressed or esc_pressed == -2:
        if keys.startswith("\x01[" * esc_pressed):
            # Multiples of 3 seem to "cancel" themselves,
            # e.g. Esc-Esc-Esc-Alt-j-11 is detected as "\x01[\x01[\x01"
            # followed by "\x01[j11" (two different signals).
            if signal_data == "\x01[" * 3:
                esc_pressed = -1  # `cb_check_esc()` will increment it to 0.
            else:
                esc_pressed = 0
        # This can happen if a valid combination is started but interrupted
        # with Esc, such as Ctrl-W→Esc→w which would send two signals:
        # "\x01W\x01[" then "\x01W\x01[w".
        # In that case, we still need to handle the next signal ("\x01W\x01[w")
        # so we use the special value "-2".
        else:
            esc_pressed = -2
        keys = keys.split('\x01[')[-1]  # Remove the "Esc" part(s).
    # Ctrl-Space.
    elif keys == "\x01@":
        set_mode("NORMAL")
        return weechat.WEECHAT_RC_OK_EAT

    # Nothing to do here.
    if mode == "INSERT":
        return weechat.WEECHAT_RC_OK

    # We're in Replace mode — allow 'normal' key presses (e.g. 'a') and
    # overwrite the next character with them, but let the other key presses
    # pass normally (e.g. backspace, arrow keys, etc).
    if mode == "REPLACE":
        if len(keys) == 1:
            weechat.command('', "/input delete_next_char")
        elif keys == "\x01?":
            weechat.command('', "/input move_previous_char")
            return weechat.WEECHAT_RC_OK_EAT
        return weechat.WEECHAT_RC_OK

    # We're catching keys! Only 'normal' key presses interest us (e.g. 'a'),
    # not complex ones (e.g. backspace).
    if len(keys) == 1 and catching_keys_data['amount']:
        catching_keys_data['keys'] += keys
        catching_keys_data['amount'] -= 1
        # Done catching keys, execute the callback.
        if catching_keys_data['amount'] == 0:
            globals()[catching_keys_data['callback']]()
            vi_buffer = ''
            weechat.bar_item_update("vi_buffer")
        return weechat.WEECHAT_RC_OK_EAT

    # We're in command-line mode.
    if cmd_text:
        # Backspace key.
        if keys == "\x01?":
            # Remove the last character from our command line.
            cmd_text = list(cmd_text)
            del cmd_text[-1]
            cmd_text = ''.join(cmd_text)
        # Return key.
        elif keys == "\x01M":
            weechat.hook_timer(1, 0, 1, "cb_exec_cmd", cmd_text)
            cmd_text = ''
        # Input.
        elif len(keys) == 1:
            cmd_text += keys
        # Update (and maybe hide) the bar item.
        weechat.bar_item_update("cmd_text")
        if not cmd_text:
            weechat.command('', "/bar hide vi_cmd")
        return weechat.WEECHAT_RC_OK_EAT
    # Enter command mode.
    elif keys == ':':
        cmd_text += ':'
        weechat.command('', "/bar show vi_cmd")
        weechat.bar_item_update("cmd_text")
        return weechat.WEECHAT_RC_OK_EAT

    # Add key to the buffer.
    vi_buffer += keys
    weechat.bar_item_update("vi_buffer")
    if not vi_buffer:
        return weechat.WEECHAT_RC_OK

    # Check if the keys have a (partial or full) match. If so, also get the
    # keys without the count. (These are the actual keys we should handle.)
    # After that, `vi_buffer` is only used for display purposes — only
    # `vi_keys` is checked for all the handling.
    # If no matches are found, the keys buffer is cleared.
    matched, vi_keys, count = get_keys_and_count(vi_buffer)
    if not matched:
        vi_buffer = ''
        return weechat.WEECHAT_RC_OK_EAT

    buf = weechat.current_buffer()
    input_line = weechat.buffer_get_string(buf, 'input')
    cur = weechat.buffer_get_integer(buf, "input_pos")

    # It's a key. If the corresponding value is a string, we assume it's a
    # WeeChat command. Otherwise, it's a method we'll call.
    if vi_keys in VI_KEYS:
        if isinstance(VI_KEYS[vi_keys], str):
            for _ in range(max(count, 1)):
                # This is to avoid crashing WeeChat on script reloads/unloads,
                # because no hooks must still be running when a script is
                # reloaded or unloaded.
                if VI_KEYS[vi_keys] == "/input return":
                    return weechat.WEECHAT_RC_OK
                weechat.command('', VI_KEYS[vi_keys])
                current_cur = weechat.buffer_get_integer(buf, "input_pos")
                set_cur(buf, input_line, current_cur)
        else:
            VI_KEYS[vi_keys](buf, input_line, cur, count)
    # It's a motion (e.g. 'w') — call `motion_X()` where X is the motion, then
    # set the cursor's position to what that function returned.
    elif vi_keys in VI_MOTIONS:
        if vi_keys in SPECIAL_CHARS:
            func = "motion_%s" % SPECIAL_CHARS[vi_keys]
        else:
            func = "motion_%s" % vi_keys
        end, _ = globals()[func](input_line, cur, count)
        set_cur(buf, input_line, end)
    # It's an operator + motion (e.g. 'dw') — call `motion_X()` (where X is
    # the motion), then we call `operator_Y()` (where Y is the operator)
    # with the position `motion_X()` returned. `operator_Y()` should then
    # handle changing the input line.
    elif (len(vi_keys) > 1 and vi_keys[0] in VI_OPERATORS
          and vi_keys[1:] in VI_MOTIONS):
        if vi_keys[1:] in SPECIAL_CHARS:
            func = "motion_%s" % SPECIAL_CHARS[vi_keys[1:]]
        else:
            func = "motion_%s" % vi_keys[1:]
        pos, overwrite = globals()[func](input_line, cur, count)
        oper = "operator_%s" % vi_keys[0]
        globals()[oper](buf, input_line, cur, pos, overwrite)
    # The combo isn't completed yet (e.g. just 'd').
    else:
        return weechat.WEECHAT_RC_OK_EAT

    # We've already handled the key combo, so clear the keys buffer.
    if not catching_keys_data['amount']:
        vi_buffer = ''
        weechat.bar_item_update("vi_buffer")
    return weechat.WEECHAT_RC_OK_EAT
Example #50
0
def update_cb(data, signal, signal_data):
    weechat.bar_item_update(SCRIPT_NAME)
    return weechat.WEECHAT_RC_OK
Example #51
0
def set_mode(arg):
    """Set the current mode and update the bar mode indicator."""
    global mode
    mode = arg
    weechat.bar_item_update("mode_indicator")
Example #52
0
def buffer_switch_cb(data, signal, signal_data):
    weechat.bar_item_update('spell_correction')
    return weechat.WEECHAT_RC_OK
Example #53
0
    OPTIONS[option] = value  # save new value
    weechat.bar_item_update(SCRIPT_NAME)
    return weechat.WEECHAT_RC_OK


# ================================[ main ]===============================
if __name__ == "__main__":
    #    global filter_status
    if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
                        SCRIPT_LICENSE, SCRIPT_DESC, '', ''):
        version = weechat.info_get("version_number", "") or 0

        if int(version) >= 0x00030600:
            filter_status = int(weechat.info_get('filters_enabled', ''))
            bar_item = weechat.bar_item_new(SCRIPT_NAME, 'show_item', '')
            weechat.bar_item_update(SCRIPT_NAME)
            weechat.hook_signal('buffer_line_added', 'update_cb', '')
            weechat.hook_signal('window_scrolled', 'update_cb', '')
            weechat.hook_signal('buffer_switch', 'update_cb', '')
            weechat.hook_signal('*filters*', 'filtered_update_cb', '')
            weechat.hook_command_run('/buffer clear*', 'update_cb', '')
            weechat.hook_command_run('/window page*', 'update_cb', '')
            weechat.hook_command_run('/input zoom_merged_buffer', 'update_cb',
                                     '')
            weechat.hook_config('plugins.var.python.' + SCRIPT_NAME + '.*',
                                'toggle_refresh', '')
            init_options()
        else:
            weechat.prnt(
                '', '%s%s %s' % (weechat.prefix('error'), SCRIPT_NAME,
                                 ': needs version 0.3.6 or higher'))
Example #54
0
def delete_localvar_replace_mode(buffer):
    if OPTIONS['replace_mode'].lower() == "on":
        weechat.buffer_set(buffer, 'localvar_del_inline_replace_mode', '')
        weechat.buffer_set(buffer, 'localvar_del_inline_suggestions', '')
        weechat.buffer_set(buffer, 'localvar_del_save_position_of_word', '')
        weechat.bar_item_update('spell_suggest')
Example #55
0
def input_complete_cb(data, buffer, command):

    # check if a misspelled word already exists!
    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
    if not localvar_aspell_suggest and not weechat.buffer_get_string(
            buffer, 'localvar_inline_replace_mode'):
        return weechat.WEECHAT_RC_OK

    # first [TAB] on a misspelled word in "replace mode"
    if OPTIONS['replace_mode'].lower(
    ) == "on" and not weechat.buffer_get_string(
            buffer, 'localvar_inline_replace_mode') and int(
                OPTIONS['complete_near']) >= 0:
        weechat.buffer_set(buffer, 'localvar_set_inline_replace_mode', '1')

        misspelled_word, aspell_suggestions = localvar_aspell_suggest.split(
            ':')
        begin_last_position, end_last_position, input_pos = get_last_position_of_misspelled_word(
            misspelled_word, buffer)

        # maybe nick completion?
        if begin_last_position == -1:
            delete_localvar_replace_mode(buffer)
            return weechat.WEECHAT_RC_OK

        if input_pos - end_last_position > int(OPTIONS['complete_near']):
            delete_localvar_replace_mode(buffer)
            return weechat.WEECHAT_RC_OK

        aspell_suggestions = aspell_suggestions.replace('/', ',')
        weechat.buffer_set(buffer, 'localvar_set_inline_suggestions',
                           '%s:%s:%s' % ('2', '0', aspell_suggestions))
        weechat.buffer_set(buffer, 'localvar_set_save_position_of_word',
                           '%s:%s' % (begin_last_position, end_last_position))
        inline_suggestions = aspell_suggestions.split(',')

        input_line = weechat.buffer_get_string(buffer, 'input')
        input_line = input_line[:begin_last_position] + inline_suggestions[
            0] + input_line[end_last_position:]

        #        input_line = input_line.replace(misspelled_word, inline_suggestions[0])
        word_differ = 0
        if len(misspelled_word) > len(inline_suggestions[0]):
            word_differ = len(misspelled_word) - len(inline_suggestions[0])
        else:
            word_differ = len(inline_suggestions[0]) - len(misspelled_word)
        if input_line[-2:] == '  ':
            input_line = input_line.rstrip()
            input_line = input_line + ' '

        weechat.buffer_set(buffer, 'input', input_line)
        input_pos = int(input_pos) + word_differ
        weechat.buffer_set(buffer, 'input_pos', str(input_pos))
        weechat.bar_item_update('spell_suggest')
        return weechat.WEECHAT_RC_OK

    # after first [TAB] on a misspelled word in "replace mode"
    if OPTIONS['replace_mode'].lower() == "on" and weechat.buffer_get_string(
            buffer, 'localvar_inline_replace_mode') == "1" and int(
                OPTIONS['complete_near']) >= 0:
        tab_complete, position, aspell_suggest_items = weechat.buffer_get_string(
            buffer, 'localvar_inline_suggestions').split(':', 2)

        if not position or not aspell_suggest_items:
            weechat.buffer_set(buffer, 'localvar_del_inline_replace_mode', '')
            return weechat.WEECHAT_RC_OK
        inline_suggestions = aspell_suggest_items.split(',')

        position = int(position)
        previous_position = position
        # cycle backwards through suggestions
        if command == '/input complete_previous':
            # position <= -1? go to last suggestion
            if position <= -1:
                position = len(inline_suggestions) - 1
            else:
                position -= 1
        # cycle forward through suggestions
        elif command == '/input complete_next':
            if position >= len(inline_suggestions) - 1:
                position = 0
            else:
                position += 1

        begin_last_position, end_last_position, input_pos = get_last_position_of_misspelled_word(
            inline_suggestions[previous_position], buffer)

        if input_pos - end_last_position > int(OPTIONS['complete_near']):
            delete_localvar_replace_mode(buffer)
            return weechat.WEECHAT_RC_OK

        input_line = weechat.buffer_get_string(buffer, 'input')
        input_line = input_line[:begin_last_position] + inline_suggestions[
            position] + input_line[end_last_position:]
        #        input_line = input_line.replace(inline_suggestions[previous_position], inline_suggestions[position])

        word_differ = 0
        if len(inline_suggestions[previous_position]) > len(
                inline_suggestions[position]):
            word_differ = len(inline_suggestions[previous_position]) - len(
                inline_suggestions[position])
        else:
            word_differ = len(inline_suggestions[position]) - len(
                inline_suggestions[previous_position])

        if input_line[-2:] == '  ':
            input_line = input_line.rstrip()
            input_line = input_line + ' '

        weechat.buffer_set(buffer, 'input', input_line)
        input_pos = int(input_pos) + word_differ
        weechat.buffer_set(buffer, 'input_pos', str(input_pos))

        weechat.buffer_set(
            buffer, 'localvar_set_inline_suggestions',
            '%s:%s:%s' % ('2', str(position), aspell_suggest_items))
        weechat.bar_item_update('spell_suggest')
        return weechat.WEECHAT_RC_OK

    if int(OPTIONS['complete_near']) > 0:
        misspelled_word, aspell_suggestions = localvar_aspell_suggest.split(
            ':')
        begin_last_position, end_last_position, input_pos = get_last_position_of_misspelled_word(
            misspelled_word, buffer)
        if input_pos - end_last_position > int(OPTIONS['complete_near']):
            return weechat.WEECHAT_RC_OK

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(
        buffer)
    weechat.buffer_set(buffer, 'localvar_set_spell_correction_suggest_item',
                       '%s:%s:%s' % ('2', position, aspell_suggest_item))

    auto_suggest_cmd_cb('', buffer, command)
    weechat.bar_item_update('spell_suggest')
    return weechat.WEECHAT_RC_OK
Example #56
0
def bar_config_update_cb(data, option):
    """Callback for updating the status bar when its config changes."""
    weechat.bar_item_update(SCRIPT_NAME)

    return weechat.WEECHAT_RC_OK
Example #57
0
def auto_suggest_cmd_cb(data, buffer, args):

    arguments = args.split(' ')

    input_line = weechat.buffer_get_string(buffer, 'input')
    weechat.buffer_set(buffer,
                       'localvar_set_spell_correction_suggest_input_line',
                       '%s' % input_line)

    if args.lower() == 'replace':
        replace_misspelled_word(buffer)
        return weechat.WEECHAT_RC_OK

#    if not weechat.buffer_get_string(buffer,'localvar_spell_correction_suggest_item'):
#        return weechat.WEECHAT_RC_OK

    tab_complete, position, aspell_suggest_item = get_position_and_suggest_item(
        buffer)
    if not position:
        position = -1

    if arguments[0].lower() == 'addword' and len(arguments) >= 2:
        found_dicts = get_aspell_dict_for(buffer)
        if len(found_dicts.split(",")) == 1 and len(arguments) == 2:
            word = arguments[1]
            weechat.command("", "/aspell addword %s" % word)
        elif arguments[1] in found_dicts.split(",") and len(arguments) == 3:
            word = arguments[2]
            weechat.command("", "/aspell addword %s %s" % (arguments[1], word))
        return weechat.WEECHAT_RC_OK

    # get localvar for misspelled_word and suggestions from buffer or return
    localvar_aspell_suggest = get_localvar_aspell_suggest(buffer)
    if not localvar_aspell_suggest:
        return weechat.WEECHAT_RC_OK

    misspelled_word, aspell_suggestions = localvar_aspell_suggest.split(':')

    aspell_suggestions = aspell_suggestions.replace('/', ',')
    aspell_suggestion_list = aspell_suggestions.split(',')
    if len(aspell_suggestion_list) == 0:
        position = -1
        weechat.bar_item_update('spell_correction')
        return weechat.WEECHAT_RC_OK

    # append an empty entry to suggestions to quit without changes.
    if OPTIONS['auto_replace'].lower() == "on":
        aspell_suggestion_list.append('')

    position = int(position)
    # cycle backwards through suggestions
    if args == '/input complete_previous' or args == 'previous':
        # position <= -1? go to last suggestion
        if position <= -1:
            position = len(aspell_suggestion_list) - 1
        position -= 1
    # cycle forward through suggestions
    else:
        if position >= len(aspell_suggestion_list) - 1:
            position = 0
        else:
            position += 1

    # 2 = TAB or command is called
    weechat.buffer_set(
        buffer, 'localvar_set_spell_correction_suggest_item',
        '%s:%s:%s' % ('2', str(position), aspell_suggestion_list[position]))

    weechat.bar_item_update('spell_correction')
    return weechat.WEECHAT_RC_OK
Example #58
0
def logger_level_update_cb(data, option, value):
    """Callback called when any logger level changes."""
    weechat.bar_item_update(SCRIPT_NAME)

    return weechat.WEECHAT_RC_OK
Example #59
0
def input_text_changed_cb(data, signal, buffer):
    if active:
        input = weechat.buffer_get_string(buffer, "input")
        set_localvars(input)
        weechat.bar_item_update(SCRIPT_BAR_ITEM)
    return weechat.WEECHAT_RC_OK
Example #60
0
def cb_timer_update_line_numbers(data, remaining_calls):
    """Update the line numbers bar item."""
    weechat.bar_item_update("line_numbers")
    return weechat.WEECHAT_RC_OK