Exemplo n.º 1
0
def count_lines(winpointer, bufpointer):

    hdata_buf = weechat.hdata_get('buffer')
    hdata_lines = weechat.hdata_get('lines')
    lines = weechat.hdata_pointer(hdata_buf, bufpointer,
                                  'lines')  # own_lines, mixed_lines
    lines_count = weechat.hdata_integer(hdata_lines, lines, 'lines_count')

    hdata_window = weechat.hdata_get('window')
    hdata_winscroll = weechat.hdata_get('window_scroll')
    window_scroll = weechat.hdata_pointer(hdata_window, winpointer, 'scroll')
    lines_after = weechat.hdata_integer(hdata_winscroll, window_scroll,
                                        'lines_after')
    window_height = weechat.window_get_integer(weechat.current_window(),
                                               'win_chat_height')

    if lines_count > window_height:
        differential = lines_count - window_height
        percent = max(
            int(round(100. * (differential - lines_after) / differential)), 0)
    else:
        percent = 100
    #weechat.prnt('', " : lines_count "+str(lines_count)+" window_height "+str(window_height)+" lines after "+str(lines_after))
    current_line = lines_count - lines_after
    return lines_after, lines_count, percent, current_line
Exemplo n.º 2
0
def get_time_from_line(ptr_buffer):
    lines = weechat.hdata_pointer(weechat.hdata_get('buffer'), ptr_buffer, 'own_lines')

    if lines:
        line = weechat.hdata_pointer(weechat.hdata_get('lines'), lines, 'last_line')
        last_read_line = weechat.hdata_pointer(weechat.hdata_get('lines'), lines, 'last_read_line')
        # last line already read?
        while line != last_read_line:
            hdata_line = weechat.hdata_get('line')
            hdata_line_data = weechat.hdata_get('line_data')

            data = weechat.hdata_pointer(hdata_line, line, 'data')

            date_last_line = weechat.hdata_time(hdata_line_data, data, 'date')
            displayed = weechat.hdata_char(hdata_line_data, data, 'displayed')
            # message hidden?
            if not displayed and OPTIONS['ignore_hidden'].lower() == 'on':
                prev_line = weechat.hdata_pointer(hdata_line, line, 'prev_line')
                line = prev_line
                continue

            # buffer empty?
            if not date_last_line:
                return 0

            get_current_ticks = time.time()

            time_gone = get_current_ticks - date_last_line
            if int(OPTIONS['time']) < time_gone:
                return 1
            else:
                return 0
    return 0
Exemplo n.º 3
0
def unhide_buffer_cb(data, signal, signal_data):
    """Unhide a buffer on new activity.

    This callback unhides a buffer in which a new message has been received.
    If configuration option ``unhide_low`` is enabled,
    buffers with only low priority messages (like JOIN, PART, etc.) will be unhidden as well.

    :param data: Pointer
    :param signal: Signal sent by Weechat
    :param signal_data: Data sent with signal
    :returns: Callback return value expected by Weechat.
    """
    hotlist = hotlist_dict()
    line_data = weechat.hdata_pointer(weechat.hdata_get('line'), signal_data, 'data')
    buffer = weechat.hdata_pointer(weechat.hdata_get('line_data'), line_data, 'buffer')

    if not buffer in hotlist.keys():
        # just some background noise
        return WEECHAT_RC_OK

    if (weechat.config_get_plugin("unhide_low") == "on"
            and hotlist[buffer]["count_low"] > 0
            or hotlist[buffer]["count_message"] > 0
            or hotlist[buffer]["count_private"] > 0
            or hotlist[buffer]["count_highlight"] > 0):
        remove_keep_alive(buffer)
        weechat.buffer_set(buffer, "hidden", "0")

    return WEECHAT_RC_OK
Exemplo n.º 4
0
def count_lines(ptr_window, ptr_buffer):
    global filter_status

    hdata_buf = weechat.hdata_get("buffer")
    hdata_lines = weechat.hdata_get("lines")
    lines = weechat.hdata_pointer(hdata_buf, ptr_buffer, "lines")  # own_lines, mixed_lines
    lines_count = weechat.hdata_integer(hdata_lines, lines, "lines_count")

    hdata_window = weechat.hdata_get("window")
    hdata_winscroll = weechat.hdata_get("window_scroll")
    window_scroll = weechat.hdata_pointer(hdata_window, ptr_window, "scroll")
    lines_after = weechat.hdata_integer(hdata_winscroll, window_scroll, "lines_after")
    window_height = weechat.window_get_integer(weechat.current_window(), "win_chat_height")

    filtered = 0
    filtered_before = 0
    filtered_after = 0
    # if filter is disabled, don't count.
    if (OPTIONS["count_filtered_lines"].lower() == "off") and filter_status == 1:
        filtered, filtered_before, filtered_after = count_filtered_lines(ptr_buffer, lines_count, lines_after)
        lines_count = lines_count - filtered
    #        lines_after = lines_after - filtered_after

    if lines_count > window_height:
        differential = lines_count - window_height
        percent = max(int(round(100.0 * (differential - lines_after) / differential)), 0)
    else:
        percent = 100

    # get current position
    current_line = lines_count - lines_after

    return lines_after, lines_count, percent, current_line, filtered, filtered_before, filtered_after
Exemplo n.º 5
0
def count_filtered_lines(ptr_buffer, lines_count, lines_after):
    filtered_before = 0
    filtered_after = 0
    filtered = 0

    lines = weechat.hdata_pointer(weechat.hdata_get("buffer"), ptr_buffer, "own_lines")
    counter = 0
    current_position = lines_count - lines_after

    if lines:
        line = weechat.hdata_pointer(weechat.hdata_get("lines"), lines, "first_line")
        hdata_line = weechat.hdata_get("line")
        hdata_line_data = weechat.hdata_get("line_data")

        while line:
            data = weechat.hdata_pointer(hdata_line, line, "data")
            if data:
                #                message = weechat.hdata_string(hdata_line_data, data, 'message')
                displayed = weechat.hdata_char(hdata_line_data, data, "displayed")
                if displayed == 0:
                    #                    weechat.prnt('','%d - %s - %s' % (counter, displayed, message))
                    if counter < current_position:
                        filtered_before += 1
                    else:
                        filtered_after += 1
            counter += 1
            line = weechat.hdata_move(hdata_line, line, 1)

    filtered = filtered_before + filtered_after
    return filtered, filtered_before, filtered_after
Exemplo n.º 6
0
def bufsave_cmd(data, buffer, args):
    filename = weechat.buffer_get_string(
        buffer, 'localvar_server') + '.' + weechat.buffer_get_string(
            buffer,
            'localvar_channel')[1:] + '-' + time.strftime('%y_%m_%d') + '.log'
    filename = weechat.string_eval_path_home('%h/logs/' + filename, {}, {}, {})
    try:
        fp = open(filename, 'w')
    except:
        weechat.prnt('', 'Error writing to target file!')
        return weechat.WEECHAT_RC_OK
    own_lines = weechat.hdata_pointer(weechat.hdata_get('buffer'), buffer,
                                      'own_lines')
    if own_lines:
        line = weechat.hdata_pointer(weechat.hdata_get('lines'), own_lines,
                                     'first_line')
        hdata_line = weechat.hdata_get('line')
        hdata_line_data = weechat.hdata_get('line_data')
        while line:
            data = weechat.hdata_pointer(hdata_line, line, 'data')
            if data:
                date = weechat.hdata_time(hdata_line_data, data, 'date')
                if not isinstance(date, str):
                    date = time.strftime('%F %T', time.localtime(int(date)))
                fp.write('{0} {1} {2}\n'.format(
                    date,
                    cstrip(
                        weechat.hdata_string(hdata_line_data, data, 'prefix')),
                    cstrip(
                        weechat.hdata_string(hdata_line_data, data,
                                             'message'))))
            line = weechat.hdata_move(hdata_line, line, 1)
    fp.close()
    return weechat.WEECHAT_RC_OK
Exemplo n.º 7
0
def count_filtered_lines(ptr_buffer, lines_count, lines_after):
    filtered_before = 0
    filtered_after = 0
    filtered = 0

    lines = weechat.hdata_pointer(weechat.hdata_get('buffer'), ptr_buffer,
                                  'own_lines')
    counter = 0
    current_position = lines_count - lines_after

    if lines:
        line = weechat.hdata_pointer(weechat.hdata_get('lines'), lines,
                                     'first_line')
        hdata_line = weechat.hdata_get('line')
        hdata_line_data = weechat.hdata_get('line_data')

        while line:
            data = weechat.hdata_pointer(hdata_line, line, 'data')
            if data:
                #                message = weechat.hdata_string(hdata_line_data, data, 'message')
                displayed = weechat.hdata_char(hdata_line_data, data,
                                               'displayed')
                if displayed == 0:
                    #                    weechat.prnt('','%d - %s - %s' % (counter, displayed, message))
                    if counter < current_position:
                        filtered_before += 1
                    else:
                        filtered_after += 1
            counter += 1
            line = weechat.hdata_move(hdata_line, line, 1)

    filtered = filtered_before + filtered_after
    return filtered, filtered_before, filtered_after
Exemplo n.º 8
0
def count_lines(ptr_window,ptr_buffer):
    global filter_status

    hdata_buf = weechat.hdata_get('buffer')
    hdata_lines = weechat.hdata_get('lines')
    lines = weechat.hdata_pointer(hdata_buf, ptr_buffer, 'lines') # own_lines, mixed_lines
    lines_count = weechat.hdata_integer(hdata_lines, lines, 'lines_count')

    hdata_window = weechat.hdata_get('window')
    hdata_winscroll = weechat.hdata_get('window_scroll')
    window_scroll = weechat.hdata_pointer(hdata_window, ptr_window, 'scroll')
    lines_after = weechat.hdata_integer(hdata_winscroll, window_scroll, 'lines_after')
    window_height = weechat.window_get_integer(weechat.current_window(), 'win_chat_height')

    filtered = 0
    filtered_before = 0
    filtered_after = 0
    # if filter is disabled, don't count.
    if (OPTIONS['count_filtered_lines'].lower() == 'off') and filter_status == 1:
        filtered, filtered_before,filtered_after = count_filtered_lines(ptr_buffer,lines_count,lines_after)
        lines_count = lines_count - filtered
#        lines_after = lines_after - filtered_after

    if lines_count > window_height:
        differential = lines_count - window_height
        percent = max(int(round(100. * (differential - lines_after) / differential)), 0)
    else:
        percent = 100

    # get current position
    current_line = lines_count - lines_after

    return lines_after,lines_count,percent,current_line, filtered, filtered_before, filtered_after
Exemplo n.º 9
0
def layout_apply_cb(data, buffer, command):
    if weechat.config_string_to_boolean(
            weechat.config_get_plugin("layout_apply")):
        m = LAYOUT_APPLY_RE.match(command)
        if m:
            layout_name = m.group(1) or "default"
            hdata_layout = weechat.hdata_get("layout")
            layouts = weechat.hdata_get_list(hdata_layout, "gui_layouts")
            layout = weechat.hdata_search(hdata_layout, layouts,
                                          "${layout.name} == " + layout_name,
                                          1)
            if layout:
                hdata_layout_buffer = weechat.hdata_get("layout_buffer")
                layout_buffer = weechat.hdata_pointer(hdata_layout, layout,
                                                      "layout_buffers")
                while layout_buffer:
                    plugin_name = weechat.hdata_string(hdata_layout_buffer,
                                                       layout_buffer,
                                                       "plugin_name")
                    buffer_name = weechat.hdata_string(hdata_layout_buffer,
                                                       layout_buffer,
                                                       "buffer_name")
                    full_name = "{}.{}".format(plugin_name, buffer_name)

                    buffer = weechat.buffer_search("==", full_name)
                    if not buffer:
                        buffer_open_full_name(full_name, noswitch=True)

                    layout_buffer = weechat.hdata_move(hdata_layout_buffer,
                                                       layout_buffer, 1)
    return weechat.WEECHAT_RC_OK
Exemplo n.º 10
0
def bufsave_cmd(data, buffer, args):
    ''' Callback for /bufsave command '''

    filename_raw = args

    if not filename_raw:
        w.command('', '/help %s' % SCRIPT_COMMAND)
        return w.WEECHAT_RC_OK

    filename = w.string_eval_path_home(filename_raw, {}, {}, {})

    if exists(filename):
        w.prnt('', 'Error: target file already exists!')
        return w.WEECHAT_RC_OK

    try:
        fp = open(filename, 'w')
    except:
        w.prnt('', 'Error writing to target file!')
        return w.WEECHAT_RC_OK

    version = w.info_get('version_number', '') or 0
    if int(version) >= 0x00030600:
        # use hdata with WeeChat >= 0.3.6 (direct access to data, very fast)
        own_lines = w.hdata_pointer(w.hdata_get('buffer'), buffer, 'own_lines')
        if own_lines:
            line = w.hdata_pointer(w.hdata_get('lines'), own_lines,
                                   'first_line')
            hdata_line = w.hdata_get('line')
            hdata_line_data = w.hdata_get('line_data')
            while line:
                data = w.hdata_pointer(hdata_line, line, 'data')
                if data:
                    date = w.hdata_time(hdata_line_data, data, 'date')
                    # since WeeChat 0.3.9, hdata_time returns long instead of string
                    if not isinstance(date, str):
                        date = time.strftime('%F %T',
                                             time.localtime(int(date)))
                    fp.write('%s %s %s\n' %(\
                            date,
                            cstrip(w.hdata_string(hdata_line_data, data, 'prefix')),
                            cstrip(w.hdata_string(hdata_line_data, data, 'message')),
                            ))
                line = w.hdata_move(hdata_line, line, 1)
    else:
        # use infolist with WeeChat <= 0.3.5 (full duplication of lines, slow and uses memory)
        infolist = w.infolist_get('buffer_lines', buffer, '')
        while w.infolist_next(infolist):
            fp.write('%s %s %s\n' %(\
                    w.infolist_time(infolist, 'date'),
                    cstrip(w.infolist_string(infolist, 'prefix')),
                    cstrip(w.infolist_string(infolist, 'message')),
                    ))
        w.infolist_free(infolist)

    fp.close()

    return w.WEECHAT_RC_OK
Exemplo n.º 11
0
def bufsave_cmd(data, buffer, args):
    ''' Callback for /bufsave command '''

    filename_raw = args

    if not filename_raw:
        w.command('', '/help %s' %SCRIPT_COMMAND)
        return w.WEECHAT_RC_OK
    
    filename = w.string_eval_path_home(filename_raw, {}, {}, {})

    if exists(filename):
        w.prnt('', 'Error: target file already exists!')
        return w.WEECHAT_RC_OK

    try:
        fp = open(filename, 'w')
    except:
        w.prnt('', 'Error writing to target file!')
        return w.WEECHAT_RC_OK

    version = w.info_get('version_number', '') or 0
    if int(version) >= 0x00030600:
        # use hdata with WeeChat >= 0.3.6 (direct access to data, very fast)
        own_lines = w.hdata_pointer(w.hdata_get('buffer'), buffer, 'own_lines')
        if own_lines:
            line = w.hdata_pointer(w.hdata_get('lines'), own_lines, 'first_line')
            hdata_line = w.hdata_get('line')
            hdata_line_data = w.hdata_get('line_data')
            while line:
                data = w.hdata_pointer(hdata_line, line, 'data')
                if data:
                    date = w.hdata_time(hdata_line_data, data, 'date')
                    # since WeeChat 0.3.9, hdata_time returns long instead of string
                    if not isinstance(date, str):
                        date = time.strftime('%F %T', time.localtime(int(date)))
                    fp.write('%s %s %s\n' %(\
                            date,
                            cstrip(w.hdata_string(hdata_line_data, data, 'prefix')),
                            cstrip(w.hdata_string(hdata_line_data, data, 'message')),
                            ))
                line = w.hdata_move(hdata_line, line, 1)
    else:
        # use infolist with WeeChat <= 0.3.5 (full duplication of lines, slow and uses memory)
        infolist = w.infolist_get('buffer_lines', buffer, '')
        while w.infolist_next(infolist):
            fp.write('%s %s %s\n' %(\
                    w.infolist_time(infolist, 'date'),
                    cstrip(w.infolist_string(infolist, 'prefix')),
                    cstrip(w.infolist_string(infolist, 'message')),
                    ))
        w.infolist_free(infolist)

    fp.close()

    return w.WEECHAT_RC_OK
Exemplo n.º 12
0
def test12(data, buffer, arg):
    own_lines = weechat.hdata_pointer(weechat.hdata_get("buffer"), buffer,
                                      'own_lines')
    line = weechat.hdata_pointer(weechat.hdata_get('lines'), own_lines,
                                 'last_line')
    hdata_line_data = weechat.hdata_get('line_data')
    hdata_line = weechat.hdata_get('line')
    d = weechat.hdata_pointer(hdata_line, line, 'data')
    weechat.prnt(buffer, weechat.hdata_string(hdata_line_data, d, 'message'))
    weechat.prnt(buffer, weechat.hdata_string(hdata_line_data, d, 'prefix'))
    return weechat.WEECHAT_RC_OK
Exemplo n.º 13
0
def logexport_export_cmd(buff, exportFile, mustExportLine):
    """ Called when an export function is called, as `/logexport time`.

    `exportFile` is the name of the file to which we will export.

    `mustExportLine`, when fed a message line (ie. `timestamp, prefix, msg`),
    should return `True` iff this line should be included in the export. The
    lines will be fed one by one starting from the most recent.
    When all the lines that should be exported have been checked, this function
    should raise `StopExport` to avoid looping uselessly through all the
    backlog.
    It is eventually called with `None, None, None` when the top of the backlog
    is reached, and could raise an exception at this time if something went
    wrong.
    """

    cBuffer = weechat.hdata_get('buffer')
    lines = weechat.hdata_pointer(cBuffer, buff, 'lines')
    # 'lines' and not 'own_lines': match what the user sees.

    cLine = weechat.hdata_pointer(weechat.hdata_get('lines'), lines,
                                  'last_line')
    hdata_line = weechat.hdata_get('line')
    hdata_line_data = weechat.hdata_get('line_data')

    gathered = []
    reachedTop = True  # Only False if we `break` at some point
    while cLine:
        data = weechat.hdata_pointer(hdata_line, cLine, 'data')
        if data:
            timestamp = weechat.hdata_time(hdata_line_data, data, 'date')
            prefix = weechat.hdata_string(hdata_line_data, data, 'prefix')
            msg = weechat.hdata_string(hdata_line_data, data, 'message')

            try:
                if mustExportLine(timestamp, prefix, msg):
                    gathered.append(LogLine(timestamp, prefix, msg))
            except StopExport:
                reachedTop = False
                break

        cLine = weechat.hdata_pointer(hdata_line, cLine, 'prev_line')

    if reachedTop:
        # Give `mustExportLine` the chance to signal something went wrong.
        mustExportLine(None, None, None)

    html = renderHtml(gathered[::-1], buff)
    writeFile(html, formatFilePath(exportFile))
Exemplo n.º 14
0
def get_merged_buffers(ptr):
    """
	Get a list of buffers which are merged with "ptr".
	"""

    hdata = weechat.hdata_get("buffer")
    buffers = weechat.hdata_get_list(hdata, "gui_buffers")
    buffer = weechat.hdata_search(
        hdata, buffers,
        "${buffer.number} == %i" % weechat.hdata_integer(hdata, ptr, "number"),
        1)
    nbuffer = weechat.hdata_move(hdata, buffer, 1)

    ret = []
    while buffer:
        ret.append(weechat.hdata_string(hdata, buffer, "full_name"))

        if (weechat.hdata_integer(hdata, buffer,
                                  "number") == weechat.hdata_integer(
                                      hdata, nbuffer, "number")):
            buffer = nbuffer
            nbuffer = weechat.hdata_move(hdata, nbuffer, 1)
        else:
            buffer = None

    return ret
Exemplo n.º 15
0
def buffer_build_regex(buffer):
	"""
	Build a regex according to "buffer"'s search settings.
	"""

	hdata = weechat.hdata_get("buffer")
	input = weechat.hdata_string(hdata, buffer, "input_buffer")
	exact = weechat.hdata_integer(hdata, buffer, "text_search_exact")
	where = weechat.hdata_integer(hdata, buffer, "text_search_where")
	regex = weechat.hdata_integer(hdata, buffer, "text_search_regex")

	if not regex:
		input = re.escape(input)

	if exact:
		input = "(?-i)%s" % input

	filter_regex = None
	if where == 1: # message
		filter_regex = input
	elif where == 2: # prefix
		filter_regex = "%s\\t" % input
	else: # prefix | message
		filter_regex = input # TODO: impossible with current filter regex

	return "!%s" % filter_regex
Exemplo n.º 16
0
def hotlist_item_cb(data, item, window):
    priorities = {}
    titles = {}

    hdata_hotlist = w.hdata_get('hotlist')
    ptr_hotlist = w.hdata_get_list(hdata_hotlist, 'gui_hotlist')
    while ptr_hotlist:
        priority = w.hdata_integer(hdata_hotlist, ptr_hotlist, 'priority')
        buffer = w.hdata_pointer(hdata_hotlist, ptr_hotlist, 'buffer')
        count = w.hdata_integer(
            hdata_hotlist, ptr_hotlist, '%d|count' % GUI_HOTLIST_MESSAGE)
        number = w.buffer_get_integer(buffer, 'number')
        name = w.buffer_get_string(buffer, 'short_name')

        if priority != GUI_HOTLIST_LOW:
            priorities[number] = priority
            titles[number] = '%d:%s' % (number, name)
            if count:
                titles[number] += '(%d)' % count

        ptr_hotlist = w.hdata_move(hdata_hotlist, ptr_hotlist, 1)

    items = []
    for number, priority in sorted(priorities.items()):
        items.append('%s %s %s' % (
            w.color(COLORS[priority]),
            titles[number],
            w.color('reset')))
    return ' '.join(items)
Exemplo n.º 17
0
def filter_exists(name):
    """
    Check whether a filter named "name" exists.
    """

    weechat_version = int(weechat.info_get("version_number", "") or 0)

    hdata = weechat.hdata_get("filter")
    filters = weechat.hdata_get_list(hdata, "gui_filters")
    if weechat_version >= 0x03040000:
        filter = weechat.hdata_search(
            hdata,
            filters,
            "${filter.name} == ${name}",
            {},
            {"name": name},
            {},
            1,
        )
    else:
        filter = weechat.hdata_search(
            hdata,
            filters,
            "${filter.name} == %s" % name,
            1,
        )

    return bool(filter)
Exemplo n.º 18
0
def buffer_build_regex(buffer):
    """
    Build a regex according to "buffer"'s search settings.
    """

    hdata = weechat.hdata_get("buffer")
    input = weechat.hdata_string(hdata, buffer, "input_buffer")
    exact = weechat.hdata_integer(hdata, buffer, "text_search_exact")
    where = weechat.hdata_integer(hdata, buffer, "text_search_where")
    regex = weechat.hdata_integer(hdata, buffer, "text_search_regex")

    if not regex:
        input = re.escape(input)

    if exact:
        input = "(?-i)%s" % input

    filter_regex = None
    if where == 1:  # message
        filter_regex = input
    elif where == 2:  # prefix
        filter_regex = "%s\\t" % input
    else:  # prefix | message
        filter_regex = input  # TODO: impossible with current filter regex

    return "!%s" % filter_regex
Exemplo n.º 19
0
def handle_isupport_end_msg(data, signal, signal_data):
    global main_server

    server_name = signal.split(",")[0]
    netid = weechat.info_get("irc_server_isupport_value",
                             server_name + ",BOUNCER_NETID")

    if netid != "":
        added_networks[netid] = True

    server = server_by_name(server_name)

    hdata = weechat.hdata_get("irc_server")
    cap_list = weechat.hdata_hashtable(hdata, server, "cap_list")
    if not BOUNCER_CAP in cap_list:
        return weechat.WEECHAT_RC_OK

    if main_server is not None:
        return weechat.WEECHAT_RC_OK
    main_server = server_name

    weechat.command(weechat.buffer_search("irc", "server." + server_name),
                    "/quote BOUNCER LISTNETWORKS")

    return weechat.WEECHAT_RC_OK
Exemplo n.º 20
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)
Exemplo n.º 21
0
def exclude_server():
    global OPTIONS
    for server_exclude in OPTIONS['server_exclude'].split(','):
        if server_exclude == '*':  # show buffer for all server
            weechat.command(
                '', '/buffer unhide -all')  # simply unload script, no!? :-)
            break

        # search exclude server in list of servers
        hdata = weechat.hdata_get('irc_server')
        servers = weechat.hdata_get_list(hdata, 'irc_servers')
        if int(version) >= 0x03040000:
            server = weechat.hdata_search(
                hdata,
                servers,
                '${irc_server.name} =* ${server_name}',
                {},
                {'server_name': server_exclude},
                {},
                1,
            )
        else:
            server = weechat.hdata_search(
                hdata,
                servers,
                '${irc_server.name} =* %s' % server_exclude,
                1,
            )
        if server:
            #            is_connected    = weechat.hdata_integer(hdata, server, "is_connected")
            #            nick_modes      = weechat.hdata_string(hdata, server, "nick_modes")
            buffer_ptr = weechat.hdata_pointer(hdata, server, 'buffer')
            weechat.command(buffer_ptr, '/allchan -current /buffer unhide')
    return
Exemplo n.º 22
0
def read_history(filename, ptr_buffer):
    global_history = 0

    # get buffer_autoset_option as a fallback. could happen that the localvar is not already set to buffer
    plugin = weechat.buffer_get_string(ptr_buffer, 'localvar_plugin')
    name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
    buffer_autoset_option = (
        'buffer_autoset.buffer.%s.%s.localvar_set_save_history' %
        (plugin, name))
    buffer_autoset_option = weechat.config_get(buffer_autoset_option)

    # global history does not use buffer pointers!
    if filename == filename_global_history:
        global_history = 1

    filename = get_filename_with_path(filename)

    # filename exists?
    if not os.path.isfile(filename):
        return

    # check for buffer history (0, global = 1)
    if global_history == 0 and OPTIONS['save_buffer'].lower() == 'off':
        # localvar_save_history exists for buffer?
        if not ptr_buffer and not buffer_autoset_option and not weechat.buffer_get_string(
                ptr_buffer, 'localvar_save_history'):
            return
    hdata = weechat.hdata_get('history')
    if not hdata:
        return

    try:
        f = open(filename, 'r')
        #        for line in f.xreadlines():    # old python 2.x
        for line in f:  # should also work with python 2.x
            #            line = line.decode('utf-8')
            line = str(line.strip())
            if ptr_buffer:
                # add to buffer history
                weechat.hdata_update(hdata, '', {
                    'buffer': ptr_buffer,
                    'text': line
                })
            else:
                # add to global history
                weechat.hdata_update(hdata, '', {'text': line})
        f.close()
    except:
        if global_history == 1:
            weechat.prnt(
                '', '%s%s: Error loading global history from "%s"' %
                (weechat.prefix('error'), SCRIPT_NAME, filename))
        else:
            name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
            weechat.prnt(
                '',
                '%s%s: Error loading buffer history for buffer "%s" from "%s"'
                % (weechat.prefix('error'), SCRIPT_NAME, name, filename))
        raise
Exemplo n.º 23
0
def buffer_searching(buffer):
	"""
	Check whether "buffer" is in search mode.
	"""

	hdata = weechat.hdata_get("buffer")

	return bool(weechat.hdata_integer(hdata, buffer, "text_search"))
Exemplo n.º 24
0
def buffer_searching(buffer):
    """
    Check whether "buffer" is in search mode.
    """

    hdata = weechat.hdata_get("buffer")

    return bool(weechat.hdata_integer(hdata, buffer, "text_search"))
Exemplo n.º 25
0
def get_hdata():
    """Get list of hdata hooked by plugins in a dict with 3 indexes: plugin, name, xxx."""
    hdata = defaultdict(lambda: defaultdict(defaultdict))
    infolist = weechat.infolist_get('hook', '', 'hdata')
    while weechat.infolist_next(infolist):
        hdata_name = weechat.infolist_string(infolist, 'hdata_name')
        plugin = weechat.infolist_string(infolist, 'plugin_name') or 'weechat'
        hdata[plugin][hdata_name]['description'] = weechat.infolist_string(infolist, 'description')
        variables = ''
        variables_update = ''
        lists = ''
        ptr_hdata = weechat.hdata_get(hdata_name)
        if ptr_hdata:
            hdata2 = []
            string = weechat.hdata_get_string(ptr_hdata, 'var_keys_values')
            if string:
                for item in string.split(','):
                    key = item.split(':')[0]
                    var_offset = weechat.hdata_get_var_offset(ptr_hdata, key)
                    var_array_size = weechat.hdata_get_var_array_size_string(ptr_hdata, '', key)
                    if var_array_size:
                        var_array_size = ', array_size: "%s"' % var_array_size
                    var_hdata = weechat.hdata_get_var_hdata(ptr_hdata, key)
                    if var_hdata:
                        var_hdata = ', hdata: "%s"' % var_hdata
                    type_string = weechat.hdata_get_var_type_string(ptr_hdata, key)
                    hdata2.append({'offset': var_offset,
                                   'text': '\'%s\' (%s)' % (key, type_string),
                                   'textlong': '\'%s\' (%s%s%s)' % (key, type_string, var_array_size, var_hdata),
                                   'update': weechat.hdata_update(ptr_hdata, '', { '__update_allowed': key })})
                hdata2 = sorted(hdata2, key=itemgetter('offset'))
                for item in hdata2:
                    if variables:
                        variables += ' +\n'
                    variables += '  %s' % item['textlong']
                    if item['update']:
                        if variables_update:
                            variables_update += ' +\n'
                        variables_update += '  %s' % item['text']
                if weechat.hdata_update(ptr_hdata, '', { '__delete_allowed' : '' }):
                    if variables_update:
                        variables_update += ' +\n'
                    variables_update += '  \'__delete\''
            hdata[plugin][hdata_name]['vars'] = '\n%s' % variables
            hdata[plugin][hdata_name]['vars_update'] = '\n%s' % variables_update

            string = weechat.hdata_get_string(ptr_hdata, 'list_keys')
            if string:
                for item in sorted(string.split(',')):
                    if lists:
                        lists += ' +\n'
                    lists += '  \'%s\'' % item
                lists = '\n%s' % lists
            else:
                lists = '\n  -'
            hdata[plugin][hdata_name]['lists'] = lists
    weechat.infolist_free(infolist)
    return hdata
Exemplo n.º 26
0
def get_last_message_time(buffer):
    lines = weechat.hdata_pointer(weechat.hdata_get("buffer"), buffer,
                                  "own_lines")
    line = weechat.hdata_pointer(weechat.hdata_get("lines"), lines,
                                 "last_line")
    while line:
        line_data = weechat.hdata_pointer(weechat.hdata_get("line"), line,
                                          "data")
        tags_count = weechat.hdata_integer(weechat.hdata_get("line_data"),
                                           line_data, "tags_count")
        tags = [
            weechat.hdata_string(weechat.hdata_get("line_data"), line_data,
                                 "{}|tags_array".format(i))
            for i in range(tags_count)
        ]
        irc_tags = [t for t in tags if t.startswith("irc_")]
        if len(irc_tags) > 0:
            break
        line = weechat.hdata_pointer(weechat.hdata_get("line"), line,
                                     "prev_line")
    if not line:
        return None
    # TODO: get timestamp with millisecond granularity
    ts = weechat.hdata_time(weechat.hdata_get("line_data"), line_data, "date")
    t = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)
    return t
Exemplo n.º 27
0
def fill_last_lines(buffer):
    last_lines.append(get_input_line(buffer, -1))
    hdata = w.hdata_get("buffer")
    lines = w.hdata_pointer(hdata, buffer, "own_lines")

    found = 0
    processed = 0
    lines_limit = int(w.config_get_plugin("lines"))
    raw_lines_limit = int(w.config_get_plugin("raw_lines"))
    line  = w.hdata_pointer(w.hdata_get('lines'), lines, "last_line")

    while found < lines_limit and processed < raw_lines_limit and line != "":
        line_data = w.hdata_pointer(w.hdata_get('line'), line, "data")

        count = w.hdata_integer(w.hdata_get("line_data"), line_data, "tags_count")
        if count == 0:
            processed += 1
            continue

        tag = w.hdata_string(w.hdata_get('line_data'), line_data, "0|tags_array")
        if tag == 'irc_privmsg':
            message = w.hdata_string(w.hdata_get('line_data'), line_data, "message")
            last_lines.append(message)
            found += 1
        line = w.hdata_pointer(w.hdata_get('line'), line, "prev_line")
        processed += 1

    last_lines.append(get_input_line(buffer, 1))
Exemplo n.º 28
0
def hdata_server(server_to_search):
    hdata = weechat.hdata_get('irc_server')
    hdata_servers = weechat.hdata_get_list(hdata,'irc_servers')
    server = weechat.hdata_search(hdata, hdata_servers,'${irc_server.name} =* %s' % server_to_search, 1)
    if server:
        is_connected = weechat.hdata_integer(hdata, server, 'is_connected')
        nick_modes = weechat.hdata_string(hdata, server, 'nick_modes')
        buffer_ptr = weechat.hdata_pointer(hdata, server, 'buffer')
    return
Exemplo n.º 29
0
def test12(data, buffer, arg):
    own_lines = weechat.hdata_pointer(weechat.hdata_get("buffer"), buffer,
                                      'own_lines')
    #line = weechat.hdata_pointer(weechat.hdata_get("lines"), own_lines, "last_line")
    #line_data = weechat.hdata_pointer(weechat.hdata_get("line"), line, "data")
    #hdata = weechat.hdata_get("line_data")
    #data = weechat.hdata_pointer(hdata.line, pointer, 'data')
    weechat.prnt("", str(own_lines))
    return weechat.WEECHAT_RC_OK
Exemplo n.º 30
0
def hdata_server(server_to_search):
    hdata = weechat.hdata_get('irc_server')
    hdata_servers = weechat.hdata_get_list(hdata, 'irc_servers')
    server = weechat.hdata_search(
        hdata, hdata_servers, '${irc_server.name} =* %s' % server_to_search, 1)
    if server:
        is_connected = weechat.hdata_integer(hdata, server, 'is_connected')
        nick_modes = weechat.hdata_string(hdata, server, 'nick_modes')
        buffer_ptr = weechat.hdata_pointer(hdata, server, 'buffer')
    return
Exemplo n.º 31
0
def filter_exists(name):
	"""
	Check whether a filter named "name" exists.
	"""

	hdata = weechat.hdata_get("filter")
	filters = weechat.hdata_get_list(hdata, "gui_filters")
	filter = weechat.hdata_search(hdata, filters, "${filter.name} == %s" % name, 1)

	return bool(filter)
Exemplo n.º 32
0
def filter_exists(name):
	"""
	Check whether a filter named "name" exists.
	"""

	hdata = weechat.hdata_get("filter")
	filters = weechat.hdata_get_list(hdata, "gui_filters")
	filter = weechat.hdata_search(hdata, filters, "${filter.name} == %s" % name, 1)

	return bool(filter)
Exemplo n.º 33
0
def get_buffers():
	''' Get a list of all the buffers in weechat. '''
	hdata  = weechat.hdata_get('buffer')
	buffer = weechat.hdata_get_list(hdata, "gui_buffers");

	result = []
	while buffer:
		number = weechat.hdata_integer(hdata, buffer, 'number')
		result.append((number, buffer))
		buffer = weechat.hdata_pointer(hdata, buffer, 'next_buffer')
	return hdata, result
Exemplo n.º 34
0
def count_lines(ptr_window, ptr_buffer):
    global filter_status

    hdata_buf = weechat.hdata_get('buffer')
    hdata_lines = weechat.hdata_get('lines')
    lines = weechat.hdata_pointer(hdata_buf, ptr_buffer,
                                  'lines')  # own_lines, mixed_lines
    lines_count = weechat.hdata_integer(hdata_lines, lines, 'lines_count')

    hdata_window = weechat.hdata_get('window')
    hdata_winscroll = weechat.hdata_get('window_scroll')
    window_scroll = weechat.hdata_pointer(hdata_window, ptr_window, 'scroll')
    lines_after = weechat.hdata_integer(hdata_winscroll, window_scroll,
                                        'lines_after')
    window_height = weechat.window_get_integer(weechat.current_window(),
                                               'win_chat_height')

    filtered = 0
    filtered_before = 0
    filtered_after = 0
    # if filter is disabled, don't count.
    if (OPTIONS['count_filtered_lines'].lower()
            == 'off') and filter_status == 1:
        filtered, filtered_before, filtered_after = count_filtered_lines(
            ptr_buffer, lines_count, lines_after)
        lines_count = lines_count - filtered


#        lines_after = lines_after - filtered_after

    if lines_count > window_height:
        differential = lines_count - window_height
        percent = max(
            int(round(100. * (differential - lines_after) / differential)), 0)
    else:
        percent = 100

    # get current position
    current_line = lines_count - lines_after

    return lines_after, lines_count, percent, current_line, filtered, filtered_before, filtered_after
Exemplo n.º 35
0
def count_lines(winpointer, bufpointer):

    hdata_buf = weechat.hdata_get("buffer")
    hdata_lines = weechat.hdata_get("lines")
    lines = weechat.hdata_pointer(hdata_buf, bufpointer, "lines")  # own_lines, mixed_lines
    lines_count = weechat.hdata_integer(hdata_lines, lines, "lines_count")

    hdata_window = weechat.hdata_get("window")
    hdata_winscroll = weechat.hdata_get("window_scroll")
    window_scroll = weechat.hdata_pointer(hdata_window, winpointer, "scroll")
    lines_after = weechat.hdata_integer(hdata_winscroll, window_scroll, "lines_after")
    window_height = weechat.window_get_integer(weechat.current_window(), "win_chat_height")

    if lines_count > window_height:
        differential = lines_count - window_height
        percent = max(int(round(100.0 * (differential - lines_after) / differential)), 0)
    else:
        percent = 100
    # weechat.prnt('', " : lines_count "+str(lines_count)+" window_height "+str(window_height)+" lines after "+str(lines_after))
    current_line = lines_count - lines_after
    return lines_after, lines_count, percent, current_line
Exemplo n.º 36
0
def read_history(filename, ptr_buffer):
    global_history = 0

    # global history does not use buffer pointers!
    if filename == filename_global_history:
        global_history = 1

    filename = get_filename_with_path(filename)

    # filename exists?
    if not os.path.isfile(filename):
        return

    # check for global history
    if global_history == 0:
        # localvar_save_history exists for buffer?
        if not ptr_buffer or not weechat.buffer_get_string(
                ptr_buffer, 'localvar_save_history'):
            return

    hdata = weechat.hdata_get('history')
    if not hdata:
        return

    try:
        f = open(filename, 'r')
        #        for line in f.xreadlines():    # old python 2.x
        for line in f:  # should also work with python 2.x
            #            line = line.decode('utf-8')
            line = str(line.strip())
            if ptr_buffer:
                # add to buffer history
                weechat.hdata_update(hdata, '', {
                    'buffer': ptr_buffer,
                    'text': line
                })
            else:
                # add to global history
                weechat.hdata_update(hdata, '', {'text': line})
        f.close()
    except:
        if global_history == 1:
            weechat.prnt(
                '', '%s%s: Error loading global history from "%s"' %
                (weechat.prefix('error'), SCRIPT_NAME, filename))
        else:
            name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
            weechat.prnt(
                '',
                '%s%s: Error loading buffer history for buffer "%s" from "%s"'
                % (weechat.prefix('error'), SCRIPT_NAME, name, filename))
        raise
Exemplo n.º 37
0
def hdata_update_history_cmd(data, buffer, args):
    hdata = weechat.hdata_get('history')

    # add to global history
    weechat.hdata_update(hdata, '', { 'text': 'test global 1' })
    weechat.hdata_update(hdata, '', { 'text': 'test global 2' })

    # add to history of core buffer
    core_buffer = weechat.buffer_search_main()
    weechat.hdata_update(hdata, '', { 'buffer': core_buffer, 'text': 'test core buffer 1' })
    weechat.hdata_update(hdata, '', { 'buffer': core_buffer, 'text': 'test core buffer 2' })

    return weechat.WEECHAT_RC_OK
Exemplo n.º 38
0
def cb_exec_cmd(data, remaining_calls):
    """Translate and execute our custom commands to WeeChat command."""
    # Process the entered command.
    data = list(data)
    del data[0]
    data = "".join(data)
    # s/foo/bar command.
    if data.startswith("s/"):
        cmd = data
        parsed_cmd = next(csv.reader(StringIO(cmd), delimiter="/",
                                     escapechar="\\"))
        pattern = re.escape(parsed_cmd[1])
        repl = parsed_cmd[2]
        repl = re.sub(r"([^\\])&", r"\1" + pattern, repl)
        flag = None
        if len(parsed_cmd) == 4:
            flag = parsed_cmd[3]
        count = 1
        if flag == "g":
            count = 0
        buf = weechat.current_buffer()
        input_line = weechat.buffer_get_string(buf, "input")
        input_line = re.sub(pattern, repl, input_line, count)
        weechat.buffer_set(buf, "input", input_line)
    # Shell command.
    elif data.startswith("!"):
        weechat.command("", "/exec -buffer shell %s" % data[1:])
    # Commands like `:22`. This should start cursor mode (``/cursor``) and take
    # us to the relevant line.
    # TODO: look into possible replacement key bindings for: ← ↑ → ↓ Q m q.
    elif data.isdigit():
        line_number = int(data)
        hdata_window = weechat.hdata_get("window")
        window = weechat.current_window()
        x = weechat.hdata_integer(hdata_window, window, "win_chat_x")
        y = (weechat.hdata_integer(hdata_window, window, "win_chat_y") +
             (line_number - 1))
        weechat.command("", "/cursor go {},{}".format(x, y))
    # Check againt defined commands.
    else:
        data = data.split(" ", 1)
        cmd = data[0]
        args = ""
        if len(data) == 2:
            args = data[1]
        if cmd in VI_COMMANDS:
            weechat.command("", "%s %s" % (VI_COMMANDS[cmd], args))
        # No vi commands defined, run the command as a WeeChat command.
        else:
            weechat.command("", "/{} {}".format(cmd, args))
    return weechat.WEECHAT_RC_OK
Exemplo n.º 39
0
def cb_exec_cmd(data, remaining_calls):
    """Translate and execute our custom commands to WeeChat command."""
    # Process the entered command.
    data = list(data)
    del data[0]
    data = "".join(data)
    # s/foo/bar command.
    if data.startswith("s/"):
        cmd = data
        parsed_cmd = next(
            csv.reader(StringIO(cmd), delimiter="/", escapechar="\\"))
        pattern = re.escape(parsed_cmd[1])
        repl = parsed_cmd[2]
        repl = re.sub(r"([^\\])&", r"\1" + pattern, repl)
        flag = None
        if len(parsed_cmd) == 4:
            flag = parsed_cmd[3]
        count = 1
        if flag == "g":
            count = 0
        buf = weechat.current_buffer()
        input_line = weechat.buffer_get_string(buf, "input")
        input_line = re.sub(pattern, repl, input_line, count)
        weechat.buffer_set(buf, "input", input_line)
    # Shell command.
    elif data.startswith("!"):
        weechat.command("", "/exec -buffer shell %s" % data[1:])
    # Commands like `:22`. This should start cursor mode (``/cursor``) and take
    # us to the relevant line.
    # TODO: look into possible replacement key bindings for: ← ↑ → ↓ Q m q.
    elif data.isdigit():
        line_number = int(data)
        hdata_window = weechat.hdata_get("window")
        window = weechat.current_window()
        x = weechat.hdata_integer(hdata_window, window, "win_chat_x")
        y = (weechat.hdata_integer(hdata_window, window, "win_chat_y") +
             (line_number - 1))
        weechat.command("", "/cursor go {},{}".format(x, y))
    # Check againt defined commands.
    else:
        data = data.split(" ", 1)
        cmd = data[0]
        args = ""
        if len(data) == 2:
            args = data[1]
        if cmd in VI_COMMANDS:
            weechat.command("", "%s %s" % (VI_COMMANDS[cmd], args))
        # No vi commands defined, run the command as a WeeChat command.
        else:
            weechat.command("", "/{} {}".format(cmd, args))
    return weechat.WEECHAT_RC_OK
Exemplo n.º 40
0
def auth_command(data, buffer, args):
    list_args = args.split(" ")
    server, channel = get_channel_from_buffer_args(buffer, args)
    #strip spaces
    while '' in list_args:
        list_args.remove('')
    while ' ' in list_args:
        list_args.remove(' ')

    h_servers = weechat.hdata_get("irc_server")
    l_servers = weechat.hdata_get_list(h_servers, "irc_servers")

    if len(list_args) ==  0:
        weechat.command(buffer, "/help auth")
    elif list_args[0] not in ["add", "del", "list", "cmd"]:
        weechat.prnt(buffer, "[%s] bad option while using /auth command, try '/help auth' for more info" % (NAME))
    elif list_args[0] == "cmd":
        if len(list_args[1:]) == 1 and weechat.hdata_search(h_servers, l_servers, "${irc_server.name} == "+list_args[1], 1):
            auth_cmd("", list_args[1])
        elif len(list_args[1:]) == 1:
            auth_cmd(list_args[1], server)
        elif len(list_args[1:]) >= 2:
            if weechat.hdata_search(h_servers, l_servers, "${irc_server.name} == "+list_args[-1], 1):
                auth_cmd(" ".join(list_args[1:-1]), list_args[-1])
            else:
                auth_cmd(" ".join(list_args[1:]), server)
        else:
            auth_cmd(" ".join(list_args[1:]), server)
    elif list_args[0] == "list":
        auth_list()
    elif list_args[0] == "add":
        if len(list_args) < 3 or (len(list_args) == 3 and server == ''):
            weechat.prnt(buffer, "[%s] bad option while using /auth command, try '/help auth' for more info" % (NAME))
        else:
            if len(list_args) == 3:
                auth_add(list_args[1], list_args[2], server)
            else:
                auth_add(list_args[1], list_args[2], list_args[3])
    elif list_args[0] == "del":
       if len(list_args) < 2:
           weechat.prnt(buffer, "[%s] bad option while using /auth command, try '/help auth' for more info" % (NAME))
       else:
            if len(list_args) == 2:
                auth_del(list_args[1], server)
            else:
                auth_del(list_args[1], list_args[2])
    else:
        pass
    return weechat.WEECHAT_RC_OK
Exemplo n.º 41
0
def read_history(filename,ptr_buffer):
    global filename_global_history
    global_history = 0

    # global history does not use buffer pointers!
    if filename == filename_global_history:
        global_history = 1

    filename = get_filename_with_path(filename)

    # filename exists?
    if not os.path.isfile(filename):
        return

    # check for global history
    if global_history == 0:
#        test = weechat.buffer_get_string(ptr_buffer, 'localvar_save_history')
#        test2 = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
#        weechat.prnt("","ptr: %s test: %s name: %s" % (ptr_buffer,test,test2))
        # localvar_save_history exists for buffer?
        if not ptr_buffer or not weechat.buffer_get_string(ptr_buffer, 'localvar_save_history'):
#            weechat.prnt("","test2")
            return

#    weechat.prnt("","test4")
    hdata = weechat.hdata_get('history')
    if not hdata:
        return

    try:
        f = open(filename, 'r')
#        for line in f.xreadlines():    # old python 2.x
        for line in f:                  # should also work with python 2.x
#            line = line.decode('utf-8')
            line = str(line.strip())
            if ptr_buffer:
                # add to buffer history
                weechat.hdata_update(hdata, '', { 'buffer': ptr_buffer, 'text': line })
            else:
                # add to global history
                weechat.hdata_update(hdata, '', { 'text': line })
        f.close()
    except:
        if global_history == 1:
            weechat.prnt('','%s%s: Error loading global history from "%s"' % (weechat.prefix('error'), SCRIPT_NAME, filename))
        else:
            name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
            weechat.prnt('','%s%s: Error loading buffer history for buffer "%s" from "%s"' % (weechat.prefix('error'), SCRIPT_NAME, name, filename))
        raise
Exemplo n.º 42
0
    def refresh_buffers(self):
        self.buffers.clear()
        hdata = weechat.hdata_get("buffer")
        buffer = weechat.hdata_get_list(hdata, "gui_buffers")

        if not hdata or not buffer:
            return weechat.WEECHAT_RC_OK
        while True:
            buffer = weechat.hdata_move(hdata, buffer, 1)
            if not buffer:
                break
            else:
                buf = self.buffers[full_name(buffer)] = Buffer(buffer, self.opts)
                logging.debug("Hideable: {}".format(buf.is_hideable()))
                self.try_hide(self.buffers[full_name(buffer)])
Exemplo n.º 43
0
def read_history(filename,ptr_buffer):
    global_history = 0

    # get buffer_autoset_option as a fallback. could happen that the localvar is not already set to buffer
    plugin = weechat.buffer_get_string(ptr_buffer, 'localvar_plugin')
    name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
    buffer_autoset_option = ('buffer_autoset.buffer.%s.%s.localvar_set_save_history' % (plugin,name))
    buffer_autoset_option = weechat.config_get(buffer_autoset_option)

    # global history does not use buffer pointers!
    if filename == filename_global_history:
        global_history = 1

    filename = get_filename_with_path(filename)

    # filename exists?
    if not os.path.isfile(filename):
        return

    # check for buffer history (0, global = 1)
    if global_history == 0 and OPTIONS['save_buffer'].lower() == 'off':
        # localvar_save_history exists for buffer?
        if not ptr_buffer and not buffer_autoset_option and not weechat.buffer_get_string(ptr_buffer, 'localvar_save_history'):
            return
    hdata = weechat.hdata_get('history')
    if not hdata:
        return

    try:
        f = open(filename, 'r')
#        for line in f.xreadlines():    # old python 2.x
        for line in f:                  # should also work with python 2.x
#            line = line.decode('utf-8')
            line = str(line.strip())
            if ptr_buffer:
                # add to buffer history
                weechat.hdata_update(hdata, '', { 'buffer': ptr_buffer, 'text': line })
            else:
                # add to global history
                weechat.hdata_update(hdata, '', { 'text': line })
        f.close()
    except:
        if global_history == 1:
            weechat.prnt('','%s%s: Error loading global history from "%s"' % (weechat.prefix('error'), SCRIPT_NAME, filename))
        else:
            name = weechat.buffer_get_string(ptr_buffer, 'localvar_name')
            weechat.prnt('','%s%s: Error loading buffer history for buffer "%s" from "%s"' % (weechat.prefix('error'), SCRIPT_NAME, name, filename))
        raise
Exemplo n.º 44
0
def irc_buffer_open(server, name, noswitch):
    hdata_irc_server = weechat.hdata_get("irc_server")
    irc_servers = weechat.hdata_get_list(hdata_irc_server, "irc_servers")
    irc_server = weechat.hdata_search(hdata_irc_server, irc_servers,
                                      "${irc_server.name} == " + server, 1)
    chantypes = weechat.hdata_string(hdata_irc_server, irc_server, "chantypes")
    is_channel = name[0] in chantypes

    noswitch_flag = "-noswitch " if noswitch else ""
    if is_channel:
        command_plugin(
            "irc", "/join {}-server {} {}".format(noswitch_flag, server, name))
    else:
        command_plugin(
            "irc", "/query {}-server {} {}".format(noswitch_flag, server,
                                                   name))
Exemplo n.º 45
0
def exclude_server(server):
    global OPTIONS
    for server_exclude in OPTIONS['server_exclude'].split(','):
        if server_exclude == '*':                                               # show buffer for all server
            weechat.command('','/buffer unhide -all')                           # simply unload script, no!? :-)
            break

        # search exclude server in list of servers
        hdata = weechat.hdata_get('irc_server')
        servers = weechat.hdata_get_list(hdata, 'irc_servers')
        server = weechat.hdata_search(hdata, servers, '${irc_server.name} =* %s' % server_exclude, 1)
        if server:
#            is_connected    = weechat.hdata_integer(hdata, server, "is_connected")
#            nick_modes      = weechat.hdata_string(hdata, server, "nick_modes")
            buffer_ptr = weechat.hdata_pointer(hdata, server, 'buffer')
            weechat.command(buffer_ptr,'/allchan -current /buffer unhide')
    return
Exemplo n.º 46
0
def hdata_update_history_cmd(data, buffer, args):
    hdata = weechat.hdata_get('history')

    # add to global history
    weechat.hdata_update(hdata, '', {'text': 'test global 1'})
    weechat.hdata_update(hdata, '', {'text': 'test global 2'})

    # add to history of core buffer
    core_buffer = weechat.buffer_search_main()
    weechat.hdata_update(hdata, '', {
        'buffer': core_buffer,
        'text': 'test core buffer 1'
    })
    weechat.hdata_update(hdata, '', {
        'buffer': core_buffer,
        'text': 'test core buffer 2'
    })

    return weechat.WEECHAT_RC_OK
Exemplo n.º 47
0
def get_merged_buffers(ptr):
    """
    Get a list of buffers which are merged with "ptr".
    """

    weechat_version = int(weechat.info_get("version_number", "") or 0)

    hdata = weechat.hdata_get("buffer")
    buffers = weechat.hdata_get_list(hdata, "gui_buffers")
    if weechat_version >= 0x03040000:
        buffer = weechat.hdata_search(
            hdata,
            buffers,
            "${buffer.number} == ${value}",
            {},
            {"value": str(weechat.hdata_integer(hdata, ptr, "number"))},
            {},
            1,
        )
    else:
        buffer = weechat.hdata_search(
            hdata,
            buffers,
            "${buffer.number} == %i" %
            weechat.hdata_integer(hdata, ptr, "number"),
            1,
        )
    nbuffer = weechat.hdata_move(hdata, buffer, 1)

    ret = []
    while buffer:
        ret.append(weechat.hdata_string(hdata, buffer, "full_name"))

        if weechat.hdata_integer(hdata, buffer,
                                 "number") == weechat.hdata_integer(
                                     hdata, nbuffer, "number"):
            buffer = nbuffer
            nbuffer = weechat.hdata_move(hdata, nbuffer, 1)
        else:
            buffer = None

    return ret
Exemplo n.º 48
0
def get_merged_buffers(ptr):
	"""
	Get a list of buffers which are merged with "ptr".
	"""

	hdata = weechat.hdata_get("buffer")
	buffers = weechat.hdata_get_list(hdata, "gui_buffers")
	buffer = weechat.hdata_search(hdata, buffers, "${buffer.number} == %i" % weechat.hdata_integer(hdata, ptr, "number"), 1)
	nbuffer = weechat.hdata_move(hdata, buffer, 1)

	ret = []
	while buffer:
		ret.append(weechat.hdata_string(hdata, buffer, "full_name"))

		if (weechat.hdata_integer(hdata, buffer, "number") == weechat.hdata_integer(hdata, nbuffer, "number")):
			buffer = nbuffer
			nbuffer = weechat.hdata_move(hdata, nbuffer, 1)
		else:
			buffer = None

	return ret
Exemplo n.º 49
0
def server_by_name(server_name):
    hdata = weechat.hdata_get("irc_server")
    server_list = weechat.hdata_get_list(hdata, "irc_servers")
    weechat_version = int(weechat.info_get("version_number", "") or 0)
    if weechat_version >= 0x03040000:
        return weechat.hdata_search(
            hdata,
            server_list,
            "${irc_server.name} == ${name}",
            {},
            {"name": server_name},
            {},
            1,
        )
    else:
        return weechat.hdata_search(
            hdata,
            server_list,
            "${irc_server.name} == " + server_name,
            1,
        )
