1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2009-2011 by Elián Hanisch <lambdae2@gmail.com>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 # Search in Weechat buffers and logs (for Weechat 0.3.*)
22 # Inspired by xt's grep.py
23 # Originally I just wanted to add some fixes in grep.py, but then
24 # I got carried away and rewrote everything, so new script.
28 # Search in logs or buffers, see /help grep
30 # Lists logs in ~/.weechat/logs, see /help logs
33 # * plugins.var.python.grep.clear_buffer:
34 # Clear the results buffer before each search. Valid values: on, off
36 # * plugins.var.python.grep.go_to_buffer:
37 # Automatically go to grep buffer when search is over. Valid values: on, off
39 # * plugins.var.python.grep.log_filter:
40 # Coma separated list of patterns that grep will use for exclude logs, e.g.
41 # if you use '*server/*' any log in the 'server' folder will be excluded
42 # when using the command '/grep log'
44 # * plugins.var.python.grep.show_summary:
45 # Shows summary for each log. Valid values: on, off
47 # * plugins.var.python.grep.max_lines:
48 # Grep will only print the last matched lines that don't surpass the value defined here.
50 # * plugins.var.python.grep.size_limit:
51 # Size limit in KiB, is used for decide whenever grepping should run in background or not. If
52 # the logs to grep have a total size bigger than this value then grep run as a new process.
53 # It can be used for force or disable background process, using '0' forces to always grep in
54 # background, while using '' (empty string) will disable it.
56 # * plugins.var.python.grep.default_tail_head:
57 # Config option for define default number of lines returned when using --head or --tail options.
58 # Can be overriden in the command with --number option.
62 # * try to figure out why hook_process chokes in long outputs (using a tempfile as a
64 # * possibly add option for defining time intervals
69 # version 0.7.4: make q work to quit grep buffer (requested by: gb)
71 # 2014-03-29, Felix Eckhofer <felix@tribut.de>
72 # version 0.7.3: fix typo
75 # version 0.7.2: bug fixes
79 # * use TempFile so temporal files are guaranteed to be deleted.
80 # * enable Archlinux workaround.
85 # * using --only-match shows only unique strings.
86 # * fixed bug that inverted -B -A switches when used with -t
89 # version 0.6.8: by xt <xt@bash.no>
90 # * supress highlights when printing in grep buffer
93 # version 0.6.7: by xt <xt@bash.no>
94 # * better temporary file:
95 # use tempfile.mkstemp. to create a temp file in log dir,
96 # makes it safer with regards to write permission and multi user
99 # version 0.6.6: bug fixes
100 # * use WEECHAT_LIST_POS_END in log file completion, makes completion faster
101 # * disable bytecode if using python 2.6
102 # * use single quotes in command string
103 # * fix bug that could change buffer's title when using /grep stop
106 # version 0.6.5: disable bytecode is a 2.6 feature, instead, resort to delete the bytecode manually
109 # version 0.6.4: bug fix
110 # version 0.6.3: added options --invert --only-match (replaces --exact, which is still available
111 # but removed from help)
112 # * use new 'irc_nick_color' info
113 # * don't generate bytecode when spawning a new process
114 # * show active options in buffer title
117 # version 0.6.2: removed 2.6-ish code
118 # version 0.6.1: fixed bug when grepping in grep's buffer
121 # version 0.6.0: implemented grep in background
122 # * improved context lines presentation.
123 # * grepping for big (or many) log files runs in a weechat_process.
124 # * added /grep stop.
125 # * added 'size_limit' option
126 # * fixed a infolist leak when grepping buffers
127 # * added 'default_tail_head' option
128 # * results are sort by line count
129 # * don't die if log is corrupted (has NULL chars in it)
130 # * changed presentation of /logs
131 # * log path completion doesn't suck anymore
132 # * removed all tabs, because I learned how to configure Vim so that spaces aren't annoying
133 # anymore. This was the script's original policy.
136 # version 0.5.5: rename script to 'grep.py' (FlashCode <flashcode@flashtux.org>).
139 # version 0.5.4.1: fix index error when using --after/before-context options.
142 # version 0.5.4: new features
143 # * added --after-context and --before-context options.
144 # * added --context as a shortcut for using both -A -B options.
147 # version 0.5.3: improvements for long grep output
148 # * grep buffer input accepts the same flags as /grep for repeat a search with different
150 # * tweaks in grep's output.
151 # * max_lines option added for limit grep's output.
152 # * code in update_buffer() optimized.
153 # * time stats in buffer title.
154 # * added go_to_buffer config option.
155 # * added --buffer for search only in buffers.
159 # version 0.5.2: made it python-2.4.x compliant
162 # version 0.5.1: some refactoring, show_summary option added.
165 # version 0.5: rewritten from xt's grep.py
166 # * fixed searching in non weechat logs, for cases like, if you're
167 # switching from irssi and rename and copy your irssi logs to %h/logs
168 # * fixed "timestamp rainbow" when you /grep in grep's buffer
169 # * allow to search in other buffers other than current or in logs
170 # of currently closed buffers with cmd 'buffer'
171 # * allow to search in any log file in %h/logs with cmd 'log'
172 # * added --count for return the number of matched lines
173 # * added --matchcase for case sensible search
174 # * added --hilight for color matches
175 # * added --head and --tail options, and --number
176 # * added command /logs for list files in %h/logs
177 # * added config option for clear the buffer before a search
178 # * added config option for filter logs we don't want to grep
179 # * added the posibility to repeat last search with another regexp by writing
180 # it in grep's buffer
181 # * changed spaces for tabs in the code, which is my preference
186 import sys
, getopt
, time
, os
, re
, tempfile
190 from weechat
import WEECHAT_RC_OK
, prnt
, prnt_date_tags
196 SCRIPT_AUTHOR
= "Elián Hanisch <lambdae2@gmail.com>"
197 SCRIPT_VERSION
= "0.7.4"
198 SCRIPT_LICENSE
= "GPL3"
199 SCRIPT_DESC
= "Search in buffers and logs"
200 SCRIPT_COMMAND
= "grep"
202 ### Default Settings ###
204 'clear_buffer' : 'off',
206 'go_to_buffer' : 'on',
207 'max_lines' : '4000',
208 'show_summary' : 'on',
209 'size_limit' : '2048',
210 'default_tail_head' : '10',
213 ### Class definitions ###
214 class linesDict(dict):
216 Class for handling matched lines in more than one buffer.
217 linesDict[buffer_name] = matched_lines_list
219 def __setitem__(self
, key
, value
):
220 assert isinstance(value
, list)
222 dict.__setitem
__(self
, key
, value
)
224 dict.__getitem
__(self
, key
).extend(value
)
226 def get_matches_count(self
):
227 """Return the sum of total matches stored."""
228 if dict.__len
__(self
):
229 return sum(map(lambda L
: L
.matches_count
, self
.itervalues()))
234 """Return the sum of total lines stored."""
235 if dict.__len
__(self
):
236 return sum(map(len, self
.itervalues()))
241 """Returns buffer count or buffer name if there's just one stored."""
244 return self
.keys()[0]
251 """Returns a list of items sorted by line count."""
252 items
= dict.items(self
)
253 items
.sort(key
=lambda i
: len(i
[1]))
256 def items_count(self
):
257 """Returns a list of items sorted by match count."""
258 items
= dict.items(self
)
259 items
.sort(key
=lambda i
: i
[1].matches_count
)
262 def strip_separator(self
):
263 for L
in self
.itervalues():
266 def get_last_lines(self
, n
):
267 total_lines
= len(self
)
268 #debug('total: %s n: %s' %(total_lines, n))
272 for k
, v
in reversed(self
.items()):
277 v
.stripped_lines
= l
-n
283 class linesList(list):
284 """Class for list of matches, since sometimes I need to add lines that aren't matches, I need an
285 independent counter."""
287 def __init__(self
, *args
):
288 list.__init
__(self
, *args
)
289 self
.matches_count
= 0
290 self
.stripped_lines
= 0
292 def append(self
, item
):
293 """Append lines, can be a string or a list with strings."""
294 if isinstance(item
, str):
295 list.append(self
, item
)
299 def append_separator(self
):
300 """adds a separator into the list, makes sure it doen't add two together."""
302 if (self
and self
[-1] != s
) or not self
:
310 def count_match(self
, item
=None):
311 if item
is None or isinstance(item
, str):
312 self
.matches_count
+= 1
314 self
.matches_count
+= len(item
)
316 def strip_separator(self
):
317 """removes separators if there are first or/and last in the list."""
325 ### Misc functions ###
329 return os
.stat(f
).st_size
333 sizeDict
= {0:'b', 1:'KiB', 2:'MiB', 3:'GiB', 4:'TiB'}
334 def human_readable_size(size
):
339 return '%.2f %s' %(size
, sizeDict
.get(power
, ''))
341 def color_nick(nick
):
342 """Returns coloured nick, with coloured mode if any."""
343 if not nick
: return ''
344 wcolor
= weechat
.color
345 config_string
= lambda s
: weechat
.config_string(weechat
.config_get(s
))
346 config_int
= lambda s
: weechat
.config_integer(weechat
.config_get(s
))
348 prefix
= config_string('irc.look.nick_prefix')
349 suffix
= config_string('irc.look.nick_suffix')
350 prefix_c
= suffix_c
= wcolor(config_string('weechat.color.chat_delimiters'))
351 if nick
[0] == prefix
:
354 prefix
= prefix_c
= ''
355 if nick
[-1] == suffix
:
357 suffix
= wcolor(color_delimiter
) + suffix
359 suffix
= suffix_c
= ''
363 mode
, nick
= nick
[0], nick
[1:]
364 mode_color
= wcolor(config_string('weechat.color.nicklist_prefix%d' \
365 %(modes
.find(mode
) + 1)))
367 mode
= mode_color
= ''
369 nick_color
= weechat
.info_get('irc_nick_color', nick
)
371 # probably we're in WeeChat 0.3.0
372 #debug('no irc_nick_color')
373 color_nicks_number
= config_int('weechat.look.color_nicks_number')
374 idx
= (sum(map(ord, nick
))%color
_nicks
_number
) + 1
375 nick_color
= wcolor(config_string('weechat.color.chat_nick_color%02d' %idx))
376 return ''.join((prefix_c
, prefix
, mode_color
, mode
, nick_color
, nick
, suffix_c
, suffix
))
378 ### Config and value validation ###
379 boolDict
= {'on':True, 'off':False}
380 def get_config_boolean(config
):
381 value
= weechat
.config_get_plugin(config
)
383 return boolDict
[value
]
385 default
= settings
[config
]
386 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
387 error("'%s' is invalid, allowed: 'on', 'off'" %value
)
388 return boolDict
[default
]
390 def get_config_int(config
, allow_empty_string
=False):
391 value
= weechat
.config_get_plugin(config
)
395 if value
== '' and allow_empty_string
:
397 default
= settings
[config
]
398 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
399 error("'%s' is not a number." %value
)
402 def get_config_log_filter():
403 filter = weechat
.config_get_plugin('log_filter')
405 return filter.split(',')
410 home
= weechat
.config_string(weechat
.config_get('logger.file.path'))
411 return home
.replace('%h', weechat
.info_get('weechat_dir', ''))
413 def strip_home(s
, dir=''):
414 """Strips home dir from the begging of the log path, this makes them sorter."""
424 script_nick
= SCRIPT_NAME
425 def error(s
, buffer=''):
427 prnt(buffer, '%s%s %s' %(weechat
.prefix('error'), script_nick
, s
))
428 if weechat
.config_get_plugin('debug'):
430 if traceback
.sys
.exc_type
:
431 trace
= traceback
.format_exc()
434 def say(s
, buffer=''):
436 prnt_date_tags(buffer, 0, 'no_highlight', '%s\t%s' %(script_nick
, s
))
440 ### Log files and buffers ###
441 cache_dir
= {} # note: don't remove, needed for completion if the script was loaded recently
442 def dir_list(dir, filter_list
=(), filter_excludes
=True, include_dir
=False):
443 """Returns a list of files in 'dir' and its subdirs."""
446 from fnmatch
import fnmatch
447 #debug('dir_list: listing in %s' %dir)
448 key
= (dir, include_dir
)
450 return cache_dir
[key
]
454 filter_list
= filter_list
or get_config_log_filter()
458 file = file[dir_len
:] # pattern shouldn't match home dir
459 for pattern
in filter_list
:
460 if fnmatch(file, pattern
):
461 return filter_excludes
462 return not filter_excludes
464 filter = lambda f
: not filter_excludes
467 extend
= file_list
.extend
470 for basedir
, subdirs
, files
in walk(dir):
472 # subdirs = map(lambda s : join(s, ''), subdirs)
473 # files.extend(subdirs)
474 files_path
= map(lambda f
: join(basedir
, f
), files
)
475 files_path
= [ file for file in files_path
if not filter(file) ]
479 cache_dir
[key
] = file_list
480 #debug('dir_list: got %s' %str(file_list))
483 def get_file_by_pattern(pattern
, all
=False):
484 """Returns the first log whose path matches 'pattern',
485 if all is True returns all logs that matches."""
486 if not pattern
: return []
487 #debug('get_file_by_filename: searching for %s.' %pattern)
488 # do envvar expandsion and check file
489 file = path
.expanduser(pattern
)
490 file = path
.expandvars(file)
491 if path
.isfile(file):
493 # lets see if there's a matching log
495 file = path
.join(home_dir
, pattern
)
496 if path
.isfile(file):
499 from fnmatch
import fnmatch
501 file_list
= dir_list(home_dir
)
503 for log
in file_list
:
505 if fnmatch(basename
, pattern
):
507 #debug('get_file_by_filename: got %s.' %file)
513 def get_file_by_buffer(buffer):
514 """Given buffer pointer, finds log's path or returns None."""
515 #debug('get_file_by_buffer: searching for %s' %buffer)
516 infolist
= weechat
.infolist_get('logger_buffer', '', '')
517 if not infolist
: return
519 while weechat
.infolist_next(infolist
):
520 pointer
= weechat
.infolist_pointer(infolist
, 'buffer')
521 if pointer
== buffer:
522 file = weechat
.infolist_string(infolist
, 'log_filename')
523 if weechat
.infolist_integer(infolist
, 'log_enabled'):
524 #debug('get_file_by_buffer: got %s' %file)
527 # debug('get_file_by_buffer: got %s but log not enabled' %file)
529 #debug('infolist gets freed')
530 weechat
.infolist_free(infolist
)
532 def get_file_by_name(buffer_name
):
533 """Given a buffer name, returns its log path or None. buffer_name should be in 'server.#channel'
534 or '#channel' format."""
535 #debug('get_file_by_name: searching for %s' %buffer_name)
536 # common mask options
537 config_masks
= ('logger.mask.irc', 'logger.file.mask')
538 # since there's no buffer pointer, we try to replace some local vars in mask, like $channel and
539 # $server, then replace the local vars left with '*', and use it as a mask for get the path with
540 # get_file_by_pattern
541 for config
in config_masks
:
542 mask
= weechat
.config_string(weechat
.config_get(config
))
543 #debug('get_file_by_name: mask: %s' %mask)
545 mask
= mask
.replace('$name', buffer_name
)
546 elif '$channel' in mask
or '$server' in mask
:
547 if '.' in buffer_name
and \
548 '#' not in buffer_name
[:buffer_name
.find('.')]: # the dot isn't part of the channel name
549 # ^ I'm asuming channel starts with #, i'm lazy.
550 server
, channel
= buffer_name
.split('.', 1)
552 server
, channel
= '*', buffer_name
553 if '$channel' in mask
:
554 mask
= mask
.replace('$channel', channel
)
555 if '$server' in mask
:
556 mask
= mask
.replace('$server', server
)
557 # change the unreplaced vars by '*'
558 from string
import letters
560 # vars for time formatting
561 mask
= mask
.replace('%', '$')
563 masks
= mask
.split('$')
564 masks
= map(lambda s
: s
.lstrip(letters
), masks
)
565 mask
= '*'.join(masks
)
568 #debug('get_file_by_name: using mask %s' %mask)
569 file = get_file_by_pattern(mask
)
570 #debug('get_file_by_name: got file %s' %file)
575 def get_buffer_by_name(buffer_name
):
576 """Given a buffer name returns its buffer pointer or None."""
577 #debug('get_buffer_by_name: searching for %s' %buffer_name)
578 pointer
= weechat
.buffer_search('', buffer_name
)
581 infolist
= weechat
.infolist_get('buffer', '', '')
582 while weechat
.infolist_next(infolist
):
583 short_name
= weechat
.infolist_string(infolist
, 'short_name')
584 name
= weechat
.infolist_string(infolist
, 'name')
585 if buffer_name
in (short_name
, name
):
586 #debug('get_buffer_by_name: found %s' %name)
587 pointer
= weechat
.buffer_search('', name
)
590 weechat
.infolist_free(infolist
)
591 #debug('get_buffer_by_name: got %s' %pointer)
594 def get_all_buffers():
595 """Returns list with pointers of all open buffers."""
597 infolist
= weechat
.infolist_get('buffer', '', '')
598 while weechat
.infolist_next(infolist
):
599 buffers
.append(weechat
.infolist_pointer(infolist
, 'pointer'))
600 weechat
.infolist_free(infolist
)
601 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
602 if grep_buffer
and grep_buffer
in buffers
:
603 # remove it from list
604 del buffers
[buffers
.index(grep_buffer
)]
608 def make_regexp(pattern
, matchcase
=False):
609 """Returns a compiled regexp."""
610 if pattern
in ('.', '.*', '.?', '.+'):
611 # because I don't need to use a regexp if we're going to match all lines
613 # matching takes a lot more time if pattern starts or ends with .* and it isn't needed.
614 if pattern
[:2] == '.*':
615 pattern
= pattern
[2:]
616 if pattern
[-2:] == '.*':
617 pattern
= pattern
[:-2]
620 regexp
= re
.compile(pattern
, re
.IGNORECASE
)
622 regexp
= re
.compile(pattern
)
624 raise Exception, 'Bad pattern, %s' %e
627 def check_string(s
, regexp
, hilight
='', exact
=False):
628 """Checks 's' with a regexp and returns it if is a match."""
633 matchlist
= regexp
.findall(s
)
635 if isinstance(matchlist
[0], tuple):
636 # join tuples (when there's more than one match group in regexp)
637 return [ ' '.join(t
) for t
in matchlist
]
641 matchlist
= regexp
.findall(s
)
643 if isinstance(matchlist
[0], tuple):
645 matchlist
= [ item
for L
in matchlist
for item
in L
if item
]
646 matchlist
= list(set(matchlist
)) # remove duplicates if any
648 color_hilight
, color_reset
= hilight
.split(',', 1)
650 s
= s
.replace(m
, '%s%s%s' % (color_hilight
, m
, color_reset
))
653 # no need for findall() here
654 elif regexp
.search(s
):
657 def grep_file(file, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
, invert
):
658 """Return a list of lines that match 'regexp' in 'file', if no regexp returns all lines."""
660 tail
= head
= after_context
= before_context
= False
663 before_context
= after_context
= False
667 #debug(' '.join(map(str, (file, head, tail, after_context, before_context))))
670 # define these locally as it makes the loop run slightly faster
671 append
= lines
.append
672 count_match
= lines
.count_match
673 separator
= lines
.append_separator
676 if check_string(s
, regexp
, hilight
, exact
):
681 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
684 file_object
= open(file, 'r')
688 if tail
or before_context
:
689 # for these options, I need to seek in the file, but is slower and uses a good deal of
690 # memory if the log is too big, so we do this *only* for these options.
691 file_lines
= file_object
.readlines()
694 # instead of searching in the whole file and later pick the last few lines, we
695 # reverse the log, search until count reached and reverse it again, that way is a lot
698 # don't invert context switches
699 before_context
, after_context
= after_context
, before_context
702 before_context_range
= range(1, before_context
+ 1)
703 before_context_range
.reverse()
708 while line_idx
< len(file_lines
):
709 line
= file_lines
[line_idx
]
715 for id in before_context_range
:
717 context_line
= file_lines
[line_idx
- id]
718 if check(context_line
):
719 # match in before context, that means we appended these same lines in a
720 # previous match, so we delete them merging both paragraphs
722 del lines
[id - before_context
- 1:]
732 while id < after_context
+ offset
:
735 context_line
= file_lines
[line_idx
+ id]
736 _context_line
= check(context_line
)
739 context_line
= _context_line
# so match is hilighted with --hilight
746 if limit
and lines
.matches_count
>= limit
:
756 for line
in file_object
:
759 count
or append(line
)
763 while id < after_context
+ offset
:
766 context_line
= file_object
.next()
767 _context_line
= check(context_line
)
770 context_line
= _context_line
772 count
or append(context_line
)
773 except StopIteration:
776 if limit
and lines
.matches_count
>= limit
:
782 def grep_buffer(buffer, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
,
784 """Return a list of lines that match 'regexp' in 'buffer', if no regexp returns all lines."""
787 tail
= head
= after_context
= before_context
= False
790 before_context
= after_context
= False
791 #debug(' '.join(map(str, (tail, head, after_context, before_context, count, exact, hilight))))
793 # Using /grep in grep's buffer can lead to some funny effects
794 # We should take measures if that's the case
795 def make_get_line_funcion():
796 """Returns a function for get lines from the infolist, depending if the buffer is grep's or
798 string_remove_color
= weechat
.string_remove_color
799 infolist_string
= weechat
.infolist_string
800 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
801 if grep_buffer
and buffer == grep_buffer
:
802 def function(infolist
):
803 prefix
= infolist_string(infolist
, 'prefix')
804 message
= infolist_string(infolist
, 'message')
805 if prefix
: # only our messages have prefix, ignore it
809 infolist_time
= weechat
.infolist_time
810 def function(infolist
):
811 prefix
= string_remove_color(infolist_string(infolist
, 'prefix'), '')
812 message
= string_remove_color(infolist_string(infolist
, 'message'), '')
813 date
= infolist_time(infolist
, 'date')
814 return '%s\t%s\t%s' %(date
, prefix
, message
)
816 get_line
= make_get_line_funcion()
818 infolist
= weechat
.infolist_get('buffer_lines', buffer, '')
820 # like with grep_file() if we need the last few matching lines, we move the cursor to
821 # the end and search backwards
822 infolist_next
= weechat
.infolist_prev
823 infolist_prev
= weechat
.infolist_next
825 infolist_next
= weechat
.infolist_next
826 infolist_prev
= weechat
.infolist_prev
829 # define these locally as it makes the loop run slightly faster
830 append
= lines
.append
831 count_match
= lines
.count_match
832 separator
= lines
.append_separator
835 if check_string(s
, regexp
, hilight
, exact
):
840 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
843 before_context_range
= range(1, before_context
+ 1)
844 before_context_range
.reverse()
846 while infolist_next(infolist
):
847 line
= get_line(infolist
)
848 if line
is None: continue
854 for id in before_context_range
:
855 if not infolist_prev(infolist
):
857 for id in before_context_range
:
858 context_line
= get_line(infolist
)
859 if check(context_line
):
861 del lines
[id - before_context
- 1:]
865 infolist_next(infolist
)
866 count
or append(line
)
870 while id < after_context
+ offset
:
872 if infolist_next(infolist
):
873 context_line
= get_line(infolist
)
874 _context_line
= check(context_line
)
876 context_line
= _context_line
881 # in the main loop infolist_next will start again an cause an infinite loop
883 infolist_next
= lambda x
: 0
885 if limit
and lines
.matches_count
>= limit
:
887 weechat
.infolist_free(infolist
)
893 ### this is our main grep function
894 hook_file_grep
= None
895 def show_matching_lines():
897 Greps buffers in search_in_buffers or files in search_in_files and updates grep buffer with the
900 global pattern
, matchcase
, number
, count
, exact
, hilight
, invert
901 global tail
, head
, after_context
, before_context
902 global search_in_files
, search_in_buffers
, matched_lines
, home_dir
904 matched_lines
= linesDict()
905 #debug('buffers:%s \nlogs:%s' %(search_in_buffers, search_in_files))
909 if search_in_buffers
:
910 regexp
= make_regexp(pattern
, matchcase
)
911 for buffer in search_in_buffers
:
912 buffer_name
= weechat
.buffer_get_string(buffer, 'name')
913 matched_lines
[buffer_name
] = grep_buffer(buffer, head
, tail
, after_context
,
914 before_context
, count
, regexp
, hilight
, exact
, invert
)
918 size_limit
= get_config_int('size_limit', allow_empty_string
=True)
920 if size_limit
or size_limit
== 0:
921 size
= sum(map(get_size
, search_in_files
))
922 if size
> size_limit
* 1024:
924 elif size_limit
== '':
929 regexp
= make_regexp(pattern
, matchcase
)
930 for log
in search_in_files
:
931 log_name
= strip_home(log
)
932 matched_lines
[log_name
] = grep_file(log
, head
, tail
, after_context
, before_context
,
933 count
, regexp
, hilight
, exact
, invert
)
936 # we hook a process so grepping runs in background.
937 #debug('on background')
938 global hook_file_grep
, script_path
, bytecode
939 timeout
= 1000*60*5 # 5 min
941 quotify
= lambda s
: '"%s"' %s
942 files_string
= ', '.join(map(quotify
, search_in_files
))
945 # we keep the file descriptor as a global var so it isn't deleted until next grep
946 tmpFile
= tempfile
.NamedTemporaryFile(prefix
=SCRIPT_NAME
,
947 dir=weechat
.info_get('weechat_dir', ''))
948 cmd
= grep_process_cmd
%dict
(logs
=files_string
, head
=head
, pattern
=pattern
, tail
=tail
,
949 hilight
=hilight
, after_context
=after_context
, before_context
=before_context
,
950 exact
=exact
, matchcase
=matchcase
, home_dir
=home_dir
, script_path
=script_path
,
951 count
=count
, invert
=invert
, bytecode
=bytecode
, filename
=tmpFile
.name
,
952 python
=weechat
.info_get('python2_bin', '') or 'python')
955 hook_file_grep
= weechat
.hook_process(cmd
, timeout
, 'grep_file_callback', tmpFile
.name
)
958 buffer_create("Searching for '%s' in %s worth of data..." %(pattern_tmpl
,
959 human_readable_size(size
)))
963 # defined here for commodity
964 grep_process_cmd
= """%(python)s -%(bytecode)sc '
965 import sys, cPickle, os
966 sys.path.append("%(script_path)s") # add WeeChat script dir so we can import grep
967 from grep import make_regexp, grep_file, strip_home
970 regexp = make_regexp("%(pattern)s", %(matchcase)s)
973 log_name = strip_home(log, "%(home_dir)s")
974 lines = grep_file(log, %(head)s, %(tail)s, %(after_context)s, %(before_context)s,
975 %(count)s, regexp, "%(hilight)s", %(exact)s, %(invert)s)
977 fd = open("%(filename)s", "wb")
978 cPickle.dump(d, fd, -1)
981 print >> sys.stderr, e'
984 grep_stdout
= grep_stderr
= ''
985 def grep_file_callback(filename
, command
, rc
, stdout
, stderr
):
986 global hook_file_grep
, grep_stderr
, grep_stdout
988 #debug("rc: %s\nstderr: %s\nstdout: %s" %(rc, repr(stderr), repr(stdout)))
990 grep_stdout
+= stdout
992 grep_stderr
+= stderr
995 def set_buffer_error():
996 grep_buffer
= buffer_create()
997 title
= weechat
.buffer_get_string(grep_buffer
, 'title')
998 title
= title
+ ' %serror' %color
_title
999 weechat
.buffer_set(grep_buffer
, 'title', title
)
1007 elif path
.exists(filename
):
1011 fd
= open(filename
, 'rb')
1012 d
= cPickle
.load(fd
)
1013 matched_lines
.update(d
)
1015 except Exception, e
:
1023 grep_stdout
= grep_stderr
= ''
1024 hook_file_grep
= None
1025 return WEECHAT_RC_OK
1027 def get_grep_file_status():
1028 global search_in_files
, matched_lines
, time_start
1029 elapsed
= now() - time_start
1030 if len(search_in_files
) == 1:
1031 log
= '%s (%s)' %(strip_home(search_in_files
[0]),
1032 human_readable_size(get_size(search_in_files
[0])))
1034 size
= sum(map(get_size
, search_in_files
))
1035 log
= '%s log files (%s)' %(len(search_in_files
), human_readable_size(size
))
1036 return 'Searching in %s, running for %.4f seconds. Interrupt it with "/grep stop" or "stop"' \
1037 ' in grep buffer.' %(log
, elapsed
)
1040 def buffer_update():
1041 """Updates our buffer with new lines."""
1042 global pattern_tmpl
, matched_lines
, pattern
, count
, hilight
, invert
, exact
1045 buffer = buffer_create()
1046 if get_config_boolean('clear_buffer'):
1047 weechat
.buffer_clear(buffer)
1048 matched_lines
.strip_separator() # remove first and last separators of each list
1049 len_total_lines
= len(matched_lines
)
1050 max_lines
= get_config_int('max_lines')
1051 if not count
and len_total_lines
> max_lines
:
1052 weechat
.buffer_clear(buffer)
1054 def _make_summary(log
, lines
, note
):
1055 return '%s matches "%s%s%s"%s in %s%s%s%s' \
1056 %(lines
.matches_count
, color_summary
, pattern_tmpl
, color_info
,
1057 invert
and ' (inverted)' or '',
1058 color_summary
, log
, color_reset
, note
)
1061 make_summary
= lambda log
, lines
: _make_summary(log
, lines
, ' (not shown)')
1063 def make_summary(log
, lines
):
1064 if lines
.stripped_lines
:
1066 note
= ' (last %s lines shown)' %len(lines
)
1068 note
= ' (not shown)'
1071 return _make_summary(log
, lines
, note
)
1073 global weechat_format
1075 # we don't want colors if there's match highlighting
1076 format_line
= lambda s
: '%s %s %s' %split
_line
(s
)
1079 global nick_dict
, weechat_format
1080 date
, nick
, msg
= split_line(s
)
1083 nick
= nick_dict
[nick
]
1086 nick_c
= color_nick(nick
)
1087 nick_dict
[nick
] = nick_c
1089 return '%s%s %s%s %s' %(color_date
, date
, nick
, color_reset
, msg
)
1095 print_line('Search for "%s%s%s"%s in %s%s%s.' %(color_summary
, pattern_tmpl
, color_info
,
1096 invert
and ' (inverted)' or '', color_summary
, matched_lines
, color_reset
),
1098 # print last <max_lines> lines
1099 if matched_lines
.get_matches_count():
1101 # with count we sort by matches lines instead of just lines.
1102 matched_lines_items
= matched_lines
.items_count()
1104 matched_lines_items
= matched_lines
.items()
1106 matched_lines
.get_last_lines(max_lines
)
1107 for log
, lines
in matched_lines_items
:
1108 if lines
.matches_count
:
1112 weechat_format
= True
1117 if line
== linesList
._sep
:
1119 prnt(buffer, context_sep
)
1123 error("Found garbage in log '%s', maybe it's corrupted" %log
)
1124 line
= line
.replace('\x00', '')
1125 prnt_date_tags(buffer, 0, 'no_highlight', format_line(line
))
1128 if count
or get_config_boolean('show_summary'):
1129 summary
= make_summary(log
, lines
)
1130 print_line(summary
, buffer)
1133 if not count
and lines
:
1136 print_line('No matches found.', buffer)
1142 time_total
= time_end
- time_start
1143 # percent of the total time used for grepping
1144 time_grep_pct
= (time_grep
- time_start
)/time_total
*100
1145 #debug('time: %.4f seconds (%.2f%%)' %(time_total, time_grep_pct))
1146 if not count
and len_total_lines
> max_lines
:
1147 note
= ' (last %s lines shown)' %len(matched_lines
)
1150 title
= "'q': close buffer | Search in %s%s%s %s matches%s | pattern \"%s%s%s\"%s %s | %.4f seconds (%.2f%%)" \
1151 %(color_title
, matched_lines
, color_reset
, matched_lines
.get_matches_count(), note
,
1152 color_title
, pattern_tmpl
, color_reset
, invert
and ' (inverted)' or '', format_options(),
1153 time_total
, time_grep_pct
)
1154 weechat
.buffer_set(buffer, 'title', title
)
1156 if get_config_boolean('go_to_buffer'):
1157 weechat
.buffer_set(buffer, 'display', '1')
1159 # free matched_lines so it can be removed from memory
1163 """Splits log's line 's' in 3 parts, date, nick and msg."""
1164 global weechat_format
1165 if weechat_format
and s
.count('\t') >= 2:
1166 date
, nick
, msg
= s
.split('\t', 2) # date, nick, message
1168 # looks like log isn't in weechat's format
1169 weechat_format
= False # incoming lines won't be formatted
1170 date
, nick
, msg
= '', '', s
1173 msg
= msg
.replace('\t', ' ')
1174 return date
, nick
, msg
1176 def print_line(s
, buffer=None, display
=False):
1177 """Prints 's' in script's buffer as 'script_nick'. For displaying search summaries."""
1179 buffer = buffer_create()
1180 say('%s%s' %(color_info
, s
), buffer)
1181 if display
and get_config_boolean('go_to_buffer'):
1182 weechat
.buffer_set(buffer, 'display', '1')
1184 def format_options():
1185 global matchcase
, number
, count
, exact
, hilight
, invert
1186 global tail
, head
, after_context
, before_context
1188 append
= options
.append
1189 insert
= options
.insert
1191 for i
, flag
in enumerate((count
, hilight
, matchcase
, exact
, invert
)):
1196 n
= get_config_int('default_tail_head')
1210 if before_context
and after_context
and (before_context
== after_context
):
1212 append(before_context
)
1216 append(before_context
)
1219 append(after_context
)
1221 s
= ''.join(map(str, options
)).strip()
1222 if s
and s
[0] != '-':
1226 def buffer_create(title
=None):
1227 """Returns our buffer pointer, creates and cleans the buffer if needed."""
1228 buffer = weechat
.buffer_search('python', SCRIPT_NAME
)
1230 buffer = weechat
.buffer_new(SCRIPT_NAME
, 'buffer_input', '', '', '')
1231 weechat
.buffer_set(buffer, 'time_for_each_line', '0')
1232 weechat
.buffer_set(buffer, 'nicklist', '0')
1233 weechat
.buffer_set(buffer, 'title', title
or 'grep output buffer')
1234 weechat
.buffer_set(buffer, 'localvar_set_no_log', '1')
1236 weechat
.buffer_set(buffer, 'title', title
)
1239 def buffer_input(data
, buffer, input_data
):
1240 """Repeats last search with 'input_data' as regexp."""
1242 cmd_grep_stop(buffer, input_data
)
1244 return WEECHAT_RC_OK
1245 if input_data
in ('q', 'Q'):
1246 weechat
.buffer_close(buffer)
1247 return weechat
.WEECHAT_RC_OK
1249 global search_in_buffers
, search_in_files
1252 if pattern
and (search_in_files
or search_in_buffers
):
1253 # check if the buffer pointers are still valid
1254 for pointer
in search_in_buffers
:
1255 infolist
= weechat
.infolist_get('buffer', pointer
, '')
1257 del search_in_buffers
[search_in_buffers
.index(pointer
)]
1258 weechat
.infolist_free(infolist
)
1260 cmd_grep_parsing(input_data
)
1261 except Exception, e
:
1262 error('Argument error, %s' %e, buffer=buffer)
1263 return WEECHAT_RC_OK
1265 show_matching_lines()
1266 except Exception, e
:
1269 error("There isn't any previous search to repeat.", buffer=buffer)
1270 return WEECHAT_RC_OK
1274 """Resets global vars."""
1275 global home_dir
, cache_dir
, nick_dict
1276 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1277 global tail
, head
, after_context
, before_context
1279 head
= tail
= after_context
= before_context
= invert
= False
1280 matchcase
= count
= exact
= False
1281 pattern_tmpl
= pattern
= number
= None
1282 home_dir
= get_home()
1283 cache_dir
= {} # for avoid walking the dir tree more than once per command
1284 nick_dict
= {} # nick cache for don't calculate nick color every time
1286 def cmd_grep_parsing(args
):
1287 """Parses args for /grep and grep input buffer."""
1288 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1289 global tail
, head
, after_context
, before_context
1290 global log_name
, buffer_name
, only_buffers
, all
1291 opts
, args
= getopt
.gnu_getopt(args
.split(), 'cmHeahtivn:bA:B:C:o', ['count', 'matchcase', 'hilight',
1292 'exact', 'all', 'head', 'tail', 'number=', 'buffer', 'after-context=', 'before-context=',
1293 'context=', 'invert', 'only-match'])
1294 #debug(opts, 'opts: '); debug(args, 'args: ')
1296 if args
[0] == 'log':
1298 log_name
= args
.pop(0)
1299 elif args
[0] == 'buffer':
1301 buffer_name
= args
.pop(0)
1303 def tmplReplacer(match
):
1304 """This function will replace templates with regexps"""
1305 s
= match
.groups()[0]
1306 tmpl_args
= s
.split()
1307 tmpl_key
, _
, tmpl_args
= s
.partition(' ')
1309 template
= templates
[tmpl_key
]
1310 if callable(template
):
1311 r
= template(tmpl_args
)
1313 error("Template %s returned empty string "\
1314 "(WeeChat doesn't have enough data)." %t
)
1321 args
= ' '.join(args
) # join pattern for keep spaces
1324 pattern
= _tmplRe
.sub(tmplReplacer
, args
)
1325 debug('Using regexp: %s', pattern
)
1327 raise Exception, 'No pattern for grep the logs.'
1329 def positive_number(opt
, val
):
1340 raise Exception, "argument for %s must be a positive integer." %opt
1342 for opt
, val
in opts
:
1343 opt
= opt
.strip('-')
1344 if opt
in ('c', 'count'):
1346 elif opt
in ('m', 'matchcase'):
1347 matchcase
= not matchcase
1348 elif opt
in ('H', 'hilight'):
1349 # hilight must be always a string!
1353 hilight
= '%s,%s' %(color_hilight
, color_reset
)
1354 # we pass the colors in the variable itself because check_string() must not use
1355 # weechat's module when applying the colors (this is for grep in a hooked process)
1356 elif opt
in ('e', 'exact', 'o', 'only-match'):
1359 elif opt
in ('a', 'all'):
1361 elif opt
in ('h', 'head'):
1364 elif opt
in ('t', 'tail'):
1367 elif opt
in ('b', 'buffer'):
1369 elif opt
in ('n', 'number'):
1370 number
= positive_number(opt
, val
)
1371 elif opt
in ('C', 'context'):
1372 n
= positive_number(opt
, val
)
1375 elif opt
in ('A', 'after-context'):
1376 after_context
= positive_number(opt
, val
)
1377 elif opt
in ('B', 'before-context'):
1378 before_context
= positive_number(opt
, val
)
1379 elif opt
in ('i', 'v', 'invert'):
1383 if number
is not None:
1392 n
= get_config_int('default_tail_head')
1398 def cmd_grep_stop(buffer, args
):
1399 global hook_file_grep
, pattern
, matched_lines
, tmpFile
1402 weechat
.unhook(hook_file_grep
)
1403 hook_file_grep
= None
1404 s
= 'Search for \'%s\' stopped.' %pattern
1406 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
1408 weechat
.buffer_set(grep_buffer
, 'title', s
)
1412 say(get_grep_file_status(), buffer)
1415 def cmd_grep(data
, buffer, args
):
1416 """Search in buffers and logs."""
1417 global pattern
, matchcase
, head
, tail
, number
, count
, exact
, hilight
1419 cmd_grep_stop(buffer, args
)
1421 return WEECHAT_RC_OK
1424 weechat
.command('', '/help %s' %SCRIPT_COMMAND
)
1425 return WEECHAT_RC_OK
1428 global log_name
, buffer_name
, only_buffers
, all
1429 log_name
= buffer_name
= ''
1430 only_buffers
= all
= False
1434 cmd_grep_parsing(args
)
1435 except Exception, e
:
1436 error('Argument error, %s' %e)
1437 return WEECHAT_RC_OK
1440 log_file
= search_buffer
= None
1442 log_file
= get_file_by_pattern(log_name
, all
)
1444 error("Couldn't find any log for %s. Try /logs" %log_name
)
1445 return WEECHAT_RC_OK
1447 search_buffer
= get_all_buffers()
1449 search_buffer
= get_buffer_by_name(buffer_name
)
1450 if not search_buffer
:
1451 # there's no buffer, try in the logs
1452 log_file
= get_file_by_name(buffer_name
)
1454 error("Logs or buffer for '%s' not found." %buffer_name
)
1455 return WEECHAT_RC_OK
1457 search_buffer
= [search_buffer
]
1459 search_buffer
= [buffer]
1462 global search_in_files
, search_in_buffers
1463 search_in_files
= []
1464 search_in_buffers
= []
1466 search_in_files
= log_file
1467 elif not only_buffers
:
1468 #debug(search_buffer)
1469 for pointer
in search_buffer
:
1470 log
= get_file_by_buffer(pointer
)
1471 #debug('buffer %s log %s' %(pointer, log))
1473 search_in_files
.append(log
)
1475 search_in_buffers
.append(pointer
)
1477 search_in_buffers
= search_buffer
1481 show_matching_lines()
1482 except Exception, e
:
1484 return WEECHAT_RC_OK
1486 def cmd_logs(data
, buffer, args
):
1487 """List files in Weechat's log dir."""
1490 sort_by_size
= False
1494 opts
, args
= getopt
.gnu_getopt(args
.split(), 's', ['size'])
1497 for opt
, var
in opts
:
1498 opt
= opt
.strip('-')
1499 if opt
in ('size', 's'):
1501 except Exception, e
:
1502 error('Argument error, %s' %e)
1503 return WEECHAT_RC_OK
1505 # is there's a filter, filter_excludes should be False
1506 file_list
= dir_list(home_dir
, filter, filter_excludes
=not filter)
1508 file_list
.sort(key
=get_size
)
1512 file_sizes
= map(lambda x
: human_readable_size(get_size(x
)), file_list
)
1513 # calculate column lenght
1518 column_len
= len(bigest
) + 3
1522 buffer = buffer_create()
1523 if get_config_boolean('clear_buffer'):
1524 weechat
.buffer_clear(buffer)
1525 file_list
= zip(file_list
, file_sizes
)
1526 msg
= 'Found %s logs.' %len(file_list
)
1528 print_line(msg
, buffer, display
=True)
1529 for file, size
in file_list
:
1530 separator
= column_len
and '.'*(column_len
- len(file))
1531 prnt(buffer, '%s %s %s' %(strip_home(file), separator
, size
))
1533 print_line(msg
, buffer)
1534 return WEECHAT_RC_OK
1538 def completion_log_files(data
, completion_item
, buffer, completion
):
1539 #debug('completion: %s' %', '.join((data, completion_item, buffer, completion)))
1542 completion_list_add
= weechat
.hook_completion_list_add
1543 WEECHAT_LIST_POS_END
= weechat
.WEECHAT_LIST_POS_END
1544 for log
in dir_list(home_dir
):
1545 completion_list_add(completion
, log
[l
:], 0, WEECHAT_LIST_POS_END
)
1546 return WEECHAT_RC_OK
1548 def completion_grep_args(data
, completion_item
, buffer, completion
):
1549 for arg
in ('count', 'all', 'matchcase', 'hilight', 'exact', 'head', 'tail', 'number', 'buffer',
1550 'after-context', 'before-context', 'context', 'invert', 'only-match'):
1551 weechat
.hook_completion_list_add(completion
, '--' + arg
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1552 for tmpl
in templates
:
1553 weechat
.hook_completion_list_add(completion
, '%{' + tmpl
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1554 return WEECHAT_RC_OK
1558 # template placeholder
1559 _tmplRe
= re
.compile(r
'%\{(\w+.*?)(?:\}|$)')
1560 # will match 999.999.999.999 but I don't care
1561 ipAddress
= r
'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
1562 domain
= r
'[\w-]{2,}(?:\.[\w-]{2,})*\.[a-z]{2,}'
1563 url
= r
'\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?' % (domain
, ipAddress
)
1565 def make_url_regexp(args
):
1566 #debug('make url: %s', args)
1568 words
= r
'(?:%s)' %'|'.join(map(re
.escape
, args
.split()))
1569 return r
'(?:\w+://|www\.)[^\s]*%s[^\s]*(?:/[^\])>\s]*)?' %words
1573 def make_simple_regexp(pattern
):
1586 'url': make_url_regexp
,
1587 'escape': lambda s
: re
.escape(s
),
1588 'simple': make_simple_regexp
,
1593 def delete_bytecode():
1595 bytecode
= path
.join(script_path
, SCRIPT_NAME
+ '.pyc')
1596 if path
.isfile(bytecode
):
1598 return WEECHAT_RC_OK
1600 if __name__
== '__main__' and import_ok
and \
1601 weechat
.register(SCRIPT_NAME
, SCRIPT_AUTHOR
, SCRIPT_VERSION
, SCRIPT_LICENSE
, \
1602 SCRIPT_DESC
, 'delete_bytecode', ''):
1603 home_dir
= get_home()
1605 # for import ourselves
1607 script_path
= path
.dirname(__file__
)
1608 sys
.path
.append(script_path
)
1611 # check python version
1614 if sys
.version_info
> (2, 6):
1620 weechat
.hook_command(SCRIPT_COMMAND
, cmd_grep
.__doc
__,
1621 "[log <file> | buffer <name> | stop] [-a|--all] [-b|--buffer] [-c|--count] [-m|--matchcase] "
1622 "[-H|--hilight] [-o|--only-match] [-i|-v|--invert] [(-h|--head)|(-t|--tail) [-n|--number <n>]] "
1623 "[-A|--after-context <n>] [-B|--before-context <n>] [-C|--context <n> ] <expression>",
1626 log <file>: Search in one log that matches <file> in the logger path.
1627 Use '*' and '?' as wildcards.
1628 buffer <name>: Search in buffer <name>, if there's no buffer with <name> it will
1629 try to search for a log file.
1630 stop: Stops a currently running search.
1631 -a --all: Search in all open buffers.
1632 If used with 'log <file>' search in all logs that matches <file>.
1633 -b --buffer: Search only in buffers, not in file logs.
1634 -c --count: Just count the number of matched lines instead of showing them.
1635 -m --matchcase: Don't do case insensible search.
1636 -H --hilight: Colour exact matches in output buffer.
1637 -o --only-match: Print only the matching part of the line (unique matches).
1638 -v -i --invert: Print lines that don't match the regular expression.
1639 -t --tail: Print the last 10 matching lines.
1640 -h --head: Print the first 10 matching lines.
1641 -n --number <n>: Overrides default number of lines for --tail or --head.
1642 -A --after-context <n>: Shows <n> lines of trailing context after matching lines.
1643 -B --before-context <n>: Shows <n> lines of leading context before matching lines.
1644 -C --context <n>: Same as using both --after-context and --before-context simultaneously.
1645 <expression>: Expression to search.
1648 Input line accepts most arguments of /grep, it'll repeat last search using the new
1649 arguments provided. You can't search in different logs from the buffer's input.
1650 Boolean arguments like --count, --tail, --head, --hilight, ... are toggleable
1652 Python regular expression syntax:
1653 See http://docs.python.org/lib/re-syntax.html
1656 %{url [text]}: Matches anything like an url, or an url with text.
1657 %{ip}: Matches anything that looks like an ip.
1658 %{domain}: Matches anything like a domain.
1659 %{escape text}: Escapes text in pattern.
1660 %{simple pattern}: Converts a pattern with '*' and '?' wildcards into a regexp.
1663 Search for urls with the word 'weechat' said by 'nick'
1664 /grep nick\\t.*%{url weechat}
1665 Search for '*.*' string
1668 # completion template
1669 "buffer %(buffers_names) %(grep_arguments)|%*"
1670 "||log %(grep_log_files) %(grep_arguments)|%*"
1672 "||%(grep_arguments)|%*",
1674 weechat
.hook_command('logs', cmd_logs
.__doc
__, "[-s|--size] [<filter>]",
1675 "-s --size: Sort logs by size.\n"
1676 " <filter>: Only show logs that match <filter>. Use '*' and '?' as wildcards.", '--size', 'cmd_logs', '')
1678 weechat
.hook_completion('grep_log_files', "list of log files",
1679 'completion_log_files', '')
1680 weechat
.hook_completion('grep_arguments', "list of arguments",
1681 'completion_grep_args', '')
1684 for opt
, val
in settings
.iteritems():
1685 if not weechat
.config_is_set_plugin(opt
):
1686 weechat
.config_set_plugin(opt
, val
)
1689 color_date
= weechat
.color('brown')
1690 color_info
= weechat
.color('cyan')
1691 color_hilight
= weechat
.color('lightred')
1692 color_reset
= weechat
.color('reset')
1693 color_title
= weechat
.color('yellow')
1694 color_summary
= weechat
.color('lightcyan')
1695 color_delimiter
= weechat
.color('chat_delimiters')
1696 color_script_nick
= weechat
.color('chat_nick')
1699 script_nick
= '%s[%s%s%s]%s' %(color_delimiter
, color_script_nick
, SCRIPT_NAME
, color_delimiter
,
1701 script_nick_nocolor
= '[%s]' %SCRIPT_NAME
1702 # paragraph separator when using context options
1703 context_sep
= '%s\t%s--' %(script_nick
, color_info
)
1705 # -------------------------------------------------------------------------
1708 if weechat
.config_get_plugin('debug'):
1710 # custom debug module I use, allows me to inspect script's objects.
1712 debug
= pybuffer
.debugBuffer(globals(), '%s_debug' % SCRIPT_NAME
)
1714 def debug(s
, *args
):
1715 if not isinstance(s
, basestring
):
1719 prnt('', '%s\t%s' %(script_nick
, s
))
1724 # vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=100: