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.timeout_secs:
57 # Timeout (in seconds) for background grepping.
59 # * plugins.var.python.grep.default_tail_head:
60 # Config option for define default number of lines returned when using --head or --tail options.
61 # Can be overriden in the command with --number option.
65 # * try to figure out why hook_process chokes in long outputs (using a tempfile as a
67 # * possibly add option for defining time intervals
72 # 2018-04-10, Sébastien Helleu <flashcode@flashtux.org>
73 # version 0.8.1: fix infolist_time for WeeChat >= 2.2 (WeeChat returns a long
74 # integer instead of a string)
76 # 2017-09-20, mickael9
78 # * use weechat 1.5+ api for background processing (old method was unsafe and buggy)
79 # * add timeout_secs setting (was previously hardcoded to 5 mins)
81 # 2017-07-23, Sébastien Helleu <flashcode@flashtux.org>
82 # version 0.7.8: fix modulo by zero when nick is empty string
84 # 2016-06-23, mickael9
85 # version 0.7.7: fix get_home function
88 # version 0.7.6: fix a typo
92 # '~' is now expaned to the home directory in the log file path so
93 # paths like '~/logs/' should work.
96 # version 0.7.4: make q work to quit grep buffer (requested by: gb)
98 # 2014-03-29, Felix Eckhofer <felix@tribut.de>
99 # version 0.7.3: fix typo
102 # version 0.7.2: bug fixes
106 # * use TempFile so temporal files are guaranteed to be deleted.
107 # * enable Archlinux workaround.
112 # * using --only-match shows only unique strings.
113 # * fixed bug that inverted -B -A switches when used with -t
116 # version 0.6.8: by xt <xt@bash.no>
117 # * supress highlights when printing in grep buffer
120 # version 0.6.7: by xt <xt@bash.no>
121 # * better temporary file:
122 # use tempfile.mkstemp. to create a temp file in log dir,
123 # makes it safer with regards to write permission and multi user
126 # version 0.6.6: bug fixes
127 # * use WEECHAT_LIST_POS_END in log file completion, makes completion faster
128 # * disable bytecode if using python 2.6
129 # * use single quotes in command string
130 # * fix bug that could change buffer's title when using /grep stop
133 # version 0.6.5: disable bytecode is a 2.6 feature, instead, resort to delete the bytecode manually
136 # version 0.6.4: bug fix
137 # version 0.6.3: added options --invert --only-match (replaces --exact, which is still available
138 # but removed from help)
139 # * use new 'irc_nick_color' info
140 # * don't generate bytecode when spawning a new process
141 # * show active options in buffer title
144 # version 0.6.2: removed 2.6-ish code
145 # version 0.6.1: fixed bug when grepping in grep's buffer
148 # version 0.6.0: implemented grep in background
149 # * improved context lines presentation.
150 # * grepping for big (or many) log files runs in a weechat_process.
151 # * added /grep stop.
152 # * added 'size_limit' option
153 # * fixed a infolist leak when grepping buffers
154 # * added 'default_tail_head' option
155 # * results are sort by line count
156 # * don't die if log is corrupted (has NULL chars in it)
157 # * changed presentation of /logs
158 # * log path completion doesn't suck anymore
159 # * removed all tabs, because I learned how to configure Vim so that spaces aren't annoying
160 # anymore. This was the script's original policy.
163 # version 0.5.5: rename script to 'grep.py' (FlashCode <flashcode@flashtux.org>).
166 # version 0.5.4.1: fix index error when using --after/before-context options.
169 # version 0.5.4: new features
170 # * added --after-context and --before-context options.
171 # * added --context as a shortcut for using both -A -B options.
174 # version 0.5.3: improvements for long grep output
175 # * grep buffer input accepts the same flags as /grep for repeat a search with different
177 # * tweaks in grep's output.
178 # * max_lines option added for limit grep's output.
179 # * code in update_buffer() optimized.
180 # * time stats in buffer title.
181 # * added go_to_buffer config option.
182 # * added --buffer for search only in buffers.
186 # version 0.5.2: made it python-2.4.x compliant
189 # version 0.5.1: some refactoring, show_summary option added.
192 # version 0.5: rewritten from xt's grep.py
193 # * fixed searching in non weechat logs, for cases like, if you're
194 # switching from irssi and rename and copy your irssi logs to %h/logs
195 # * fixed "timestamp rainbow" when you /grep in grep's buffer
196 # * allow to search in other buffers other than current or in logs
197 # of currently closed buffers with cmd 'buffer'
198 # * allow to search in any log file in %h/logs with cmd 'log'
199 # * added --count for return the number of matched lines
200 # * added --matchcase for case sensible search
201 # * added --hilight for color matches
202 # * added --head and --tail options, and --number
203 # * added command /logs for list files in %h/logs
204 # * added config option for clear the buffer before a search
205 # * added config option for filter logs we don't want to grep
206 # * added the posibility to repeat last search with another regexp by writing
207 # it in grep's buffer
208 # * changed spaces for tabs in the code, which is my preference
213 import sys
, getopt
, time
, os
, re
216 import cPickle
as pickle
222 from weechat
import WEECHAT_RC_OK
, prnt
, prnt_date_tags
228 SCRIPT_AUTHOR
= "Elián Hanisch <lambdae2@gmail.com>"
229 SCRIPT_VERSION
= "0.8.1"
230 SCRIPT_LICENSE
= "GPL3"
231 SCRIPT_DESC
= "Search in buffers and logs"
232 SCRIPT_COMMAND
= "grep"
234 ### Default Settings ###
236 'clear_buffer' : 'off',
238 'go_to_buffer' : 'on',
239 'max_lines' : '4000',
240 'show_summary' : 'on',
241 'size_limit' : '2048',
242 'default_tail_head' : '10',
243 'timeout_secs' : '300',
246 ### Class definitions ###
247 class linesDict(dict):
249 Class for handling matched lines in more than one buffer.
250 linesDict[buffer_name] = matched_lines_list
252 def __setitem__(self
, key
, value
):
253 assert isinstance(value
, list)
255 dict.__setitem
__(self
, key
, value
)
257 dict.__getitem
__(self
, key
).extend(value
)
259 def get_matches_count(self
):
260 """Return the sum of total matches stored."""
261 if dict.__len
__(self
):
262 return sum(map(lambda L
: L
.matches_count
, self
.itervalues()))
267 """Return the sum of total lines stored."""
268 if dict.__len
__(self
):
269 return sum(map(len, self
.itervalues()))
274 """Returns buffer count or buffer name if there's just one stored."""
277 return self
.keys()[0]
284 """Returns a list of items sorted by line count."""
285 items
= dict.items(self
)
286 items
.sort(key
=lambda i
: len(i
[1]))
289 def items_count(self
):
290 """Returns a list of items sorted by match count."""
291 items
= dict.items(self
)
292 items
.sort(key
=lambda i
: i
[1].matches_count
)
295 def strip_separator(self
):
296 for L
in self
.itervalues():
299 def get_last_lines(self
, n
):
300 total_lines
= len(self
)
301 #debug('total: %s n: %s' %(total_lines, n))
305 for k
, v
in reversed(self
.items()):
310 v
.stripped_lines
= l
-n
316 class linesList(list):
317 """Class for list of matches, since sometimes I need to add lines that aren't matches, I need an
318 independent counter."""
320 def __init__(self
, *args
):
321 list.__init
__(self
, *args
)
322 self
.matches_count
= 0
323 self
.stripped_lines
= 0
325 def append(self
, item
):
326 """Append lines, can be a string or a list with strings."""
327 if isinstance(item
, str):
328 list.append(self
, item
)
332 def append_separator(self
):
333 """adds a separator into the list, makes sure it doen't add two together."""
335 if (self
and self
[-1] != s
) or not self
:
343 def count_match(self
, item
=None):
344 if item
is None or isinstance(item
, str):
345 self
.matches_count
+= 1
347 self
.matches_count
+= len(item
)
349 def strip_separator(self
):
350 """removes separators if there are first or/and last in the list."""
358 ### Misc functions ###
362 return os
.stat(f
).st_size
366 sizeDict
= {0:'b', 1:'KiB', 2:'MiB', 3:'GiB', 4:'TiB'}
367 def human_readable_size(size
):
372 return '%.2f %s' %(size
, sizeDict
.get(power
, ''))
374 def color_nick(nick
):
375 """Returns coloured nick, with coloured mode if any."""
376 if not nick
: return ''
377 wcolor
= weechat
.color
378 config_string
= lambda s
: weechat
.config_string(weechat
.config_get(s
))
379 config_int
= lambda s
: weechat
.config_integer(weechat
.config_get(s
))
381 prefix
= config_string('irc.look.nick_prefix')
382 suffix
= config_string('irc.look.nick_suffix')
383 prefix_c
= suffix_c
= wcolor(config_string('weechat.color.chat_delimiters'))
384 if nick
[0] == prefix
:
387 prefix
= prefix_c
= ''
388 if nick
[-1] == suffix
:
390 suffix
= wcolor(color_delimiter
) + suffix
392 suffix
= suffix_c
= ''
396 mode
, nick
= nick
[0], nick
[1:]
397 mode_color
= wcolor(config_string('weechat.color.nicklist_prefix%d' \
398 %(modes
.find(mode
) + 1)))
400 mode
= mode_color
= ''
404 nick_color
= weechat
.info_get('irc_nick_color', nick
)
406 # probably we're in WeeChat 0.3.0
407 #debug('no irc_nick_color')
408 color_nicks_number
= config_int('weechat.look.color_nicks_number')
409 idx
= (sum(map(ord, nick
))%color
_nicks
_number
) + 1
410 nick_color
= wcolor(config_string('weechat.color.chat_nick_color%02d' %idx))
411 return ''.join((prefix_c
, prefix
, mode_color
, mode
, nick_color
, nick
, suffix_c
, suffix
))
413 ### Config and value validation ###
414 boolDict
= {'on':True, 'off':False}
415 def get_config_boolean(config
):
416 value
= weechat
.config_get_plugin(config
)
418 return boolDict
[value
]
420 default
= settings
[config
]
421 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
422 error("'%s' is invalid, allowed: 'on', 'off'" %value
)
423 return boolDict
[default
]
425 def get_config_int(config
, allow_empty_string
=False):
426 value
= weechat
.config_get_plugin(config
)
430 if value
== '' and allow_empty_string
:
432 default
= settings
[config
]
433 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
434 error("'%s' is not a number." %value
)
437 def get_config_log_filter():
438 filter = weechat
.config_get_plugin('log_filter')
440 return filter.split(',')
445 home
= weechat
.config_string(weechat
.config_get('logger.file.path'))
446 home
= home
.replace('%h', weechat
.info_get('weechat_dir', ''))
447 home
= path
.abspath(path
.expanduser(home
))
450 def strip_home(s
, dir=''):
451 """Strips home dir from the begging of the log path, this makes them sorter."""
461 script_nick
= SCRIPT_NAME
462 def error(s
, buffer=''):
464 prnt(buffer, '%s%s %s' %(weechat
.prefix('error'), script_nick
, s
))
465 if weechat
.config_get_plugin('debug'):
467 if traceback
.sys
.exc_type
:
468 trace
= traceback
.format_exc()
471 def say(s
, buffer=''):
473 prnt_date_tags(buffer, 0, 'no_highlight', '%s\t%s' %(script_nick
, s
))
477 ### Log files and buffers ###
478 cache_dir
= {} # note: don't remove, needed for completion if the script was loaded recently
479 def dir_list(dir, filter_list
=(), filter_excludes
=True, include_dir
=False):
480 """Returns a list of files in 'dir' and its subdirs."""
483 from fnmatch
import fnmatch
484 #debug('dir_list: listing in %s' %dir)
485 key
= (dir, include_dir
)
487 return cache_dir
[key
]
491 filter_list
= filter_list
or get_config_log_filter()
495 file = file[dir_len
:] # pattern shouldn't match home dir
496 for pattern
in filter_list
:
497 if fnmatch(file, pattern
):
498 return filter_excludes
499 return not filter_excludes
501 filter = lambda f
: not filter_excludes
504 extend
= file_list
.extend
507 for basedir
, subdirs
, files
in walk(dir):
509 # subdirs = map(lambda s : join(s, ''), subdirs)
510 # files.extend(subdirs)
511 files_path
= map(lambda f
: join(basedir
, f
), files
)
512 files_path
= [ file for file in files_path
if not filter(file) ]
516 cache_dir
[key
] = file_list
517 #debug('dir_list: got %s' %str(file_list))
520 def get_file_by_pattern(pattern
, all
=False):
521 """Returns the first log whose path matches 'pattern',
522 if all is True returns all logs that matches."""
523 if not pattern
: return []
524 #debug('get_file_by_filename: searching for %s.' %pattern)
525 # do envvar expandsion and check file
526 file = path
.expanduser(pattern
)
527 file = path
.expandvars(file)
528 if path
.isfile(file):
530 # lets see if there's a matching log
532 file = path
.join(home_dir
, pattern
)
533 if path
.isfile(file):
536 from fnmatch
import fnmatch
538 file_list
= dir_list(home_dir
)
540 for log
in file_list
:
542 if fnmatch(basename
, pattern
):
544 #debug('get_file_by_filename: got %s.' %file)
550 def get_file_by_buffer(buffer):
551 """Given buffer pointer, finds log's path or returns None."""
552 #debug('get_file_by_buffer: searching for %s' %buffer)
553 infolist
= weechat
.infolist_get('logger_buffer', '', '')
554 if not infolist
: return
556 while weechat
.infolist_next(infolist
):
557 pointer
= weechat
.infolist_pointer(infolist
, 'buffer')
558 if pointer
== buffer:
559 file = weechat
.infolist_string(infolist
, 'log_filename')
560 if weechat
.infolist_integer(infolist
, 'log_enabled'):
561 #debug('get_file_by_buffer: got %s' %file)
564 # debug('get_file_by_buffer: got %s but log not enabled' %file)
566 #debug('infolist gets freed')
567 weechat
.infolist_free(infolist
)
569 def get_file_by_name(buffer_name
):
570 """Given a buffer name, returns its log path or None. buffer_name should be in 'server.#channel'
571 or '#channel' format."""
572 #debug('get_file_by_name: searching for %s' %buffer_name)
573 # common mask options
574 config_masks
= ('logger.mask.irc', 'logger.file.mask')
575 # since there's no buffer pointer, we try to replace some local vars in mask, like $channel and
576 # $server, then replace the local vars left with '*', and use it as a mask for get the path with
577 # get_file_by_pattern
578 for config
in config_masks
:
579 mask
= weechat
.config_string(weechat
.config_get(config
))
580 #debug('get_file_by_name: mask: %s' %mask)
582 mask
= mask
.replace('$name', buffer_name
)
583 elif '$channel' in mask
or '$server' in mask
:
584 if '.' in buffer_name
and \
585 '#' not in buffer_name
[:buffer_name
.find('.')]: # the dot isn't part of the channel name
586 # ^ I'm asuming channel starts with #, i'm lazy.
587 server
, channel
= buffer_name
.split('.', 1)
589 server
, channel
= '*', buffer_name
590 if '$channel' in mask
:
591 mask
= mask
.replace('$channel', channel
)
592 if '$server' in mask
:
593 mask
= mask
.replace('$server', server
)
594 # change the unreplaced vars by '*'
595 from string
import letters
597 # vars for time formatting
598 mask
= mask
.replace('%', '$')
600 masks
= mask
.split('$')
601 masks
= map(lambda s
: s
.lstrip(letters
), masks
)
602 mask
= '*'.join(masks
)
605 #debug('get_file_by_name: using mask %s' %mask)
606 file = get_file_by_pattern(mask
)
607 #debug('get_file_by_name: got file %s' %file)
612 def get_buffer_by_name(buffer_name
):
613 """Given a buffer name returns its buffer pointer or None."""
614 #debug('get_buffer_by_name: searching for %s' %buffer_name)
615 pointer
= weechat
.buffer_search('', buffer_name
)
618 infolist
= weechat
.infolist_get('buffer', '', '')
619 while weechat
.infolist_next(infolist
):
620 short_name
= weechat
.infolist_string(infolist
, 'short_name')
621 name
= weechat
.infolist_string(infolist
, 'name')
622 if buffer_name
in (short_name
, name
):
623 #debug('get_buffer_by_name: found %s' %name)
624 pointer
= weechat
.buffer_search('', name
)
627 weechat
.infolist_free(infolist
)
628 #debug('get_buffer_by_name: got %s' %pointer)
631 def get_all_buffers():
632 """Returns list with pointers of all open buffers."""
634 infolist
= weechat
.infolist_get('buffer', '', '')
635 while weechat
.infolist_next(infolist
):
636 buffers
.append(weechat
.infolist_pointer(infolist
, 'pointer'))
637 weechat
.infolist_free(infolist
)
638 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
639 if grep_buffer
and grep_buffer
in buffers
:
640 # remove it from list
641 del buffers
[buffers
.index(grep_buffer
)]
645 def make_regexp(pattern
, matchcase
=False):
646 """Returns a compiled regexp."""
647 if pattern
in ('.', '.*', '.?', '.+'):
648 # because I don't need to use a regexp if we're going to match all lines
650 # matching takes a lot more time if pattern starts or ends with .* and it isn't needed.
651 if pattern
[:2] == '.*':
652 pattern
= pattern
[2:]
653 if pattern
[-2:] == '.*':
654 pattern
= pattern
[:-2]
657 regexp
= re
.compile(pattern
, re
.IGNORECASE
)
659 regexp
= re
.compile(pattern
)
661 raise Exception, 'Bad pattern, %s' %e
664 def check_string(s
, regexp
, hilight
='', exact
=False):
665 """Checks 's' with a regexp and returns it if is a match."""
670 matchlist
= regexp
.findall(s
)
672 if isinstance(matchlist
[0], tuple):
673 # join tuples (when there's more than one match group in regexp)
674 return [ ' '.join(t
) for t
in matchlist
]
678 matchlist
= regexp
.findall(s
)
680 if isinstance(matchlist
[0], tuple):
682 matchlist
= [ item
for L
in matchlist
for item
in L
if item
]
683 matchlist
= list(set(matchlist
)) # remove duplicates if any
685 color_hilight
, color_reset
= hilight
.split(',', 1)
687 s
= s
.replace(m
, '%s%s%s' % (color_hilight
, m
, color_reset
))
690 # no need for findall() here
691 elif regexp
.search(s
):
694 def grep_file(file, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
, invert
):
695 """Return a list of lines that match 'regexp' in 'file', if no regexp returns all lines."""
697 tail
= head
= after_context
= before_context
= False
700 before_context
= after_context
= False
704 #debug(' '.join(map(str, (file, head, tail, after_context, before_context))))
707 # define these locally as it makes the loop run slightly faster
708 append
= lines
.append
709 count_match
= lines
.count_match
710 separator
= lines
.append_separator
713 if check_string(s
, regexp
, hilight
, exact
):
718 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
721 file_object
= open(file, 'r')
725 if tail
or before_context
:
726 # for these options, I need to seek in the file, but is slower and uses a good deal of
727 # memory if the log is too big, so we do this *only* for these options.
728 file_lines
= file_object
.readlines()
731 # instead of searching in the whole file and later pick the last few lines, we
732 # reverse the log, search until count reached and reverse it again, that way is a lot
735 # don't invert context switches
736 before_context
, after_context
= after_context
, before_context
739 before_context_range
= range(1, before_context
+ 1)
740 before_context_range
.reverse()
745 while line_idx
< len(file_lines
):
746 line
= file_lines
[line_idx
]
752 for id in before_context_range
:
754 context_line
= file_lines
[line_idx
- id]
755 if check(context_line
):
756 # match in before context, that means we appended these same lines in a
757 # previous match, so we delete them merging both paragraphs
759 del lines
[id - before_context
- 1:]
769 while id < after_context
+ offset
:
772 context_line
= file_lines
[line_idx
+ id]
773 _context_line
= check(context_line
)
776 context_line
= _context_line
# so match is hilighted with --hilight
783 if limit
and lines
.matches_count
>= limit
:
793 for line
in file_object
:
796 count
or append(line
)
800 while id < after_context
+ offset
:
803 context_line
= file_object
.next()
804 _context_line
= check(context_line
)
807 context_line
= _context_line
809 count
or append(context_line
)
810 except StopIteration:
813 if limit
and lines
.matches_count
>= limit
:
819 def grep_buffer(buffer, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
,
821 """Return a list of lines that match 'regexp' in 'buffer', if no regexp returns all lines."""
824 tail
= head
= after_context
= before_context
= False
827 before_context
= after_context
= False
828 #debug(' '.join(map(str, (tail, head, after_context, before_context, count, exact, hilight))))
830 # Using /grep in grep's buffer can lead to some funny effects
831 # We should take measures if that's the case
832 def make_get_line_funcion():
833 """Returns a function for get lines from the infolist, depending if the buffer is grep's or
835 string_remove_color
= weechat
.string_remove_color
836 infolist_string
= weechat
.infolist_string
837 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
838 if grep_buffer
and buffer == grep_buffer
:
839 def function(infolist
):
840 prefix
= infolist_string(infolist
, 'prefix')
841 message
= infolist_string(infolist
, 'message')
842 if prefix
: # only our messages have prefix, ignore it
846 infolist_time
= weechat
.infolist_time
847 def function(infolist
):
848 prefix
= string_remove_color(infolist_string(infolist
, 'prefix'), '')
849 message
= string_remove_color(infolist_string(infolist
, 'message'), '')
850 date
= infolist_time(infolist
, 'date')
851 # since WeeChat 2.2, infolist_time returns a long integer
852 # instead of a string
853 if not isinstance(date
, str):
854 date
= time
.strftime('%F %T', time
.localtime(int(date
)))
855 return '%s\t%s\t%s' %(date
, prefix
, message
)
857 get_line
= make_get_line_funcion()
859 infolist
= weechat
.infolist_get('buffer_lines', buffer, '')
861 # like with grep_file() if we need the last few matching lines, we move the cursor to
862 # the end and search backwards
863 infolist_next
= weechat
.infolist_prev
864 infolist_prev
= weechat
.infolist_next
866 infolist_next
= weechat
.infolist_next
867 infolist_prev
= weechat
.infolist_prev
870 # define these locally as it makes the loop run slightly faster
871 append
= lines
.append
872 count_match
= lines
.count_match
873 separator
= lines
.append_separator
876 if check_string(s
, regexp
, hilight
, exact
):
881 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
884 before_context_range
= range(1, before_context
+ 1)
885 before_context_range
.reverse()
887 while infolist_next(infolist
):
888 line
= get_line(infolist
)
889 if line
is None: continue
895 for id in before_context_range
:
896 if not infolist_prev(infolist
):
898 for id in before_context_range
:
899 context_line
= get_line(infolist
)
900 if check(context_line
):
902 del lines
[id - before_context
- 1:]
906 infolist_next(infolist
)
907 count
or append(line
)
911 while id < after_context
+ offset
:
913 if infolist_next(infolist
):
914 context_line
= get_line(infolist
)
915 _context_line
= check(context_line
)
917 context_line
= _context_line
922 # in the main loop infolist_next will start again an cause an infinite loop
924 infolist_next
= lambda x
: 0
926 if limit
and lines
.matches_count
>= limit
:
928 weechat
.infolist_free(infolist
)
934 ### this is our main grep function
935 hook_file_grep
= None
936 def show_matching_lines():
938 Greps buffers in search_in_buffers or files in search_in_files and updates grep buffer with the
941 global pattern
, matchcase
, number
, count
, exact
, hilight
, invert
942 global tail
, head
, after_context
, before_context
943 global search_in_files
, search_in_buffers
, matched_lines
, home_dir
945 matched_lines
= linesDict()
946 #debug('buffers:%s \nlogs:%s' %(search_in_buffers, search_in_files))
950 if search_in_buffers
:
951 regexp
= make_regexp(pattern
, matchcase
)
952 for buffer in search_in_buffers
:
953 buffer_name
= weechat
.buffer_get_string(buffer, 'name')
954 matched_lines
[buffer_name
] = grep_buffer(buffer, head
, tail
, after_context
,
955 before_context
, count
, regexp
, hilight
, exact
, invert
)
959 size_limit
= get_config_int('size_limit', allow_empty_string
=True)
961 if size_limit
or size_limit
== 0:
962 size
= sum(map(get_size
, search_in_files
))
963 if size
> size_limit
* 1024:
965 elif size_limit
== '':
968 regexp
= make_regexp(pattern
, matchcase
)
970 global grep_options
, log_pairs
971 grep_options
= (head
, tail
, after_context
, before_context
,
972 count
, regexp
, hilight
, exact
, invert
)
974 log_pairs
= [(strip_home(log
), log
) for log
in search_in_files
]
978 for log_name
, log
in log_pairs
:
979 matched_lines
[log_name
] = grep_file(log
, *grep_options
)
982 global hook_file_grep
, grep_stdout
, grep_stderr
, pattern_tmpl
983 grep_stdout
= grep_stderr
= ''
984 hook_file_grep
= weechat
.hook_process(
986 get_config_int('timeout_secs') * 1000,
991 buffer_create("Searching for '%s' in %s worth of data..." % (
993 human_readable_size(size
)
999 def grep_process(*args
):
1002 global grep_options
, log_pairs
1003 for log_name
, log
in log_pairs
:
1004 result
[log_name
] = grep_file(log
, *grep_options
)
1005 except Exception, e
:
1008 return pickle
.dumps(result
)
1010 grep_stdout
= grep_stderr
= ''
1012 def grep_process_cb(data
, command
, return_code
, out
, err
):
1013 global grep_stdout
, grep_stderr
, matched_lines
, hook_file_grep
1018 def set_buffer_error(message
):
1020 grep_buffer
= buffer_create()
1021 title
= weechat
.buffer_get_string(grep_buffer
, 'title')
1022 title
= title
+ ' %serror' % color_title
1023 weechat
.buffer_set(grep_buffer
, 'title', title
)
1025 if return_code
== weechat
.WEECHAT_HOOK_PROCESS_ERROR
:
1026 set_buffer_error("Background grep timed out")
1027 hook_file_grep
= None
1028 return WEECHAT_RC_OK
1030 elif return_code
>= 0:
1031 hook_file_grep
= None
1033 set_buffer_error(grep_stderr
)
1034 return WEECHAT_RC_OK
1037 data
= pickle
.loads(grep_stdout
)
1038 if isinstance(data
, Exception):
1040 matched_lines
.update(data
)
1041 except Exception, e
:
1042 set_buffer_error(repr(e
))
1043 return WEECHAT_RC_OK
1047 return WEECHAT_RC_OK
1049 def get_grep_file_status():
1050 global search_in_files
, matched_lines
, time_start
1051 elapsed
= now() - time_start
1052 if len(search_in_files
) == 1:
1053 log
= '%s (%s)' %(strip_home(search_in_files
[0]),
1054 human_readable_size(get_size(search_in_files
[0])))
1056 size
= sum(map(get_size
, search_in_files
))
1057 log
= '%s log files (%s)' %(len(search_in_files
), human_readable_size(size
))
1058 return 'Searching in %s, running for %.4f seconds. Interrupt it with "/grep stop" or "stop"' \
1059 ' in grep buffer.' %(log
, elapsed
)
1062 def buffer_update():
1063 """Updates our buffer with new lines."""
1064 global pattern_tmpl
, matched_lines
, pattern
, count
, hilight
, invert
, exact
1067 buffer = buffer_create()
1068 if get_config_boolean('clear_buffer'):
1069 weechat
.buffer_clear(buffer)
1070 matched_lines
.strip_separator() # remove first and last separators of each list
1071 len_total_lines
= len(matched_lines
)
1072 max_lines
= get_config_int('max_lines')
1073 if not count
and len_total_lines
> max_lines
:
1074 weechat
.buffer_clear(buffer)
1076 def _make_summary(log
, lines
, note
):
1077 return '%s matches "%s%s%s"%s in %s%s%s%s' \
1078 %(lines
.matches_count
, color_summary
, pattern_tmpl
, color_info
,
1079 invert
and ' (inverted)' or '',
1080 color_summary
, log
, color_reset
, note
)
1083 make_summary
= lambda log
, lines
: _make_summary(log
, lines
, ' (not shown)')
1085 def make_summary(log
, lines
):
1086 if lines
.stripped_lines
:
1088 note
= ' (last %s lines shown)' %len(lines
)
1090 note
= ' (not shown)'
1093 return _make_summary(log
, lines
, note
)
1095 global weechat_format
1097 # we don't want colors if there's match highlighting
1098 format_line
= lambda s
: '%s %s %s' %split
_line
(s
)
1101 global nick_dict
, weechat_format
1102 date
, nick
, msg
= split_line(s
)
1105 nick
= nick_dict
[nick
]
1108 nick_c
= color_nick(nick
)
1109 nick_dict
[nick
] = nick_c
1111 return '%s%s %s%s %s' %(color_date
, date
, nick
, color_reset
, msg
)
1117 print_line('Search for "%s%s%s"%s in %s%s%s.' %(color_summary
, pattern_tmpl
, color_info
,
1118 invert
and ' (inverted)' or '', color_summary
, matched_lines
, color_reset
),
1120 # print last <max_lines> lines
1121 if matched_lines
.get_matches_count():
1123 # with count we sort by matches lines instead of just lines.
1124 matched_lines_items
= matched_lines
.items_count()
1126 matched_lines_items
= matched_lines
.items()
1128 matched_lines
.get_last_lines(max_lines
)
1129 for log
, lines
in matched_lines_items
:
1130 if lines
.matches_count
:
1134 weechat_format
= True
1139 if line
== linesList
._sep
:
1141 prnt(buffer, context_sep
)
1145 error("Found garbage in log '%s', maybe it's corrupted" %log
)
1146 line
= line
.replace('\x00', '')
1147 prnt_date_tags(buffer, 0, 'no_highlight', format_line(line
))
1150 if count
or get_config_boolean('show_summary'):
1151 summary
= make_summary(log
, lines
)
1152 print_line(summary
, buffer)
1155 if not count
and lines
:
1158 print_line('No matches found.', buffer)
1164 time_total
= time_end
- time_start
1165 # percent of the total time used for grepping
1166 time_grep_pct
= (time_grep
- time_start
)/time_total
*100
1167 #debug('time: %.4f seconds (%.2f%%)' %(time_total, time_grep_pct))
1168 if not count
and len_total_lines
> max_lines
:
1169 note
= ' (last %s lines shown)' %len(matched_lines
)
1172 title
= "'q': close buffer | Search in %s%s%s %s matches%s | pattern \"%s%s%s\"%s %s | %.4f seconds (%.2f%%)" \
1173 %(color_title
, matched_lines
, color_reset
, matched_lines
.get_matches_count(), note
,
1174 color_title
, pattern_tmpl
, color_reset
, invert
and ' (inverted)' or '', format_options(),
1175 time_total
, time_grep_pct
)
1176 weechat
.buffer_set(buffer, 'title', title
)
1178 if get_config_boolean('go_to_buffer'):
1179 weechat
.buffer_set(buffer, 'display', '1')
1181 # free matched_lines so it can be removed from memory
1185 """Splits log's line 's' in 3 parts, date, nick and msg."""
1186 global weechat_format
1187 if weechat_format
and s
.count('\t') >= 2:
1188 date
, nick
, msg
= s
.split('\t', 2) # date, nick, message
1190 # looks like log isn't in weechat's format
1191 weechat_format
= False # incoming lines won't be formatted
1192 date
, nick
, msg
= '', '', s
1195 msg
= msg
.replace('\t', ' ')
1196 return date
, nick
, msg
1198 def print_line(s
, buffer=None, display
=False):
1199 """Prints 's' in script's buffer as 'script_nick'. For displaying search summaries."""
1201 buffer = buffer_create()
1202 say('%s%s' %(color_info
, s
), buffer)
1203 if display
and get_config_boolean('go_to_buffer'):
1204 weechat
.buffer_set(buffer, 'display', '1')
1206 def format_options():
1207 global matchcase
, number
, count
, exact
, hilight
, invert
1208 global tail
, head
, after_context
, before_context
1210 append
= options
.append
1211 insert
= options
.insert
1213 for i
, flag
in enumerate((count
, hilight
, matchcase
, exact
, invert
)):
1218 n
= get_config_int('default_tail_head')
1232 if before_context
and after_context
and (before_context
== after_context
):
1234 append(before_context
)
1238 append(before_context
)
1241 append(after_context
)
1243 s
= ''.join(map(str, options
)).strip()
1244 if s
and s
[0] != '-':
1248 def buffer_create(title
=None):
1249 """Returns our buffer pointer, creates and cleans the buffer if needed."""
1250 buffer = weechat
.buffer_search('python', SCRIPT_NAME
)
1252 buffer = weechat
.buffer_new(SCRIPT_NAME
, 'buffer_input', '', '', '')
1253 weechat
.buffer_set(buffer, 'time_for_each_line', '0')
1254 weechat
.buffer_set(buffer, 'nicklist', '0')
1255 weechat
.buffer_set(buffer, 'title', title
or 'grep output buffer')
1256 weechat
.buffer_set(buffer, 'localvar_set_no_log', '1')
1258 weechat
.buffer_set(buffer, 'title', title
)
1261 def buffer_input(data
, buffer, input_data
):
1262 """Repeats last search with 'input_data' as regexp."""
1264 cmd_grep_stop(buffer, input_data
)
1266 return WEECHAT_RC_OK
1267 if input_data
in ('q', 'Q'):
1268 weechat
.buffer_close(buffer)
1269 return weechat
.WEECHAT_RC_OK
1271 global search_in_buffers
, search_in_files
1274 if pattern
and (search_in_files
or search_in_buffers
):
1275 # check if the buffer pointers are still valid
1276 for pointer
in search_in_buffers
:
1277 infolist
= weechat
.infolist_get('buffer', pointer
, '')
1279 del search_in_buffers
[search_in_buffers
.index(pointer
)]
1280 weechat
.infolist_free(infolist
)
1282 cmd_grep_parsing(input_data
)
1283 except Exception, e
:
1284 error('Argument error, %s' %e, buffer=buffer)
1285 return WEECHAT_RC_OK
1287 show_matching_lines()
1288 except Exception, e
:
1291 error("There isn't any previous search to repeat.", buffer=buffer)
1292 return WEECHAT_RC_OK
1296 """Resets global vars."""
1297 global home_dir
, cache_dir
, nick_dict
1298 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1299 global tail
, head
, after_context
, before_context
1301 head
= tail
= after_context
= before_context
= invert
= False
1302 matchcase
= count
= exact
= False
1303 pattern_tmpl
= pattern
= number
= None
1304 home_dir
= get_home()
1305 cache_dir
= {} # for avoid walking the dir tree more than once per command
1306 nick_dict
= {} # nick cache for don't calculate nick color every time
1308 def cmd_grep_parsing(args
):
1309 """Parses args for /grep and grep input buffer."""
1310 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1311 global tail
, head
, after_context
, before_context
1312 global log_name
, buffer_name
, only_buffers
, all
1313 opts
, args
= getopt
.gnu_getopt(args
.split(), 'cmHeahtivn:bA:B:C:o', ['count', 'matchcase', 'hilight',
1314 'exact', 'all', 'head', 'tail', 'number=', 'buffer', 'after-context=', 'before-context=',
1315 'context=', 'invert', 'only-match'])
1316 #debug(opts, 'opts: '); debug(args, 'args: ')
1318 if args
[0] == 'log':
1320 log_name
= args
.pop(0)
1321 elif args
[0] == 'buffer':
1323 buffer_name
= args
.pop(0)
1325 def tmplReplacer(match
):
1326 """This function will replace templates with regexps"""
1327 s
= match
.groups()[0]
1328 tmpl_args
= s
.split()
1329 tmpl_key
, _
, tmpl_args
= s
.partition(' ')
1331 template
= templates
[tmpl_key
]
1332 if callable(template
):
1333 r
= template(tmpl_args
)
1335 error("Template %s returned empty string "\
1336 "(WeeChat doesn't have enough data)." %t
)
1343 args
= ' '.join(args
) # join pattern for keep spaces
1346 pattern
= _tmplRe
.sub(tmplReplacer
, args
)
1347 debug('Using regexp: %s', pattern
)
1349 raise Exception, 'No pattern for grep the logs.'
1351 def positive_number(opt
, val
):
1362 raise Exception, "argument for %s must be a positive integer." %opt
1364 for opt
, val
in opts
:
1365 opt
= opt
.strip('-')
1366 if opt
in ('c', 'count'):
1368 elif opt
in ('m', 'matchcase'):
1369 matchcase
= not matchcase
1370 elif opt
in ('H', 'hilight'):
1371 # hilight must be always a string!
1375 hilight
= '%s,%s' %(color_hilight
, color_reset
)
1376 # we pass the colors in the variable itself because check_string() must not use
1377 # weechat's module when applying the colors (this is for grep in a hooked process)
1378 elif opt
in ('e', 'exact', 'o', 'only-match'):
1381 elif opt
in ('a', 'all'):
1383 elif opt
in ('h', 'head'):
1386 elif opt
in ('t', 'tail'):
1389 elif opt
in ('b', 'buffer'):
1391 elif opt
in ('n', 'number'):
1392 number
= positive_number(opt
, val
)
1393 elif opt
in ('C', 'context'):
1394 n
= positive_number(opt
, val
)
1397 elif opt
in ('A', 'after-context'):
1398 after_context
= positive_number(opt
, val
)
1399 elif opt
in ('B', 'before-context'):
1400 before_context
= positive_number(opt
, val
)
1401 elif opt
in ('i', 'v', 'invert'):
1405 if number
is not None:
1414 n
= get_config_int('default_tail_head')
1420 def cmd_grep_stop(buffer, args
):
1421 global hook_file_grep
, pattern
, matched_lines
1424 weechat
.unhook(hook_file_grep
)
1425 hook_file_grep
= None
1427 s
= 'Search for \'%s\' stopped.' % pattern
1429 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
1431 weechat
.buffer_set(grep_buffer
, 'title', s
)
1434 say(get_grep_file_status(), buffer)
1437 def cmd_grep(data
, buffer, args
):
1438 """Search in buffers and logs."""
1439 global pattern
, matchcase
, head
, tail
, number
, count
, exact
, hilight
1441 cmd_grep_stop(buffer, args
)
1443 return WEECHAT_RC_OK
1446 weechat
.command('', '/help %s' %SCRIPT_COMMAND
)
1447 return WEECHAT_RC_OK
1450 global log_name
, buffer_name
, only_buffers
, all
1451 log_name
= buffer_name
= ''
1452 only_buffers
= all
= False
1456 cmd_grep_parsing(args
)
1457 except Exception, e
:
1458 error('Argument error, %s' %e)
1459 return WEECHAT_RC_OK
1462 log_file
= search_buffer
= None
1464 log_file
= get_file_by_pattern(log_name
, all
)
1466 error("Couldn't find any log for %s. Try /logs" %log_name
)
1467 return WEECHAT_RC_OK
1469 search_buffer
= get_all_buffers()
1471 search_buffer
= get_buffer_by_name(buffer_name
)
1472 if not search_buffer
:
1473 # there's no buffer, try in the logs
1474 log_file
= get_file_by_name(buffer_name
)
1476 error("Logs or buffer for '%s' not found." %buffer_name
)
1477 return WEECHAT_RC_OK
1479 search_buffer
= [search_buffer
]
1481 search_buffer
= [buffer]
1484 global search_in_files
, search_in_buffers
1485 search_in_files
= []
1486 search_in_buffers
= []
1488 search_in_files
= log_file
1489 elif not only_buffers
:
1490 #debug(search_buffer)
1491 for pointer
in search_buffer
:
1492 log
= get_file_by_buffer(pointer
)
1493 #debug('buffer %s log %s' %(pointer, log))
1495 search_in_files
.append(log
)
1497 search_in_buffers
.append(pointer
)
1499 search_in_buffers
= search_buffer
1503 show_matching_lines()
1504 except Exception, e
:
1506 return WEECHAT_RC_OK
1508 def cmd_logs(data
, buffer, args
):
1509 """List files in Weechat's log dir."""
1512 sort_by_size
= False
1516 opts
, args
= getopt
.gnu_getopt(args
.split(), 's', ['size'])
1519 for opt
, var
in opts
:
1520 opt
= opt
.strip('-')
1521 if opt
in ('size', 's'):
1523 except Exception, e
:
1524 error('Argument error, %s' %e)
1525 return WEECHAT_RC_OK
1527 # is there's a filter, filter_excludes should be False
1528 file_list
= dir_list(home_dir
, filter, filter_excludes
=not filter)
1530 file_list
.sort(key
=get_size
)
1534 file_sizes
= map(lambda x
: human_readable_size(get_size(x
)), file_list
)
1535 # calculate column lenght
1540 column_len
= len(bigest
) + 3
1544 buffer = buffer_create()
1545 if get_config_boolean('clear_buffer'):
1546 weechat
.buffer_clear(buffer)
1547 file_list
= zip(file_list
, file_sizes
)
1548 msg
= 'Found %s logs.' %len(file_list
)
1550 print_line(msg
, buffer, display
=True)
1551 for file, size
in file_list
:
1552 separator
= column_len
and '.'*(column_len
- len(file))
1553 prnt(buffer, '%s %s %s' %(strip_home(file), separator
, size
))
1555 print_line(msg
, buffer)
1556 return WEECHAT_RC_OK
1560 def completion_log_files(data
, completion_item
, buffer, completion
):
1561 #debug('completion: %s' %', '.join((data, completion_item, buffer, completion)))
1564 completion_list_add
= weechat
.hook_completion_list_add
1565 WEECHAT_LIST_POS_END
= weechat
.WEECHAT_LIST_POS_END
1566 for log
in dir_list(home_dir
):
1567 completion_list_add(completion
, log
[l
:], 0, WEECHAT_LIST_POS_END
)
1568 return WEECHAT_RC_OK
1570 def completion_grep_args(data
, completion_item
, buffer, completion
):
1571 for arg
in ('count', 'all', 'matchcase', 'hilight', 'exact', 'head', 'tail', 'number', 'buffer',
1572 'after-context', 'before-context', 'context', 'invert', 'only-match'):
1573 weechat
.hook_completion_list_add(completion
, '--' + arg
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1574 for tmpl
in templates
:
1575 weechat
.hook_completion_list_add(completion
, '%{' + tmpl
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1576 return WEECHAT_RC_OK
1580 # template placeholder
1581 _tmplRe
= re
.compile(r
'%\{(\w+.*?)(?:\}|$)')
1582 # will match 999.999.999.999 but I don't care
1583 ipAddress
= r
'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
1584 domain
= r
'[\w-]{2,}(?:\.[\w-]{2,})*\.[a-z]{2,}'
1585 url
= r
'\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?' % (domain
, ipAddress
)
1587 def make_url_regexp(args
):
1588 #debug('make url: %s', args)
1590 words
= r
'(?:%s)' %'|'.join(map(re
.escape
, args
.split()))
1591 return r
'(?:\w+://|www\.)[^\s]*%s[^\s]*(?:/[^\])>\s]*)?' %words
1595 def make_simple_regexp(pattern
):
1608 'url': make_url_regexp
,
1609 'escape': lambda s
: re
.escape(s
),
1610 'simple': make_simple_regexp
,
1615 def delete_bytecode():
1617 bytecode
= path
.join(script_path
, SCRIPT_NAME
+ '.pyc')
1618 if path
.isfile(bytecode
):
1620 return WEECHAT_RC_OK
1622 if __name__
== '__main__' and import_ok
and \
1623 weechat
.register(SCRIPT_NAME
, SCRIPT_AUTHOR
, SCRIPT_VERSION
, SCRIPT_LICENSE
, \
1624 SCRIPT_DESC
, 'delete_bytecode', ''):
1625 home_dir
= get_home()
1627 # for import ourselves
1629 script_path
= path
.dirname(__file__
)
1630 sys
.path
.append(script_path
)
1633 # check python version
1636 if sys
.version_info
> (2, 6):
1642 weechat
.hook_command(SCRIPT_COMMAND
, cmd_grep
.__doc
__,
1643 "[log <file> | buffer <name> | stop] [-a|--all] [-b|--buffer] [-c|--count] [-m|--matchcase] "
1644 "[-H|--hilight] [-o|--only-match] [-i|-v|--invert] [(-h|--head)|(-t|--tail) [-n|--number <n>]] "
1645 "[-A|--after-context <n>] [-B|--before-context <n>] [-C|--context <n> ] <expression>",
1648 log <file>: Search in one log that matches <file> in the logger path.
1649 Use '*' and '?' as wildcards.
1650 buffer <name>: Search in buffer <name>, if there's no buffer with <name> it will
1651 try to search for a log file.
1652 stop: Stops a currently running search.
1653 -a --all: Search in all open buffers.
1654 If used with 'log <file>' search in all logs that matches <file>.
1655 -b --buffer: Search only in buffers, not in file logs.
1656 -c --count: Just count the number of matched lines instead of showing them.
1657 -m --matchcase: Don't do case insensitive search.
1658 -H --hilight: Colour exact matches in output buffer.
1659 -o --only-match: Print only the matching part of the line (unique matches).
1660 -v -i --invert: Print lines that don't match the regular expression.
1661 -t --tail: Print the last 10 matching lines.
1662 -h --head: Print the first 10 matching lines.
1663 -n --number <n>: Overrides default number of lines for --tail or --head.
1664 -A --after-context <n>: Shows <n> lines of trailing context after matching lines.
1665 -B --before-context <n>: Shows <n> lines of leading context before matching lines.
1666 -C --context <n>: Same as using both --after-context and --before-context simultaneously.
1667 <expression>: Expression to search.
1670 Input line accepts most arguments of /grep, it'll repeat last search using the new
1671 arguments provided. You can't search in different logs from the buffer's input.
1672 Boolean arguments like --count, --tail, --head, --hilight, ... are toggleable
1674 Python regular expression syntax:
1675 See http://docs.python.org/lib/re-syntax.html
1678 %{url [text]}: Matches anything like an url, or an url with text.
1679 %{ip}: Matches anything that looks like an ip.
1680 %{domain}: Matches anything like a domain.
1681 %{escape text}: Escapes text in pattern.
1682 %{simple pattern}: Converts a pattern with '*' and '?' wildcards into a regexp.
1685 Search for urls with the word 'weechat' said by 'nick'
1686 /grep nick\\t.*%{url weechat}
1687 Search for '*.*' string
1690 # completion template
1691 "buffer %(buffers_names) %(grep_arguments)|%*"
1692 "||log %(grep_log_files) %(grep_arguments)|%*"
1694 "||%(grep_arguments)|%*",
1696 weechat
.hook_command('logs', cmd_logs
.__doc
__, "[-s|--size] [<filter>]",
1697 "-s --size: Sort logs by size.\n"
1698 " <filter>: Only show logs that match <filter>. Use '*' and '?' as wildcards.", '--size', 'cmd_logs', '')
1700 weechat
.hook_completion('grep_log_files', "list of log files",
1701 'completion_log_files', '')
1702 weechat
.hook_completion('grep_arguments', "list of arguments",
1703 'completion_grep_args', '')
1706 for opt
, val
in settings
.iteritems():
1707 if not weechat
.config_is_set_plugin(opt
):
1708 weechat
.config_set_plugin(opt
, val
)
1711 color_date
= weechat
.color('brown')
1712 color_info
= weechat
.color('cyan')
1713 color_hilight
= weechat
.color('lightred')
1714 color_reset
= weechat
.color('reset')
1715 color_title
= weechat
.color('yellow')
1716 color_summary
= weechat
.color('lightcyan')
1717 color_delimiter
= weechat
.color('chat_delimiters')
1718 color_script_nick
= weechat
.color('chat_nick')
1721 script_nick
= '%s[%s%s%s]%s' %(color_delimiter
, color_script_nick
, SCRIPT_NAME
, color_delimiter
,
1723 script_nick_nocolor
= '[%s]' %SCRIPT_NAME
1724 # paragraph separator when using context options
1725 context_sep
= '%s\t%s--' %(script_nick
, color_info
)
1727 # -------------------------------------------------------------------------
1730 if weechat
.config_get_plugin('debug'):
1732 # custom debug module I use, allows me to inspect script's objects.
1734 debug
= pybuffer
.debugBuffer(globals(), '%s_debug' % SCRIPT_NAME
)
1736 def debug(s
, *args
):
1737 if not isinstance(s
, basestring
):
1741 prnt('', '%s\t%s' %(script_nick
, s
))
1746 # vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=100: