Пример #1
0
 def display(self) -> None:
     """Display maze."""
     if not self.buffer:
         return
     weechat.buffer_clear(self.buffer)
     for line in range(self.height + 1):
         self.display_line(line)
Пример #2
0
    def print_tasks(self):

        w.buffer_clear(self.buffer)

        list_id = self.lists[self.active_list_name]
        rspTasks = self.rtm.tasks.getList(list_id=list_id, filter='status:incomplete')
        for task in reversed(rspTasks.tasks.list.taskseries):
            if not self.active_task_id:
                self.active_task_id = task.id

            priority = task.task.priority
            
            fgcolor = 'default'
            bgcolor = 'default'
            if priority == '3':
                fgcolor = 'green'
            elif priority == '2':
                fgcolor = 'cyan'
            elif priority == '1':
                fgcolor = 'yellow'
            elif priority == 'N':
                fgcolor = 'default'
            if int(task.id) == int(self.active_task_id):
                bgcolor = 'red'
            try:
                ttime = datetime.datetime.fromtimestamp(time.mktime(time.strptime(task.created, "%Y-%m-%dT%H:%M:%SZ")))
            except Exception, e:
                ttime = ''
                print task.created, e
           
            task_name = task.name.encode('UTF-8')
            task_name = '%s%s%s' %(w.color('%s,%s' %(fgcolor,bgcolor)), task_name, w.color('reset'))
            taskstr = '%s\t%s %s' %(ttime, '', task_name)
            w.prnt(self.buffer, taskstr)
Пример #3
0
def print_messages(mailbox='INBOX'):
    ''' Print all unread messages in a folder to buffer '''

    global imap_buffer, active_message_line, active_message_uid

    w.buffer_clear(imap_buffer)
    imap = Imap()

    typ, data = imap.messages(mailbox)
    if not typ == 'OK':
        print 'bad type returned'
        imap.logout()
        return

    y = 0
    for num in data[0].split():
        typ, data = imap.conn.fetch(num, '(FLAGS INTERNALDATE BODY[HEADER.FIELDS (SUBJECT FROM)])')
        data = data[0] # only one message is returned
        meta, headers = data[0], data[1]
        #flags = re.search(r'\(FLAGS \((?P<flags>.+)\) ', meta).groupdict()['flags']

        internaldate = datetime.fromtimestamp(time.mktime(i.Internaldate2tuple(meta)))
        internaldate = internaldate.strftime(w.config_get_plugin('time_format'))
        internaldate = internaldate.replace(':', '%s:%s' %
                (w.color(w.config_string(
                w.config_get('weechat.color.chat_time_delimiters'))),
                w.color('reset')))
        internaldate = internaldate.strip()
                
        sender = re.search(r'From: ?(?P<from>.+)\s', headers, re.I)
        if sender:
            sender = sender.groupdict()['from']

        subject = re.search(r'Subject: ?(?P<subject>.+)\s', headers, re.I)
        if subject:
            subject = subject.groupdict()['subject']


        sender = imap.decode_helper(sender)
        subject = imap.decode_helper(subject)

        bgcolor = 'default'
        if y == active_message_line:
            active_message_uid = num
            bgcolor = 'red'

        if ' ' in sender:
            sender = irc_nick_find_color(sender.split()[0].strip('"'))
        else:
            sender = irc_nick_find_color(sender)

        w.prnt(imap_buffer, '%s %s\t%s %s' % \
                (internaldate, sender, w.color('default,%s' %bgcolor), subject))
        y += 1
        if y == 25:
            break

    imap.logout()
Пример #4
0
def lb_refresh():
    global lb_channels, lb_buffer
    weechat.buffer_clear(lb_buffer)

    y = 0
    for list_data in lb_channels:
        lb_refresh_line(y)
        y += 1
    return
Пример #5
0
def floodit_display(clear=False):
    """Display status and board."""
    global floodit
    if not floodit['buffer']:
        return
    if clear:
        weechat.buffer_clear(floodit['buffer'])
    spaces = ' ' * ((floodit['zoom'] + 1) * 2)
    str_line = ''
    for index, color in enumerate(floodit['colors']):
        str_select = [' ', ' ']
        if floodit['color'] == index:
            str_select = ['»', '«']
        str_line += '%s%s%s%s%s%s%s' % (weechat.color('white,default'),
                                        str_select[0],
                                        weechat.color(',%s' % color),
                                        spaces,
                                        weechat.color('white,default'),
                                        str_select[1],
                                        spaces[0:-2])
    str_status = ''
    str_end = ''
    if floodit['mode'] == 'single':
        board = copy.deepcopy(floodit['board'])
        floodit_flood_xy(board, 0, 0, board[0][0])
        percent = (floodit_count_color(board, -1) * 100) // (floodit['size'] * floodit['size'])
        str_status = '%2d/%d%s (%d%%)' % (floodit['count'], floodit['count_max'],
                                          weechat.color('chat'), percent)
        message_end = { 'win': '** CONGRATS! **', 'lose': '...GAME OVER!...' }
    elif floodit['mode'] == 'versus':
        colors = ['yellow', 'lightred']
        board = copy.deepcopy(floodit['board'])
        floodit_flood_xy(board, 0, 0, board[0][0])
        count_player = floodit_count_color(board, -1)
        board = copy.deepcopy(floodit['board'])
        floodit_flood_xy(board, floodit['size'] - 1, floodit['size'] - 1, board[floodit['size'] - 1][floodit['size'] - 1])
        count_computer = floodit_count_color(board, -1)
        if count_player == count_computer:
            colors[1] = 'yellow'
        elif count_computer > count_player:
            colors.reverse()
        str_status = '%sYou: %d%s / %sWee: %d' % (weechat.color(colors[0]), count_player,
                                                  weechat.color('default'),
                                                  weechat.color(colors[1]), count_computer)
        message_end = { 'win': '** YOU WIN! **', 'lose': '...You lose...', 'equality': 'Equality!' }
    str_end = '%s%s' % (weechat.color('white'), message_end.get(floodit['end'], ''))
    weechat.prnt_y(floodit['buffer'], 0, '%s %s %s' % (str_line, str_status, str_end))
    for i in range (0, floodit['zoom']):
        weechat.prnt_y(floodit['buffer'], 1 + i, str_line)
    weechat.prnt_y(floodit['buffer'], floodit['zoom'] + 1, '%s%s' % (weechat.color('blue'), '─' * (floodit['size'] * ((floodit['zoom'] + 1) * 2))))
    for y, line in enumerate(floodit['board']):
        str_line = ''
        for color in line:
            str_line += '%s%s' % (weechat.color(',%s' % floodit['colors'][color]), spaces)
        str_line += '%s' % weechat.color('chat')
        for i in range (0, floodit['zoom'] + 1):
            weechat.prnt_y(floodit['buffer'], floodit['zoom'] + 2 + (y * (floodit['zoom'] + 1)) + i, str_line)
Пример #6
0
def lb_refresh():
  global lb_channels, lb_buffer
  weechat.buffer_clear(lb_buffer)

  y = 0
  for list_data in lb_channels:
    lb_refresh_line(y)
    y += 1
  return
Пример #7
0
def samegame_change_size(add):
    """Change size of board."""
    global samegame
    keys = sorted(samegame['sizes'])
    index = keys.index(samegame['size']) + add
    if index >= 0 and index < len(keys):
        samegame['size'] = keys[index]
        weechat.buffer_clear(samegame['buffer'])
        samegame_adjust_zoom()
        samegame_new_game()
Пример #8
0
def samegame_change_size(add):
    """Change size of board."""
    global samegame
    keys = sorted(samegame["sizes"])
    index = keys.index(samegame["size"]) + add
    if index >= 0 and index < len(keys):
        samegame["size"] = keys[index]
        weechat.buffer_clear(samegame["buffer"])
        samegame_adjust_zoom()
        samegame_new_game()
Пример #9
0
def print_message():
    ''' Print a single email to the buffer '''

    global imap_buffer, active_message_line, active_message_uid

    imap = Imap()
    mail = imap.fetch_num(active_folder_name, active_message_uid)
    imap.logout()

    w.buffer_clear(imap_buffer)
    w.prnt(imap_buffer, mail.get_payload())
Пример #10
0
def minesweeper_change_size(add):
    """Change size of board."""
    global minesweeper
    keys = sorted(minesweeper['mines'])
    index = keys.index(minesweeper['size']) + add
    if index >= 0 and index < len(keys):
        minesweeper['size'] = keys[index]
        minesweeper['count_max'] = minesweeper['mines'][minesweeper['size']]
        weechat.buffer_clear(minesweeper['buffer'])
        minesweeper_adjust_zoom()
        minesweeper_new_game()
Пример #11
0
def minesweeper_change_size(add):
    """Change size of board."""
    global minesweeper
    keys = sorted(minesweeper['mines'])
    index = keys.index(minesweeper['size']) + add
    if index >= 0 and index < len(keys):
        minesweeper['size'] = keys[index]
        minesweeper['count_max'] = minesweeper['mines'][minesweeper['size']]
        weechat.buffer_clear(minesweeper['buffer'])
        minesweeper_adjust_zoom()
        minesweeper_new_game()
Пример #12
0
def floodit_change_size(add):
    """Change size of board."""
    global floodit
    keys = sorted(floodit['sizes'])
    index = keys.index(floodit['size']) + add
    if index >= 0 and index < len(keys):
        floodit['size'] = keys[index]
        floodit['count_max'] = floodit['sizes'][floodit['size']]
        weechat.buffer_clear(floodit['buffer'])
        floodit_adjust_zoom()
        floodit_new_game()
Пример #13
0
def floodit_change_size(add):
    """Change size of board."""
    global floodit
    keys = sorted(floodit['sizes'])
    index = keys.index(floodit['size']) + add
    if index >= 0 and index < len(keys):
        floodit['size'] = keys[index]
        floodit['count_max'] = floodit['sizes'][floodit['size']]
        weechat.buffer_clear(floodit['buffer'])
        floodit_adjust_zoom()
        floodit_new_game()
Пример #14
0
def buffer_refresh():
    global curline
    if not script_buffer():
        return
    weechat.buffer_clear(script_buffer())

    # FIXME: Make sure buffer gets redrawn at the same position as last time
    y = 0
    for list_data in buffer_items():
        buffer_refresh_line(y)
        y += 1
    return
Пример #15
0
def buffer_refresh():
    global curline
    if not script_buffer():
        return
    weechat.buffer_clear(script_buffer())

    # FIXME: Make sure buffer gets redrawn at the same position as last time
    y = 0
    for list_data in buffer_items():
        buffer_refresh_line(y)
        y += 1
    return
Пример #16
0
def buffer_create():
	"""Returns our buffer pointer, creates and cleans the buffer if needed."""
	buffer = weechat.buffer_search('python', SCRIPT_NAME)
	if not buffer:
		buffer = weechat.buffer_new(SCRIPT_NAME, 'buffer_input', '', 'buffer_close', '')
		weechat.buffer_set(buffer, 'time_for_each_line', '0')
		weechat.buffer_set(buffer, 'nicklist', '0')
		weechat.buffer_set(buffer, 'title', 'egrep output buffer')
		weechat.buffer_set(buffer, 'localvar_set_no_log', '1')
	else:
		if get_config_boolean('clear_buffer'):
			weechat.buffer_clear(buffer)
	return buffer
Пример #17
0
def buffer_create():
    """Returns our buffer pointer, creates and cleans the buffer if needed."""
    buffer = weechat.buffer_search('python', SCRIPT_NAME)
    if not buffer:
        buffer = weechat.buffer_new(SCRIPT_NAME, 'buffer_input', '',
                                    'buffer_close', '')
        weechat.buffer_set(buffer, 'time_for_each_line', '0')
        weechat.buffer_set(buffer, 'nicklist', '0')
        weechat.buffer_set(buffer, 'title', 'egrep output buffer')
        weechat.buffer_set(buffer, 'localvar_set_no_log', '1')
    else:
        if get_config_boolean('clear_buffer'):
            weechat.buffer_clear(buffer)
    return buffer
Пример #18
0
def rooms_refresh():
    global rooms_channels, rooms_buffer, rooms_channels_filtered, rooms_filter
    weechat.buffer_clear(rooms_buffer)

    rooms_channels_filtered = []
    y = 0
    for list_data in rooms_channels:
        if rooms_filter:
            if rooms_filter.lower() not in list_data['name'].lower():
                continue

        rooms_channels_filtered.append(list_data)

        rooms_refresh_line(y)
        y += 1
    return
Пример #19
0
def timer_cb(data, remaining_calls):
    global previous_mtime
    try:
        mtime = os.stat("/run/motd.dynamic").st_mtime
    except OSError:
        return  # Try again later
    if mtime == previous_mtime:
        return weechat.WEECHAT_RC_OK

    previous_mtime = mtime
    weechat.buffer_clear(buffer)
    with open("/run/motd.dynamic") as motd:
        for line in motd:
            weechat.prnt(buffer, line)

    return weechat.WEECHAT_RC_OK
Пример #20
0
def urlserver_open_buffer():
    global urlserver, urlserver_settings
    if not urlserver['buffer']:
        urlserver['buffer'] = weechat.buffer_new(SCRIPT_BUFFER,
                                                 'urlserver_buffer_input_cb', '',
                                                 'urlserver_buffer_close_cb', '')
    if urlserver['buffer']:
        weechat.buffer_set(urlserver['buffer'], 'title', 'urlserver')
        weechat.buffer_set(urlserver['buffer'], 'localvar_set_no_log', '1')
        weechat.buffer_set(urlserver['buffer'], 'time_for_each_line', '0')
        weechat.buffer_set(urlserver['buffer'], 'print_hooks_enabled', '0')
        weechat.buffer_clear(urlserver['buffer'])
        keys = sorted(urlserver['urls'])
        for key in keys:
            urlserver_display_url_detail(key)
        weechat.buffer_set(urlserver['buffer'], 'display', '1')
Пример #21
0
def vdm_get(key):
    """ Get some VDMs by launching background process. """
    global vdm_buffer, vdm_hook_process, vdm_key, vdm_stdout, vdm_oldlist
    # open buffer if needed
    if vdm_buffer == "":
        vdm_buffer_create()
    # set language
    if key == "fr" or key == "en":
        weechat.config_set_plugin("lang", key)
        vdm_buffer_set_title()
        return
    # clear buffer
    if key[0] == "*":
        if vdm_buffer != "":
            weechat.buffer_clear(vdm_buffer)
        vdm_oldlist = []
        key = key[1:]
    # previous page
    if key == "-":
        items = vdm_key.split("/", 1)
        if len(items) == 1:
            page = 0
        else:
            page = int(items[1]) - 1
        if page <= 0:
            vdm_key = items[0]
        else:
            vdm_key = "%s/%s" % (items[0], page)
    elif key == "+":
        # next page
        items = vdm_key.split("/", 1)
        if len(items) == 1:
            page = 1
        else:
            page = int(items[1]) + 1
        vdm_key = "%s/%s" % (items[0], page)
    elif key != "r":
        vdm_key = key
    # get data from website, via hook_process
    if vdm_hook_process != "":
        weechat.unhook(vdm_hook_process)
        vdm_hook_process = ""
    vdm_stdout = ""
    url = weechat.config_get_plugin("url") % (
        vdm_key, weechat.config_get_plugin("lang"))
    vdm_hook_process = weechat.hook_process("url:%s" % url, 10 * 1000,
                                            "vdm_process_cb", "")
Пример #22
0
def samegame_display(clear=False):
    """Display status and board."""
    global samegame
    if not samegame["buffer"]:
        return
    if clear:
        weechat.buffer_clear(samegame["buffer"])
    spaces = " " * ((samegame["zoom"] + 1) * 2)

    # display status
    str_status = "Board: %s%dx%d%s    Colors: %s%d%s    Score: %s%d" % (
        weechat.color("white"),
        samegame["size"][0],
        samegame["size"][1],
        weechat.color("chat"),
        weechat.color("white"),
        samegame["numcolors"],
        weechat.color("chat"),
        weechat.color("white"),
        samegame["score"],
    )
    str_end = "%s%s" % (weechat.color("white"), samegame["end"])
    weechat.prnt_y(samegame["buffer"], 0, "%s    %s" % (str_status, str_end))

    # display board
    weechat.prnt_y(
        samegame["buffer"],
        1,
        "%s┌%s┐" % (weechat.color("chat"), "─" * (samegame["size"][0] * ((samegame["zoom"] + 1) * 2))),
    )
    for y, line in enumerate(samegame["board"]):
        str_line = "│"
        for color in line:
            if color < 0:
                str_color = "default"
            else:
                str_color = samegame["colors"][color]
            str_line += "%s%s" % (weechat.color(",%s" % str_color), spaces)
        str_line += "%s│" % weechat.color("chat")
        for i in range(0, samegame["zoom"] + 1):
            weechat.prnt_y(samegame["buffer"], 2 + (y * (samegame["zoom"] + 1)) + i, str_line)
    weechat.prnt_y(
        samegame["buffer"],
        1 + (samegame["size"][1] * (samegame["zoom"] + 1)) + 1,
        "%s└%s┘" % (weechat.color("chat"), "─" * (samegame["size"][0] * ((samegame["zoom"] + 1) * 2))),
    )
Пример #23
0
def urlserver_open_buffer():
    global urlserver, urlserver_settings
    if not urlserver["buffer"]:
        urlserver["buffer"] = weechat.buffer_new(
            SCRIPT_BUFFER, "urlserver_buffer_input_cb", "", "urlserver_buffer_close_cb", ""
        )
    if urlserver["buffer"]:
        weechat.buffer_set(urlserver["buffer"], "title", "urlserver")
        weechat.buffer_set(urlserver["buffer"], "localvar_set_no_log", "1")
        weechat.buffer_set(urlserver["buffer"], "time_for_each_line", "0")
        weechat.buffer_set(urlserver["buffer"], "print_hooks_enabled", "0")
        weechat.buffer_clear(urlserver["buffer"])
        urls = urlserver["urls"].items()
        for url in urls:
            key = url[1]
            urlserver_display_url_detail(key)
        weechat.buffer_set(urlserver["buffer"], "display", "1")
Пример #24
0
def urlserver_open_buffer():
    global urlserver, urlserver_settings
    if not urlserver['buffer']:
        urlserver['buffer'] = weechat.buffer_new(
            SCRIPT_BUFFER,
            'urlserver_buffer_input_cb', '',
            'urlserver_buffer_close_cb', '')
    if urlserver['buffer']:
        weechat.buffer_set(urlserver['buffer'], 'title', 'urlserver')
        weechat.buffer_set(urlserver['buffer'], 'localvar_set_no_log', '1')
        weechat.buffer_set(urlserver['buffer'], 'time_for_each_line', '0')
        weechat.buffer_set(urlserver['buffer'], 'print_hooks_enabled', '0')
        weechat.buffer_clear(urlserver['buffer'])
        keys = sorted(urlserver['urls'])
        for key in keys:
            urlserver_display_url_detail(key)
        weechat.buffer_set(urlserver['buffer'], 'display', '1')
Пример #25
0
def vdm_get(key):
    """ Get some VDMs by launching background process. """
    global vdm_buffer, vdm_hook_process, vdm_key, vdm_stdout, vdm_oldlist
    # open buffer if needed
    if vdm_buffer == "":
        vdm_buffer_create()
    # set language
    if key == "fr" or key == "en":
        weechat.config_set_plugin("lang", key)
        vdm_buffer_set_title()
        return
    # clear buffer
    if key[0] == "*":
        if vdm_buffer != "":
            weechat.buffer_clear(vdm_buffer)
        vdm_oldlist = []
        key = key[1:]
    # previous page
    if key == "-":
        items = vdm_key.split("/", 1)
        if len(items) == 1:
            page = 0
        else:
            page = int(items[1]) - 1
        if page <= 0:
            vdm_key = items[0]
        else:
            vdm_key = "%s/%s" % (items[0], page)
    elif key == "+":
        # next page
        items = vdm_key.split("/", 1)
        if len(items) == 1:
            page = 1
        else:
            page = int(items[1]) + 1
        vdm_key = "%s/%s" % (items[0], page)
    elif key != "r":
        vdm_key = key
    # get data from website, via hook_process
    if vdm_hook_process != "":
        weechat.unhook(vdm_hook_process)
        vdm_hook_process = ""
    vdm_stdout = ""
    url = weechat.config_get_plugin("url") % (vdm_key, weechat.config_get_plugin("lang"))
    vdm_hook_process = weechat.hook_process("url:%s" % url, 10 * 1000, "vdm_process_cb", "")
Пример #26
0
def show_nicks(args):
    global nicklist

    buffer = weechat.buffer_search('python', 'hipchat_nicks')
    if not buffer:
        buffer = weechat.buffer_new("hipchat_nicks", "nicks_input_cb", "", "", "")
    else:
        weechat.buffer_clear(buffer)

    weechat.buffer_set(buffer, "title", 'Hipchat users')
    weechat.buffer_set(buffer, "notify", "0")
    weechat.buffer_set(buffer, "nicklist", "0")
    weechat.buffer_set(buffer, "type", "free")
    weechat.buffer_set(buffer, 'localvar_set_hipchat_args', args)

    if nicklist is None:
        nicklist_download()
        return
    show_nicks_cb('', '', '')