Exemplo n.º 50
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)
Exemplo n.º 51
0
    print "\ntesting speed…\n"
    from timeit import Timer
    urls = [test[0] for test in TESTS if isinstance(test, tuple)]
    string = " lorem ipsum dolor sit amet ".join(urls)
    time = Timer("list(find_urls(string))", "import re; from __main__ import find_urls, string").timeit(ITERATIONS)
    print "%s lookups on a %s character long string with %s urls took %s seconds (%s seconds per iteration)" % \
          (ITERATIONS, len(string), len(urls), time, time/ITERATIONS)
else:
    if not weechat.register(SCRIPT_NAME, "oakkitten", SCRIPT_VERSION, "MIT", "Display hints for urls and open them with keyboard shortcuts", "exit_function", ""):
        raise Exception("Could not register script")

    WEECHAT_VERSION = int(weechat.info_get('version_number', '') or 0)
    if WEECHAT_VERSION <= 0x00040000:
        raise Exception("Need Weechat 0.4 or higher")

    H_BUFFER = weechat.hdata_get("buffer")
    H_LINES = weechat.hdata_get("lines")
    H_LINE = weechat.hdata_get("line")
    H_LINE_DATA = weechat.hdata_get("line_data")
    HL_GUI_BUFFERS = weechat.hdata_get_list(H_BUFFER, "gui_buffers")

    load_config()

    weechat.hook_print("", "", "", 0, "on_print", "")
    weechat.hook_signal("buffer_switch", "on_buffer_switch", "")
    weechat.hook_config("plugins.var.python." + SCRIPT_NAME + ".*", "load_config", "")

    if not weechat.hook_command("url_hint", __doc__.strip(), "", "", "", "url_hint", ""):
        print_error("could not hook command /url_hint")

    if not weechat.hook_command("url_hint_replace", """Replaces {url1} with url hinted with a 1, etc. Example usage:
Exemplo n.º 52
0
def get_hdata():
    """
    Get list of hdata hooked by plugins in a dict with 3 indexes:
    plugin, name, xxx.
    """
    hdata = defaultdict(lambda: defaultdict(defaultdict))
    infolist = weechat.infolist_get('hook', '', 'hdata')
    while weechat.infolist_next(infolist):
        hdata_name = weechat.infolist_string(infolist, 'hdata_name')
        plugin = weechat.infolist_string(infolist, 'plugin_name') or 'weechat'
        hdata[plugin][hdata_name]['description'] = \
            weechat.infolist_string(infolist, 'description')
        variables = ''
        variables_update = ''
        lists = ''
        ptr_hdata = weechat.hdata_get(hdata_name)
        if ptr_hdata:
            hdata2 = []
            string = weechat.hdata_get_string(ptr_hdata, 'var_keys_values')
            if string:
                for item in string.split(','):
                    key = item.split(':')[0]
                    var_offset = weechat.hdata_get_var_offset(ptr_hdata, key)
                    var_array_size = \
                        weechat.hdata_get_var_array_size_string(ptr_hdata, '',
                                                                key)
                    if var_array_size:
                        var_array_size = \
                            ', array_size: "{0}"'.format(var_array_size)
                    var_hdata = weechat.hdata_get_var_hdata(ptr_hdata, key)
                    if var_hdata:
                        var_hdata = ', hdata: "{0}"'.format(var_hdata)
                    type_string = weechat.hdata_get_var_type_string(ptr_hdata,
                                                                    key)
                    hdata2.append({
                        'offset': var_offset,
                        'text': '\'{0}\' ({1})'.format(key, type_string),
                        'textlong': '\'{0}\' ({1}{2}{3})'.format(
                            key, type_string, var_array_size, var_hdata),
                        'update': weechat.hdata_update(
                            ptr_hdata, '', {'__update_allowed': key}),
                    })
                hdata2 = sorted(hdata2, key=itemgetter('offset'))
                for item in hdata2:
                    variables += '*** {0}\n'.format(item['textlong'])
                    if item['update']:
                        variables_update += '*** {0}\n'.format(item['text'])
                if weechat.hdata_update(ptr_hdata, '',
                                        {'__create_allowed': ''}):
                    variables_update += '*** \'__create\'\n'
                if weechat.hdata_update(ptr_hdata, '',
                                        {'__delete_allowed': ''}):
                    variables_update += '*** \'__delete\'\n'
            hdata[plugin][hdata_name]['vars'] = variables
            hdata[plugin][hdata_name]['vars_update'] = variables_update

            string = weechat.hdata_get_string(ptr_hdata, 'list_keys')
            if string:
                for item in sorted(string.split(',')):
                    lists += '*** \'{0}\'\n'.format(item)
            hdata[plugin][hdata_name]['lists'] = lists
    weechat.infolist_free(infolist)
    return hdata
Exemplo n.º 53
0
def get_hdata():
    """
    Get list of WeeChat/plugins hdata as dictionary with 3 indexes: plugin,
    name, xxx.
    """
    hdata = defaultdict(lambda: defaultdict(defaultdict))
    infolist = weechat.infolist_get('hook', '', 'hdata')
    while weechat.infolist_next(infolist):
        hdata_name = weechat.infolist_string(infolist, 'hdata_name')
        plugin = weechat.infolist_string(infolist, 'plugin_name') or 'weechat'
        hdata[plugin][hdata_name]['description'] = \
            weechat.infolist_string(infolist, 'description')
        variables = ''
        variables_update = ''
        lists = ''
        ptr_hdata = weechat.hdata_get(hdata_name)
        if ptr_hdata:
            hdata2 = []
            string = weechat.hdata_get_string(ptr_hdata, 'var_keys_values')
            if string:
                for item in string.split(','):
                    key = item.split(':')[0]
                    var_offset = weechat.hdata_get_var_offset(ptr_hdata, key)
                    var_array_size = \
                        weechat.hdata_get_var_array_size_string(ptr_hdata, '',
                                                                key)
                    if var_array_size:
                        var_array_size = \
                            ', array_size: "{0}"'.format(var_array_size)
                    var_hdata = weechat.hdata_get_var_hdata(ptr_hdata, key)
                    if var_hdata:
                        var_hdata = ', hdata: "{0}"'.format(var_hdata)
                    type_string = weechat.hdata_get_var_type_string(ptr_hdata,
                                                                    key)
                    hdata2.append({
                        'offset': var_offset,
                        'text': '_{0}_ ({1})'.format(key, type_string),
                        'textlong': '_{0}_   ({1}{2}{3})'.format(
                            key, type_string, var_array_size, var_hdata),
                        'update': weechat.hdata_update(
                            ptr_hdata, '', {'__update_allowed': key}),
                    })
                hdata2 = sorted(hdata2, key=itemgetter('offset'))
                for item in hdata2:
                    variables += '{0} +\n'.format(item['textlong'])
                    if item['update']:
                        variables_update += '    {0} +\n'.format(item['text'])
                if weechat.hdata_update(ptr_hdata, '',
                                        {'__create_allowed': ''}):
                    variables_update += '    _{hdata_update_create}_ +\n'
                if weechat.hdata_update(ptr_hdata, '',
                                        {'__delete_allowed': ''}):
                    variables_update += '    _{hdata_update_delete}_ +\n'
            hdata[plugin][hdata_name]['vars'] = variables
            hdata[plugin][hdata_name]['vars_update'] = variables_update

            string = weechat.hdata_get_string(ptr_hdata, 'list_keys')
            if string:
                list_lists = string.split(',')
                lists_std = [l for l in list_lists
                             if not l.startswith('last_')]
                lists_last = [l for l in list_lists
                              if l.startswith('last_')]
                for item in sorted(lists_std) + sorted(lists_last):
                    lists += '_{0}_ +\n'.format(item)
            hdata[plugin][hdata_name]['lists'] = lists
    weechat.infolist_free(infolist)
    return hdata
Exemplo n.º 54
0
def is_away():
    '''Check if user is already away'''
    b = False
    hdhata = w.hdata_get("irc_server")
    #
    return b