Пример #27
0
def tictactoe_display(clear=False):
    """Display board."""
    if not tictactoe['buffer']:
        return
    if clear:
        weechat.buffer_clear(tictactoe['buffer'])

    line = 1
    for y in range(0, 3):
        for i in range(0, 3):
            str_line = '  '
            for x in range(0, 3):
                pos = (y * 3) + x
                if i == 0:
                    str_line += '%s%d     ' % (weechat.color(
                        tictactoe_settings['color_digits']), 9 - ((y * 3) +
                                                                  (2 - x)))
                else:
                    str_line += '%s%s' % (weechat.color(
                        tictactoe['colors'][tictactoe['board'][pos]]
                    ), tictactoe['symbols'][tictactoe['board'][pos]][i - 1])
                if x < 2:
                    str_line += '%s%s' % (weechat.color(
                        tictactoe_settings['color_board']), '│')
            if y == 0 and i == 0:
                str_line += '     %sO%s = you' % (weechat.color(
                    tictactoe_settings['color_human']),
                                                  weechat.color('default'))
            if y == 0 and i == 1:
                str_line += '     %sX%s = computer' % (
                    weechat.color(tictactoe_settings['color_computer']),
                    weechat.color('default'))
            weechat.prnt_y(tictactoe['buffer'], line, str_line)
            line += 1
        if y < 2:
            weechat.prnt_y(
                tictactoe['buffer'], line, '  %s──────┼──────┼──────' %
                weechat.color(tictactoe_settings['color_board']))
            line += 1
    line += 1
    weechat.prnt_y(
        tictactoe['buffer'], line, '%s%s' %
        (weechat.color(tictactoe_settings['color_status']), tictactoe['end']))
Пример #28
0
def infolist_display(buffer, args):
	items = args.split(" ", 1)
	infolist_args = ""
	infolist_pointer = ""
	if len(items) >= 2:
		infolist_args = items[1]
		if infolist_args[:2] == "0x":
			infolist_pointer, sep, infolist_args = infolist_args.partition(" ")
		elif infolist_args[:3] == "\"\" ":
			infolist_args = infolist_args[3:]

	infolist = weechat.infolist_get(items[0], infolist_pointer, infolist_args)
	if infolist == "":
		weechat.prnt_date_tags(buffer, 0, "no_filter",
				"%sInfolist '%s' not found."
				% (weechat.prefix("error"), items[0]))
		return weechat.WEECHAT_RC_OK

	item_count = 0
	weechat.buffer_clear(buffer)
	weechat.prnt(buffer, "")
	count = 0
	while weechat.infolist_next(infolist):
		item_count += 1
		if item_count > 1:
			weechat.prnt(buffer, "")

		fields = weechat.infolist_fields(infolist).split(",")
		for field in fields:
			(type, name) = field.split(":", 1)
			if name != 'host':
				continue
			value = weechat.infolist_string(infolist, name)
			name_end = "." * (30 - len(name))
			weechat.prnt(buffer, "%s: %s%s" %
					(name, weechat.color("cyan"), value))
			prefix = ""
			count += 1
	if count == 0:
		weechat.prnt_date_tags(buffer, 0, "no_filter", "Empty infolist.")
	weechat.infolist_free(infolist)
	return weechat.WEECHAT_RC_OK
Пример #29
0
def command_show_emotes_cb(data, cmd_buf, args):
    global emoji
    global return_buffer
    return_buffer = cmd_buf     # is this the best way?

    args = args.split()

    if args[0] == 'list':
        buf = weechat.buffer_search("python", "emote")
        weechat.buffer_clear(buf)
        wprint(buf, 'got data="%s" args="%s"' % (str(data), str(args)))
        for k,v in emoji.items():
            wprint(buf, '%16s --> %s' % (k,v))
        weechat.buffer_set(buf, 'display', '1')
        return weechat.WEECHAT_RC_OK

    # if args[0] == 'load':
    #     emoji = load_emoji()
    #     return weechat.WEECHAT_RC_OK

    return weechat.WEECHAT_RC_OK
Пример #30
0
def samegame_display(clear=False):
    """Display status and board."""
    global samegame
    if not samegame['buffer']:
        return
    if clear:
        weechat.buffer_clear(samegame['buffer'])
    spaces = ' ' * ((samegame['zoom'] + 1) * 2)

    # display status
    str_status = 'Board: %s%dx%d%s    Colors: %s%d%s    Score: %s%d' % (
        weechat.color('white'), samegame['size'][0], samegame['size'][1],
        weechat.color('chat'), weechat.color('white'), samegame['numcolors'],
        weechat.color('chat'), weechat.color('white'), samegame['score'])
    str_end = '%s%s' % (weechat.color('white'), samegame['end'])
    weechat.prnt_y(samegame['buffer'], 0, '%s    %s' % (str_status, str_end))

    # display board
    weechat.prnt_y(
        samegame['buffer'], 1,
        '%s┌%s┐' % (weechat.color('chat'), '─' *
                    (samegame['size'][0] * ((samegame['zoom'] + 1) * 2))))
    for y, line in enumerate(samegame['board']):
        str_line = '│'
        for color in line:
            if color < 0:
                str_color = 'default'
            else:
                str_color = samegame['colors'][color]
            str_line += '%s%s' % (weechat.color(',%s' % str_color), spaces)
        str_line += '%s│' % weechat.color('chat')
        for i in range(0, samegame['zoom'] + 1):
            weechat.prnt_y(samegame['buffer'],
                           2 + (y * (samegame['zoom'] + 1)) + i, str_line)
    weechat.prnt_y(
        samegame['buffer'],
        1 + (samegame['size'][1] * (samegame['zoom'] + 1)) + 1,
        '%s└%s┘' % (weechat.color('chat'), '─' *
                    (samegame['size'][0] * ((samegame['zoom'] + 1) * 2))))
Пример #31
0
def update_gcal_buffer(buffer, events):
    weechat.buffer_clear(buffer)

    if events == []:
        weechat.prnt(buffer, 'No events for now. YAY!!!')

    dates = {}
    for event in events:
        dt = datetime_parse(event['date'])
        datestr = dt.strftime('%a %Y-%m-%d')
        timestr = dt.strftime('%H:%M')

        if datestr not in dates:
            dates[datestr] = []

        dates[datestr].append({'time': timestr, 'summary': event['summary']})

    for datestr in dates.keys():
        weechat.prnt(buffer, datestr)

        dt_events = dates[datestr]
        for event in dt_events:
            weechat.prnt(buffer, '{} {}'.format(event['time'],
                                                event['summary']))
Пример #32
0
def floodit_display(clear=False):
    """Display status and board."""
    global floodit
    if not floodit['buffer']:
        return
    if clear:
        weechat.buffer_clear(floodit['buffer'])
    spaces = ' ' * ((floodit['zoom'] + 1) * 2)
    str_line = ''
    for index, color in enumerate(floodit['colors']):
        str_select = [' ', ' ']
        if floodit['color'] == index:
            str_select = ['»', '«']
        str_line += '%s%s%s%s%s%s%s' % (
            weechat.color('white,default'), str_select[0],
            weechat.color(',%s' % color), spaces,
            weechat.color('white,default'), str_select[1], spaces[0:-2])
    str_status = ''
    str_end = ''
    if floodit['mode'] == 'single':
        board = copy.deepcopy(floodit['board'])
        floodit_flood_xy(board, 0, 0, board[0][0])
        percent = (floodit_count_color(board, -1) * 100) // (floodit['size'] *
                                                             floodit['size'])
        str_status = '%2d/%d%s (%d%%)' % (floodit['count'],
                                          floodit['count_max'],
                                          weechat.color('chat'), percent)
        message_end = {'win': '** CONGRATS! **', 'lose': '...GAME OVER!...'}
    elif floodit['mode'] == 'versus':
        colors = ['yellow', 'lightred']
        board = copy.deepcopy(floodit['board'])
        floodit_flood_xy(board, 0, 0, board[0][0])
        count_player = floodit_count_color(board, -1)
        board = copy.deepcopy(floodit['board'])
        floodit_flood_xy(board, floodit['size'] - 1, floodit['size'] - 1,
                         board[floodit['size'] - 1][floodit['size'] - 1])
        count_computer = floodit_count_color(board, -1)
        if count_player == count_computer:
            colors[1] = 'yellow'
        elif count_computer > count_player:
            colors.reverse()
        str_status = '%sYou: %d%s / %sWee: %d' % (
            weechat.color(colors[0]), count_player, weechat.color('default'),
            weechat.color(colors[1]), count_computer)
        message_end = {
            'win': '** YOU WIN! **',
            'lose': '...You lose...',
            'equality': 'Equality!'
        }
    str_end = '%s%s' % (weechat.color('white'),
                        message_end.get(floodit['end'], ''))
    weechat.prnt_y(floodit['buffer'], 0,
                   '%s %s %s' % (str_line, str_status, str_end))
    for i in range(0, floodit['zoom']):
        weechat.prnt_y(floodit['buffer'], 1 + i, str_line)
    weechat.prnt_y(
        floodit['buffer'], floodit['zoom'] + 1,
        '%s%s' % (weechat.color('blue'), '─' * (floodit['size'] *
                                                ((floodit['zoom'] + 1) * 2))))
    for y, line in enumerate(floodit['board']):
        str_line = ''
        for color in line:
            str_line += '%s%s' % (weechat.color(
                ',%s' % floodit['colors'][color]), spaces)
        str_line += '%s' % weechat.color('chat')
        for i in range(0, floodit['zoom'] + 1):
            weechat.prnt_y(
                floodit['buffer'],
                floodit['zoom'] + 2 + (y * (floodit['zoom'] + 1)) + i,
                str_line)
Пример #33
0
 def clear(self):
     weechat.buffer_clear(self._getBuffer())
Пример #34
0
 def clear(self):
     weechat.buffer_clear(self._getBuffer())
Пример #35
0
def buffer_update():
    """Updates our buffer with new lines."""
    global matched_lines, pattern, count, hilight
    time_grep = now()

    buffer = buffer_create()
    len_matched_lines = len(matched_lines)
    max_lines = get_config_int('max_lines')
    if not count and len_matched_lines > max_lines:
        weechat.buffer_clear(buffer)

    # color variables defined locally
    c_title = color_title
    c_reset = color_reset
    c_summary = color_summary
    c_date = color_date
    c_info = color_info
    c_hilight = color_hilight

    # formatting functions declared locally.
    def make_title(name, number):
        note = ''
        if len_matched_lines > max_lines and not count:
            note = ' (only last %s shown)' % max_lines
        return "Search in %s%s%s | %s lines%s | pattern \"%s%s%s\" | %.4f seconds (%.2f%%)" \
          %(c_title, name, c_reset, number, note, c_title, pattern, c_reset, time_total, time_grep_pct)

    def make_summary(name, number, printed=0):
        note = ''
        if printed != number:
            if printed:
                note = ' (only last %s shown)' % printed
            else:
                note = ' (not shown)'
        return "%s lines matched \"%s%s%s\" in %s%s%s%s" \
          %(number, c_summary, pattern, c_info, c_summary, name, c_reset, note)

    global weechat_format
    weechat_format = True
    nick_dict = {}  # nick caching

    def format_line(s):
        """Returns the log line 's' ready for printing in buffer."""
        global weechat_format
        if weechat_format and s.count('\t') >= 2:
            date, nick, msg = s.split('\t', 2)  # date, nick, message
        else:
            # looks like log isn't in weechat's format
            weechat_format = False  # incoming lines won't be formatted if they have 2 tabs
            date, nick, msg = '', '', s.replace('\t', ' ')
        # we don't want colors if there's match highlighting
        if hilight:
            # fix color reset when there's highlighting from date to prefix
            if c_hilight in date and not c_reset in date:
                nick = c_hilight + nick
            return '%s\t%s %s' % (date, nick, msg)
        else:
            if nick in nick_dict:
                nick = nick_dict[nick]
            else:
                # cache nick
                s = color_nick(nick)
                nick_dict[nick] = s
                nick = s
            return '%s%s\t%s%s %s' % (c_date, date, nick, c_reset, msg)

    def color_nick(nick):
        """Returns coloured nick, with coloured mode if any."""
        # XXX should check if nick has a prefix and subfix string?
        modes = '@!+%'  # nick modes
        if not nick: return ''
        # nick mode
        if nick[0] in modes:
            mode, nick = nick[0], nick[1:]
            mode_color = weechat.config_string(weechat.config_get('weechat.color.nicklist_prefix%d' \
             %(modes.find(mode) + 1)))
            mode_color = weechat.color(mode_color)
        else:
            mode = ''
            mode_color = ''
        color_nicks_number = weechat.config_integer(
            weechat.config_get('weechat.look.color_nicks_number'))
        idx = (sum(map(ord, nick)) % color_nicks_number) + 1
        color = weechat.config_string(
            weechat.config_get('weechat.color.chat_nick_color%02d' % idx))
        nick_color = weechat.color(color)
        return '%s%s%s%s' % (mode_color, mode, nick_color, nick)

    prnt = weechat.prnt
    prnt(buffer, '\n')
    print_info('Search for "%s" in %s.' % (pattern, matched_lines), buffer)
    # print last <max_lines> lines
    print_count = max_lines
    if matched_lines:
        print_lines = []
        for log, lines in matched_lines.iteritems():
            if lines:
                # matched lines
                if not count:
                    len_lines = len(lines)
                    if len_lines < print_count:
                        print_lines = lines
                        print_count -= len_lines
                    elif print_count:
                        print_lines = lines[
                            -print_count:]  # grab the last <print_count> lines
                        print_count = 0
                    else:
                        print_lines = []
                    # print lines
                    for line in print_lines:
                        prnt(buffer, format_line(line))

                # summary
                if count or get_config_boolean('show_summary'):
                    summary = make_summary(log, len(lines), len(print_lines))
                    print_info(summary, buffer)

                # separator
                if print_lines:
                    prnt(buffer, '\n')
    else:
        print_info('No matches found.', buffer)

    # set title
    global time_start
    time_end = now()
    # total time
    time_total = time_end - time_start
    # percent of the total time used for grepping
    time_grep_pct = (time_grep - time_start) / time_total * 100
    title = make_title(matched_lines, len_matched_lines)
    weechat.buffer_set(buffer, 'title', title)

    if get_config_boolean('go_to_buffer'):
        weechat.buffer_set(buffer, 'display', '1')
Пример #36
0
def minesweeper_display(clear=False):
    """Display status and board."""
    global minesweeper, minesweeper_settings
    if not minesweeper['buffer']:
        return
    if clear:
        weechat.buffer_clear(minesweeper['buffer'])
    if minesweeper_settings['utf8'] == 'on':
        hbar = '▁'
        vbar = '▕'
        flag = '⚑'
    else:
        hbar = '_'
        vbar = '|'
        flag = 'p'
    str_grid = '%s%s%s%s ' % (hbar, hbar, hbar, hbar * minesweeper['zoom'] * 2)
    weechat.prnt_y(
        minesweeper['buffer'], 0,
        '%s%s' % (weechat.color(minesweeper_settings['color_grid']),
                  str_grid * minesweeper['size']))
    color_explosion = '%s,%s' % (minesweeper_settings['color_grid'],
                                 minesweeper_settings['color_explosion_bg'])
    color_explosion_text = '%s,%s' % (
        minesweeper_settings['color_flag'],
        minesweeper_settings['color_explosion_bg'])
    color_mine = '%s,%s' % (minesweeper_settings['color_grid'],
                            minesweeper_settings['color_mine_bg'])
    color_mine_text = '%s,%s' % (minesweeper_settings['color_mine'],
                                 minesweeper_settings['color_mine_bg'])
    for y, line in enumerate(minesweeper['board']):
        if minesweeper['zoom'] == 0:
            str_lines = ['', '']
        else:
            str_lines = ['', '', '']
        for x, status in enumerate(line):
            if minesweeper['cursor'] and minesweeper['x'] == x and minesweeper[
                    'y'] == y:
                color_nostatus = '%s,%s' % (
                    minesweeper_settings['color_grid'],
                    minesweeper_settings['color_cursor_bg'])
                color_flag = '%s,%s' % (
                    minesweeper_settings['color_grid'],
                    minesweeper_settings['color_cursor_bg'])
                color_flag_text = '%s,%s' % (
                    minesweeper_settings['color_flag'],
                    minesweeper_settings['color_cursor_bg'])
                color_digit = '%s,%s' % (
                    minesweeper_settings['color_grid'],
                    minesweeper_settings['color_cursor_bg'])
                color_digit_text_bg = ',%s' % minesweeper_settings[
                    'color_cursor_bg']
            else:
                color_nostatus = '%s,%s' % (
                    minesweeper_settings['color_grid'],
                    minesweeper_settings['color_square_bg'])
                color_flag = '%s,%s' % (
                    minesweeper_settings['color_grid'],
                    minesweeper_settings['color_square_bg'])
                color_flag_text = '%s,%s' % (
                    minesweeper_settings['color_flag'],
                    minesweeper_settings['color_square_bg'])
                color_digit = '%s,default' % minesweeper_settings['color_grid']
                color_digit_text_bg = ',default'
            if status[1] == ' ':
                char = ' '
                if status[0] and minesweeper['cheat']:
                    char = '*'
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s %s%s' % (weechat.color(
                        color_nostatus), char, vbar, weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (
                        weechat.color(color_nostatus), hbar * 3, vbar,
                        weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(
                        color_nostatus), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s  %s%s' % (weechat.color(
                        color_nostatus), char, vbar, weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (
                        weechat.color(color_nostatus), hbar * 5, vbar,
                        weechat.color('reset'))
            elif status[1] == 'F':
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s%s%s %s%s' % (
                        weechat.color(color_flag),
                        weechat.color(color_flag_text), flag,
                        weechat.color(color_flag), vbar,
                        weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_flag),
                                                  hbar * 3, vbar,
                                                  weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(color_flag),
                                                     vbar,
                                                     weechat.color('reset'))
                    str_lines[1] += '%s  %s%s%s  %s%s' % (
                        weechat.color(color_flag),
                        weechat.color(color_flag_text), flag,
                        weechat.color(color_flag), vbar,
                        weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_flag),
                                                  hbar * 5, vbar,
                                                  weechat.color('reset'))
            elif status[1].isdigit():
                char = status[1]
                if char == '0':
                    char = ' '
                    color_digit_text = 'default'
                else:
                    color_digit_text = minesweeper['color_digits'][
                        int(status[1]) - 1]
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s%s%s %s%s' % (
                        weechat.color(color_digit),
                        weechat.color(color_digit_text + color_digit_text_bg),
                        char, weechat.color(color_digit), vbar,
                        weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_digit),
                                                  hbar * 3, vbar,
                                                  weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(
                        color_digit), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s%s%s  %s%s' % (
                        weechat.color(color_digit),
                        weechat.color(color_digit_text + color_digit_text_bg),
                        char, weechat.color(color_digit), vbar,
                        weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_digit),
                                                  hbar * 5, vbar,
                                                  weechat.color('reset'))
            elif status[1] == '+':
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s*%s %s%s' % (
                        weechat.color(color_mine),
                        weechat.color(color_mine_text),
                        weechat.color(color_mine), vbar,
                        weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_mine),
                                                  hbar * 3, vbar,
                                                  weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(color_mine),
                                                     vbar,
                                                     weechat.color('reset'))
                    str_lines[1] += '%s  %s*%s  %s%s' % (
                        weechat.color(color_mine),
                        weechat.color(color_mine_text),
                        weechat.color(color_mine), vbar,
                        weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_mine),
                                                  hbar * 5, vbar,
                                                  weechat.color('reset'))
            elif status[1] == '*':
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s*%s %s%s' % (
                        weechat.color(color_explosion),
                        weechat.color(color_explosion_text),
                        weechat.color(color_explosion), vbar,
                        weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (
                        weechat.color(color_explosion), hbar * 3, vbar,
                        weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(
                        color_explosion), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s*%s  %s%s' % (
                        weechat.color(color_explosion),
                        weechat.color(color_explosion_text),
                        weechat.color(color_explosion), vbar,
                        weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (
                        weechat.color(color_explosion), hbar * 5, vbar,
                        weechat.color('reset'))
        for i, str_line in enumerate(str_lines):
            weechat.prnt_y(minesweeper['buffer'], 1 + (y * len(str_lines)) + i,
                           str_line)
    minesweeper_display_status()
Пример #37
0
def reload_conversation(data, buffer, arg):
    conv_id = weechat.buffer_get_string(buffer, "localvar_conversation_id")
    weechat.buffer_clear(buffer)
    status.get_last_history(conv_id)
    return weechat.WEECHAT_RC_OK
Пример #38
0
def infolist_display(buffer, args):
    global infolist_var_type

    items = args.split(" ", 1)
    infolist_args = ""
    infolist_pointer = ""
    if len(items) >= 2:
        infolist_args = items[1]
        if infolist_args[:2] == "0x":
            infolist_pointer, sep, infolist_args = infolist_args.partition(" ")
        elif infolist_args[:3] == "\"\" ":
            infolist_args = infolist_args[3:]

    infolist = weechat.infolist_get(items[0], infolist_pointer, infolist_args)
    if infolist == "":
        weechat.prnt_date_tags(
            buffer, 0, "no_filter",
            "%sInfolist '%s' not found." % (weechat.prefix("error"), items[0]))
        return weechat.WEECHAT_RC_OK

    item_count = 0
    weechat.buffer_clear(buffer)
    weechat.prnt_date_tags(
        buffer, 0, "no_filter",
        "Infolist '%s', with pointer '%s' and arguments '%s':" %
        (items[0], infolist_pointer, infolist_args))
    weechat.prnt(buffer, "")
    count = 0
    while weechat.infolist_next(infolist):
        item_count += 1
        if item_count > 1:
            weechat.prnt(buffer, "")

        fields = weechat.infolist_fields(infolist).split(",")
        prefix = "%s[%s%d%s]\t" % (weechat.color("chat_delimiters"),
                                   weechat.color("chat_buffer"), item_count,
                                   weechat.color("chat_delimiters"))
        for field in fields:
            (type, name) = field.split(":", 1)
            value = ""
            quote = ""
            if type == "i":
                value = weechat.infolist_integer(infolist, name)
            elif type == "s":
                value = weechat.infolist_string(infolist, name)
                quote = "'"
            elif type == "p":
                value = weechat.infolist_pointer(infolist, name)
            elif type == "t":
                value = weechat.infolist_time(infolist, name)
                # since WeeChat 2.2, infolist_time returns a long integer
                # instead of a string
                if not isinstance(value, str):
                    str_date = time.strftime('%F %T',
                                             time.localtime(int(value)))
                    value = '%d (%s)' % (value, str_date)
            name_end = "." * (30 - len(name))
            weechat.prnt_date_tags(
                buffer, 0, "no_filter", "%s%s%s: %s%s%s %s%s%s%s%s%s" %
                (prefix, name, name_end, weechat.color("brown"),
                 infolist_var_type[type], weechat.color("chat"),
                 weechat.color("chat"), quote, weechat.color("cyan"), value,
                 weechat.color("chat"), quote))
            prefix = ""
            count += 1
    if count == 0:
        weechat.prnt_date_tags(buffer, 0, "no_filter", "Empty infolist.")
    weechat.infolist_free(infolist)
    return weechat.WEECHAT_RC_OK
Пример #39
0
def infolist_display(buffer, args):
    global infolist_var_type
    
    items = args.split(" ", 1)
    infolist_args = ""
    infolist_pointer = ""
    if len(items) >= 2:
        infolist_args = items[1]
        if infolist_args[:2] == "0x":
            infolist_pointer, sep, infolist_args = infolist_args.partition(" ")
        elif infolist_args[:3] == "\"\" ":
            infolist_args = infolist_args[3:]
    
    infolist = weechat.infolist_get(items[0], infolist_pointer, infolist_args)
    if infolist == "":
        weechat.prnt_date_tags(buffer, 0, "no_filter",
                               "%sInfolist '%s' not found."
                               % (weechat.prefix("error"), items[0]))
        return weechat.WEECHAT_RC_OK
    
    item_count = 0
    weechat.buffer_clear(buffer)
    weechat.prnt_date_tags(buffer, 0, "no_filter",
                           "Infolist '%s', with pointer '%s' and arguments '%s':" % (items[0],
                               infolist_pointer, infolist_args))
    weechat.prnt(buffer, "")
    count = 0
    while weechat.infolist_next(infolist):
        item_count += 1
        if item_count > 1:
            weechat.prnt(buffer, "")
        
        fields = weechat.infolist_fields(infolist).split(",")
        prefix = "%s[%s%d%s]\t" % (weechat.color("chat_delimiters"),
                                   weechat.color("chat_buffer"),
                                   item_count,
                                   weechat.color("chat_delimiters"))
        for field in fields:
            (type, name) = field.split(":", 1)
            value = ""
            quote = ""
            if type == "i":
                value = weechat.infolist_integer(infolist, name)
            elif type == "s":
                value = weechat.infolist_string(infolist, name)
                quote = "'"
            elif type == "p":
                value = weechat.infolist_pointer(infolist, name)
            elif type == "t":
                value = weechat.infolist_time(infolist, name)
            name_end = "." * (30 - len(name))
            weechat.prnt_date_tags(buffer, 0, "no_filter",
                                   "%s%s%s: %s%s%s %s%s%s%s%s%s" %
                                   (prefix, name, name_end,
                                    weechat.color("brown"), infolist_var_type[type],
                                    weechat.color("chat"), 
                                    weechat.color("chat"), quote,
                                    weechat.color("cyan"), value,
                                    weechat.color("chat"), quote))
            prefix = ""
            count += 1
    if count == 0:
        weechat.prnt_date_tags(buffer, 0, "no_filter", "Empty infolist.")
    weechat.infolist_free(infolist)
    return weechat.WEECHAT_RC_OK
Пример #40
0
def buffer_update():
	"""Updates our buffer with new lines."""
	global matched_lines, pattern, count, hilight
	time_grep = now()

	buffer = buffer_create()
	len_matched_lines = len(matched_lines)
	max_lines = get_config_int('max_lines')
	if not count and len_matched_lines > max_lines:
		weechat.buffer_clear(buffer)

	# color variables defined locally
	c_title = color_title
	c_reset = color_reset
	c_summary = color_summary
	c_date = color_date
	c_info = color_info
	c_hilight = color_hilight

	# formatting functions declared locally.
	def make_title(name, number):
		note = ''
		if len_matched_lines > max_lines and not count:
			note = ' (only last %s shown)' %max_lines
		return "Search in %s%s%s | %s lines%s | pattern \"%s%s%s\" | %.4f seconds (%.2f%%)" \
				%(c_title, name, c_reset, number, note, c_title, pattern, c_reset, time_total, time_grep_pct)

	def make_summary(name, number, printed=0):
		note = ''
		if printed != number:
			if printed:
				note = ' (only last %s shown)' %printed
			else:
				note = ' (not shown)'
		return "%s lines matched \"%s%s%s\" in %s%s%s%s" \
				%(number, c_summary, pattern, c_info, c_summary, name, c_reset, note)

	global weechat_format
	weechat_format = True
	nick_dict = {} # nick caching
	def format_line(s):
		"""Returns the log line 's' ready for printing in buffer."""
		global weechat_format
		if weechat_format and s.count('\t') >= 2:
			date, nick, msg = s.split('\t', 2) # date, nick, message
		else:
			# looks like log isn't in weechat's format
			weechat_format = False # incoming lines won't be formatted if they have 2 tabs
			date, nick, msg = '', '', s.replace('\t', ' ')
		# we don't want colors if there's match highlighting
		if hilight:
			# fix color reset when there's highlighting from date to prefix
			if c_hilight in date and not c_reset in date:
				nick = c_hilight + nick
			return '%s\t%s %s' %(date, nick, msg)
		else:
			if nick in nick_dict:
				nick = nick_dict[nick]
			else:
				# cache nick
				s = color_nick(nick)
				nick_dict[nick] = s
				nick = s
			return '%s%s\t%s%s %s' %(c_date, date, nick, c_reset, msg)

	def color_nick(nick):
		"""Returns coloured nick, with coloured mode if any."""
		# XXX should check if nick has a prefix and subfix string?
		modes = '@!+%' # nick modes
		if not nick: return ''
		# nick mode
		if nick[0] in modes:
			mode, nick = nick[0], nick[1:]
			mode_color = weechat.config_string(weechat.config_get('weechat.color.nicklist_prefix%d' \
				%(modes.find(mode) + 1)))
			mode_color = weechat.color(mode_color)
		else:
			mode = ''
			mode_color = ''
		color_nicks_number = weechat.config_integer(weechat.config_get('weechat.look.color_nicks_number'))
		idx = (sum(map(ord, nick))%color_nicks_number) + 1
		color = weechat.config_string(weechat.config_get('weechat.color.chat_nick_color%02d' %idx))
		nick_color = weechat.color(color)
		return '%s%s%s%s' %(mode_color, mode, nick_color, nick)

	prnt = weechat.prnt
	prnt(buffer, '\n')
	print_info('Search for "%s" in %s.' %(pattern, matched_lines), buffer)
	# print last <max_lines> lines
	print_count = max_lines
	if matched_lines:
		print_lines = []
		for log, lines in matched_lines.iteritems():
			if lines:
				# matched lines
				if not count:
					len_lines = len(lines)
					if len_lines < print_count:
						print_lines = lines
						print_count -= len_lines
					elif print_count:
						print_lines = lines[-print_count:] # grab the last <print_count> lines
						print_count = 0
					else:
						print_lines = []
					# print lines
					for line in print_lines:
						prnt(buffer, format_line(line))

				# summary
				if count or get_config_boolean('show_summary'):
					summary = make_summary(log, len(lines), len(print_lines))
					print_info(summary, buffer)

				# separator
				if print_lines:
					prnt(buffer, '\n')
	else:
		print_info('No matches found.', buffer)

	# set title
	global time_start
	time_end = now()
	# total time
	time_total = time_end - time_start
	# percent of the total time used for grepping
	time_grep_pct = (time_grep - time_start)/time_total*100
	title = make_title(matched_lines, len_matched_lines)
	weechat.buffer_set(buffer, 'title', title)

	if get_config_boolean('go_to_buffer'):
		weechat.buffer_set(buffer, 'display', '1')
Пример #41
0
def minesweeper_display(clear=False):
    """Display status and board."""
    global minesweeper, minesweeper_settings
    if not minesweeper['buffer']:
        return
    if clear:
        weechat.buffer_clear(minesweeper['buffer'])
    if minesweeper_settings['utf8'] == 'on':
        hbar = '▁'
        vbar = '▕'
        flag = '⚑'
    else:
        hbar = '_'
        vbar = '|'
        flag = 'p'
    str_grid = '%s%s%s%s ' % (hbar, hbar, hbar, hbar * minesweeper['zoom'] * 2)
    weechat.prnt_y(minesweeper['buffer'], 0, '%s%s' % (weechat.color(minesweeper_settings['color_grid']), str_grid * minesweeper['size']))
    color_explosion = '%s,%s' % (minesweeper_settings['color_grid'], minesweeper_settings['color_explosion_bg'])
    color_explosion_text = '%s,%s' % (minesweeper_settings['color_flag'], minesweeper_settings['color_explosion_bg'])
    color_mine = '%s,%s' % (minesweeper_settings['color_grid'], minesweeper_settings['color_mine_bg'])
    color_mine_text = '%s,%s' % (minesweeper_settings['color_mine'], minesweeper_settings['color_mine_bg'])
    for y, line in enumerate(minesweeper['board']):
        if minesweeper['zoom'] == 0:
            str_lines = ['', '']
        else:
            str_lines = ['', '', '']
        for x, status in enumerate(line):
            if minesweeper['cursor'] and minesweeper['x'] == x and minesweeper['y'] == y:
                color_nostatus = '%s,%s' % (minesweeper_settings['color_grid'], minesweeper_settings['color_cursor_bg'])
                color_flag = '%s,%s' % (minesweeper_settings['color_grid'], minesweeper_settings['color_cursor_bg'])
                color_flag_text = '%s,%s' % (minesweeper_settings['color_flag'], minesweeper_settings['color_cursor_bg'])
                color_digit = '%s,%s' % (minesweeper_settings['color_grid'], minesweeper_settings['color_cursor_bg'])
                color_digit_text_bg = ',%s' % minesweeper_settings['color_cursor_bg']
            else:
                color_nostatus = '%s,%s' % (minesweeper_settings['color_grid'], minesweeper_settings['color_square_bg'])
                color_flag = '%s,%s' % (minesweeper_settings['color_grid'], minesweeper_settings['color_square_bg'])
                color_flag_text = '%s,%s' % (minesweeper_settings['color_flag'], minesweeper_settings['color_square_bg'])
                color_digit = '%s,default' % minesweeper_settings['color_grid']
                color_digit_text_bg = ',default'
            if status[1] == ' ':
                char = ' '
                if status[0] and minesweeper['cheat']:
                    char = '*'
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s %s%s' % (weechat.color(color_nostatus), char, vbar, weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_nostatus), hbar * 3, vbar, weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(color_nostatus), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s  %s%s' % (weechat.color(color_nostatus), char, vbar, weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_nostatus), hbar * 5, vbar, weechat.color('reset'))
            elif status[1] == 'F':
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s%s%s %s%s' % (weechat.color(color_flag), weechat.color(color_flag_text), flag, weechat.color(color_flag), vbar, weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_flag), hbar * 3, vbar, weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(color_flag), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s%s%s  %s%s' % (weechat.color(color_flag), weechat.color(color_flag_text), flag, weechat.color(color_flag), vbar, weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_flag), hbar * 5, vbar, weechat.color('reset'))
            elif status[1].isdigit():
                char = status[1]
                if char == '0':
                    char = ' '
                    color_digit_text = 'default'
                else:
                    color_digit_text = minesweeper['color_digits'][int(status[1]) - 1]
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s%s%s %s%s' % (
                        weechat.color(color_digit), weechat.color(color_digit_text + color_digit_text_bg), char, weechat.color(color_digit), vbar, weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_digit), hbar * 3, vbar, weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(color_digit), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s%s%s  %s%s' % (
                        weechat.color(color_digit), weechat.color(color_digit_text + color_digit_text_bg), char, weechat.color(color_digit), vbar, weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_digit), hbar * 5, vbar, weechat.color('reset'))
            elif status[1] == '+':
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s*%s %s%s' % (weechat.color(color_mine), weechat.color(color_mine_text), weechat.color(color_mine), vbar, weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_mine), hbar * 3, vbar, weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(color_mine), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s*%s  %s%s' % (weechat.color(color_mine), weechat.color(color_mine_text), weechat.color(color_mine), vbar, weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_mine), hbar * 5, vbar, weechat.color('reset'))
            elif status[1] == '*':
                if minesweeper['zoom'] == 0:
                    str_lines[0] += '%s %s*%s %s%s' % (
                        weechat.color(color_explosion), weechat.color(color_explosion_text), weechat.color(color_explosion), vbar, weechat.color('reset'))
                    str_lines[1] += '%s%s%s%s' % (weechat.color(color_explosion), hbar * 3, vbar, weechat.color('reset'))
                else:
                    str_lines[0] += '%s     %s%s' % (weechat.color(color_explosion), vbar, weechat.color('reset'))
                    str_lines[1] += '%s  %s*%s  %s%s' % (
                        weechat.color(color_explosion), weechat.color(color_explosion_text), weechat.color(color_explosion), vbar, weechat.color('reset'))
                    str_lines[2] += '%s%s%s%s' % (weechat.color(color_explosion), hbar * 5, vbar, weechat.color('reset'))
        for i, str_line in enumerate(str_lines):
            weechat.prnt_y(minesweeper['buffer'], 1 + (y * len(str_lines)) + i, str_line)
    minesweeper_display_status()