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 # 2019-06-30, dabbill <dabbill@gmail.com>
73 # and Sébastien Helleu <flashcode@flashtux.org>
74 # version 0.8.2: make script compatible with Python 3
76 # 2018-04-10, Sébastien Helleu <flashcode@flashtux.org>
77 # version 0.8.1: fix infolist_time for WeeChat >= 2.2 (WeeChat returns a long
78 # integer instead of a string)
80 # 2017-09-20, mickael9
82 # * use weechat 1.5+ api for background processing (old method was unsafe and buggy)
83 # * add timeout_secs setting (was previously hardcoded to 5 mins)
85 # 2017-07-23, Sébastien Helleu <flashcode@flashtux.org>
86 # version 0.7.8: fix modulo by zero when nick is empty string
88 # 2016-06-23, mickael9
89 # version 0.7.7: fix get_home function
92 # version 0.7.6: fix a typo
96 # '~' is now expaned to the home directory in the log file path so
97 # paths like '~/logs/' should work.
100 # version 0.7.4: make q work to quit grep buffer (requested by: gb)
102 # 2014-03-29, Felix Eckhofer <felix@tribut.de>
103 # version 0.7.3: fix typo
106 # version 0.7.2: bug fixes
110 # * use TempFile so temporal files are guaranteed to be deleted.
111 # * enable Archlinux workaround.
116 # * using --only-match shows only unique strings.
117 # * fixed bug that inverted -B -A switches when used with -t
120 # version 0.6.8: by xt <xt@bash.no>
121 # * supress highlights when printing in grep buffer
124 # version 0.6.7: by xt <xt@bash.no>
125 # * better temporary file:
126 # use tempfile.mkstemp. to create a temp file in log dir,
127 # makes it safer with regards to write permission and multi user
130 # version 0.6.6: bug fixes
131 # * use WEECHAT_LIST_POS_END in log file completion, makes completion faster
132 # * disable bytecode if using python 2.6
133 # * use single quotes in command string
134 # * fix bug that could change buffer's title when using /grep stop
137 # version 0.6.5: disable bytecode is a 2.6 feature, instead, resort to delete the bytecode manually
140 # version 0.6.4: bug fix
141 # version 0.6.3: added options --invert --only-match (replaces --exact, which is still available
142 # but removed from help)
143 # * use new 'irc_nick_color' info
144 # * don't generate bytecode when spawning a new process
145 # * show active options in buffer title
148 # version 0.6.2: removed 2.6-ish code
149 # version 0.6.1: fixed bug when grepping in grep's buffer
152 # version 0.6.0: implemented grep in background
153 # * improved context lines presentation.
154 # * grepping for big (or many) log files runs in a weechat_process.
155 # * added /grep stop.
156 # * added 'size_limit' option
157 # * fixed a infolist leak when grepping buffers
158 # * added 'default_tail_head' option
159 # * results are sort by line count
160 # * don't die if log is corrupted (has NULL chars in it)
161 # * changed presentation of /logs
162 # * log path completion doesn't suck anymore
163 # * removed all tabs, because I learned how to configure Vim so that spaces aren't annoying
164 # anymore. This was the script's original policy.
167 # version 0.5.5: rename script to 'grep.py' (FlashCode <flashcode@flashtux.org>).
170 # version 0.5.4.1: fix index error when using --after/before-context options.
173 # version 0.5.4: new features
174 # * added --after-context and --before-context options.
175 # * added --context as a shortcut for using both -A -B options.
178 # version 0.5.3: improvements for long grep output
179 # * grep buffer input accepts the same flags as /grep for repeat a search with different
181 # * tweaks in grep's output.
182 # * max_lines option added for limit grep's output.
183 # * code in update_buffer() optimized.
184 # * time stats in buffer title.
185 # * added go_to_buffer config option.
186 # * added --buffer for search only in buffers.
190 # version 0.5.2: made it python-2.4.x compliant
193 # version 0.5.1: some refactoring, show_summary option added.
196 # version 0.5: rewritten from xt's grep.py
197 # * fixed searching in non weechat logs, for cases like, if you're
198 # switching from irssi and rename and copy your irssi logs to %h/logs
199 # * fixed "timestamp rainbow" when you /grep in grep's buffer
200 # * allow to search in other buffers other than current or in logs
201 # of currently closed buffers with cmd 'buffer'
202 # * allow to search in any log file in %h/logs with cmd 'log'
203 # * added --count for return the number of matched lines
204 # * added --matchcase for case sensible search
205 # * added --hilight for color matches
206 # * added --head and --tail options, and --number
207 # * added command /logs for list files in %h/logs
208 # * added config option for clear the buffer before a search
209 # * added config option for filter logs we don't want to grep
210 # * added the posibility to repeat last search with another regexp by writing
211 # it in grep's buffer
212 # * changed spaces for tabs in the code, which is my preference
217 import sys
, getopt
, time
, os
, re
220 import cPickle
as pickle
226 from weechat
import WEECHAT_RC_OK
, prnt
, prnt_date_tags
232 SCRIPT_AUTHOR
= "Elián Hanisch <lambdae2@gmail.com>"
233 SCRIPT_VERSION
= "0.8.2"
234 SCRIPT_LICENSE
= "GPL3"
235 SCRIPT_DESC
= "Search in buffers and logs"
236 SCRIPT_COMMAND
= "grep"
238 ### Default Settings ###
240 'clear_buffer' : 'off',
242 'go_to_buffer' : 'on',
243 'max_lines' : '4000',
244 'show_summary' : 'on',
245 'size_limit' : '2048',
246 'default_tail_head' : '10',
247 'timeout_secs' : '300',
250 ### Class definitions ###
251 class linesDict(dict):
253 Class for handling matched lines in more than one buffer.
254 linesDict[buffer_name] = matched_lines_list
256 def __setitem__(self
, key
, value
):
257 assert isinstance(value
, list)
259 dict.__setitem
__(self
, key
, value
)
261 dict.__getitem
__(self
, key
).extend(value
)
263 def get_matches_count(self
):
264 """Return the sum of total matches stored."""
265 if dict.__len
__(self
):
266 return sum(map(lambda L
: L
.matches_count
, self
.values()))
271 """Return the sum of total lines stored."""
272 if dict.__len
__(self
):
273 return sum(map(len, self
.values()))
278 """Returns buffer count or buffer name if there's just one stored."""
281 return list(self
.keys())[0]
288 """Returns a list of items sorted by line count."""
289 items
= list(dict.items(self
))
290 items
.sort(key
=lambda i
: len(i
[1]))
293 def items_count(self
):
294 """Returns a list of items sorted by match count."""
295 items
= list(dict.items(self
))
296 items
.sort(key
=lambda i
: i
[1].matches_count
)
299 def strip_separator(self
):
300 for L
in self
.values():
303 def get_last_lines(self
, n
):
304 total_lines
= len(self
)
305 #debug('total: %s n: %s' %(total_lines, n))
309 for k
, v
in reversed(list(self
.items())):
314 v
.stripped_lines
= l
-n
320 class linesList(list):
321 """Class for list of matches, since sometimes I need to add lines that aren't matches, I need an
322 independent counter."""
324 def __init__(self
, *args
):
325 list.__init
__(self
, *args
)
326 self
.matches_count
= 0
327 self
.stripped_lines
= 0
329 def append(self
, item
):
330 """Append lines, can be a string or a list with strings."""
331 if isinstance(item
, str):
332 list.append(self
, item
)
336 def append_separator(self
):
337 """adds a separator into the list, makes sure it doen't add two together."""
339 if (self
and self
[-1] != s
) or not self
:
347 def count_match(self
, item
=None):
348 if item
is None or isinstance(item
, str):
349 self
.matches_count
+= 1
351 self
.matches_count
+= len(item
)
353 def strip_separator(self
):
354 """removes separators if there are first or/and last in the list."""
362 ### Misc functions ###
366 return os
.stat(f
).st_size
370 sizeDict
= {0:'b', 1:'KiB', 2:'MiB', 3:'GiB', 4:'TiB'}
371 def human_readable_size(size
):
376 return '%.2f %s' %(size
, sizeDict
.get(power
, ''))
378 def color_nick(nick
):
379 """Returns coloured nick, with coloured mode if any."""
380 if not nick
: return ''
381 wcolor
= weechat
.color
382 config_string
= lambda s
: weechat
.config_string(weechat
.config_get(s
))
383 config_int
= lambda s
: weechat
.config_integer(weechat
.config_get(s
))
385 prefix
= config_string('irc.look.nick_prefix')
386 suffix
= config_string('irc.look.nick_suffix')
387 prefix_c
= suffix_c
= wcolor(config_string('weechat.color.chat_delimiters'))
388 if nick
[0] == prefix
:
391 prefix
= prefix_c
= ''
392 if nick
[-1] == suffix
:
394 suffix
= wcolor(color_delimiter
) + suffix
396 suffix
= suffix_c
= ''
400 mode
, nick
= nick
[0], nick
[1:]
401 mode_color
= wcolor(config_string('weechat.color.nicklist_prefix%d' \
402 %(modes
.find(mode
) + 1)))
404 mode
= mode_color
= ''
408 nick_color
= weechat
.info_get('irc_nick_color', nick
)
410 # probably we're in WeeChat 0.3.0
411 #debug('no irc_nick_color')
412 color_nicks_number
= config_int('weechat.look.color_nicks_number')
413 idx
= (sum(map(ord, nick
))%color
_nicks
_number
) + 1
414 nick_color
= wcolor(config_string('weechat.color.chat_nick_color%02d' %idx))
415 return ''.join((prefix_c
, prefix
, mode_color
, mode
, nick_color
, nick
, suffix_c
, suffix
))
417 ### Config and value validation ###
418 boolDict
= {'on':True, 'off':False}
419 def get_config_boolean(config
):
420 value
= weechat
.config_get_plugin(config
)
422 return boolDict
[value
]
424 default
= settings
[config
]
425 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
426 error("'%s' is invalid, allowed: 'on', 'off'" %value
)
427 return boolDict
[default
]
429 def get_config_int(config
, allow_empty_string
=False):
430 value
= weechat
.config_get_plugin(config
)
434 if value
== '' and allow_empty_string
:
436 default
= settings
[config
]
437 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
438 error("'%s' is not a number." %value
)
441 def get_config_log_filter():
442 filter = weechat
.config_get_plugin('log_filter')
444 return filter.split(',')
449 home
= weechat
.config_string(weechat
.config_get('logger.file.path'))
450 home
= home
.replace('%h', weechat
.info_get('weechat_dir', ''))
451 home
= path
.abspath(path
.expanduser(home
))
454 def strip_home(s
, dir=''):
455 """Strips home dir from the begging of the log path, this makes them sorter."""
465 script_nick
= SCRIPT_NAME
466 def error(s
, buffer=''):
468 prnt(buffer, '%s%s %s' %(weechat
.prefix('error'), script_nick
, s
))
469 if weechat
.config_get_plugin('debug'):
471 if traceback
.sys
.exc_type
:
472 trace
= traceback
.format_exc()
475 def say(s
, buffer=''):
477 prnt_date_tags(buffer, 0, 'no_highlight', '%s\t%s' %(script_nick
, s
))
481 ### Log files and buffers ###
482 cache_dir
= {} # note: don't remove, needed for completion if the script was loaded recently
483 def dir_list(dir, filter_list
=(), filter_excludes
=True, include_dir
=False):
484 """Returns a list of files in 'dir' and its subdirs."""
487 from fnmatch
import fnmatch
488 #debug('dir_list: listing in %s' %dir)
489 key
= (dir, include_dir
)
491 return cache_dir
[key
]
495 filter_list
= filter_list
or get_config_log_filter()
499 file = file[dir_len
:] # pattern shouldn't match home dir
500 for pattern
in filter_list
:
501 if fnmatch(file, pattern
):
502 return filter_excludes
503 return not filter_excludes
505 filter = lambda f
: not filter_excludes
508 extend
= file_list
.extend
511 for basedir
, subdirs
, files
in walk(dir):
513 # subdirs = map(lambda s : join(s, ''), subdirs)
514 # files.extend(subdirs)
515 files_path
= map(lambda f
: join(basedir
, f
), files
)
516 files_path
= [ file for file in files_path
if not filter(file) ]
520 cache_dir
[key
] = file_list
521 #debug('dir_list: got %s' %str(file_list))
524 def get_file_by_pattern(pattern
, all
=False):
525 """Returns the first log whose path matches 'pattern',
526 if all is True returns all logs that matches."""
527 if not pattern
: return []
528 #debug('get_file_by_filename: searching for %s.' %pattern)
529 # do envvar expandsion and check file
530 file = path
.expanduser(pattern
)
531 file = path
.expandvars(file)
532 if path
.isfile(file):
534 # lets see if there's a matching log
536 file = path
.join(home_dir
, pattern
)
537 if path
.isfile(file):
540 from fnmatch
import fnmatch
542 file_list
= dir_list(home_dir
)
544 for log
in file_list
:
546 if fnmatch(basename
, pattern
):
548 #debug('get_file_by_filename: got %s.' %file)
554 def get_file_by_buffer(buffer):
555 """Given buffer pointer, finds log's path or returns None."""
556 #debug('get_file_by_buffer: searching for %s' %buffer)
557 infolist
= weechat
.infolist_get('logger_buffer', '', '')
558 if not infolist
: return
560 while weechat
.infolist_next(infolist
):
561 pointer
= weechat
.infolist_pointer(infolist
, 'buffer')
562 if pointer
== buffer:
563 file = weechat
.infolist_string(infolist
, 'log_filename')
564 if weechat
.infolist_integer(infolist
, 'log_enabled'):
565 #debug('get_file_by_buffer: got %s' %file)
568 # debug('get_file_by_buffer: got %s but log not enabled' %file)
570 #debug('infolist gets freed')
571 weechat
.infolist_free(infolist
)
573 def get_file_by_name(buffer_name
):
574 """Given a buffer name, returns its log path or None. buffer_name should be in 'server.#channel'
575 or '#channel' format."""
576 #debug('get_file_by_name: searching for %s' %buffer_name)
577 # common mask options
578 config_masks
= ('logger.mask.irc', 'logger.file.mask')
579 # since there's no buffer pointer, we try to replace some local vars in mask, like $channel and
580 # $server, then replace the local vars left with '*', and use it as a mask for get the path with
581 # get_file_by_pattern
582 for config
in config_masks
:
583 mask
= weechat
.config_string(weechat
.config_get(config
))
584 #debug('get_file_by_name: mask: %s' %mask)
586 mask
= mask
.replace('$name', buffer_name
)
587 elif '$channel' in mask
or '$server' in mask
:
588 if '.' in buffer_name
and \
589 '#' not in buffer_name
[:buffer_name
.find('.')]: # the dot isn't part of the channel name
590 # ^ I'm asuming channel starts with #, i'm lazy.
591 server
, channel
= buffer_name
.split('.', 1)
593 server
, channel
= '*', buffer_name
594 if '$channel' in mask
:
595 mask
= mask
.replace('$channel', channel
)
596 if '$server' in mask
:
597 mask
= mask
.replace('$server', server
)
598 # change the unreplaced vars by '*'
599 from string
import letters
601 # vars for time formatting
602 mask
= mask
.replace('%', '$')
604 masks
= mask
.split('$')
605 masks
= map(lambda s
: s
.lstrip(letters
), masks
)
606 mask
= '*'.join(masks
)
609 #debug('get_file_by_name: using mask %s' %mask)
610 file = get_file_by_pattern(mask
)
611 #debug('get_file_by_name: got file %s' %file)
616 def get_buffer_by_name(buffer_name
):
617 """Given a buffer name returns its buffer pointer or None."""
618 #debug('get_buffer_by_name: searching for %s' %buffer_name)
619 pointer
= weechat
.buffer_search('', buffer_name
)
622 infolist
= weechat
.infolist_get('buffer', '', '')
623 while weechat
.infolist_next(infolist
):
624 short_name
= weechat
.infolist_string(infolist
, 'short_name')
625 name
= weechat
.infolist_string(infolist
, 'name')
626 if buffer_name
in (short_name
, name
):
627 #debug('get_buffer_by_name: found %s' %name)
628 pointer
= weechat
.buffer_search('', name
)
631 weechat
.infolist_free(infolist
)
632 #debug('get_buffer_by_name: got %s' %pointer)
635 def get_all_buffers():
636 """Returns list with pointers of all open buffers."""
638 infolist
= weechat
.infolist_get('buffer', '', '')
639 while weechat
.infolist_next(infolist
):
640 buffers
.append(weechat
.infolist_pointer(infolist
, 'pointer'))
641 weechat
.infolist_free(infolist
)
642 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
643 if grep_buffer
and grep_buffer
in buffers
:
644 # remove it from list
645 del buffers
[buffers
.index(grep_buffer
)]
649 def make_regexp(pattern
, matchcase
=False):
650 """Returns a compiled regexp."""
651 if pattern
in ('.', '.*', '.?', '.+'):
652 # because I don't need to use a regexp if we're going to match all lines
654 # matching takes a lot more time if pattern starts or ends with .* and it isn't needed.
655 if pattern
[:2] == '.*':
656 pattern
= pattern
[2:]
657 if pattern
[-2:] == '.*':
658 pattern
= pattern
[:-2]
661 regexp
= re
.compile(pattern
, re
.IGNORECASE
)
663 regexp
= re
.compile(pattern
)
664 except Exception as e
:
665 raise Exception('Bad pattern, %s' % e
)
668 def check_string(s
, regexp
, hilight
='', exact
=False):
669 """Checks 's' with a regexp and returns it if is a match."""
674 matchlist
= regexp
.findall(s
)
676 if isinstance(matchlist
[0], tuple):
677 # join tuples (when there's more than one match group in regexp)
678 return [ ' '.join(t
) for t
in matchlist
]
682 matchlist
= regexp
.findall(s
)
684 if isinstance(matchlist
[0], tuple):
686 matchlist
= [ item
for L
in matchlist
for item
in L
if item
]
687 matchlist
= list(set(matchlist
)) # remove duplicates if any
689 color_hilight
, color_reset
= hilight
.split(',', 1)
691 s
= s
.replace(m
, '%s%s%s' % (color_hilight
, m
, color_reset
))
694 # no need for findall() here
695 elif regexp
.search(s
):
698 def grep_file(file, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
, invert
):
699 """Return a list of lines that match 'regexp' in 'file', if no regexp returns all lines."""
701 tail
= head
= after_context
= before_context
= False
704 before_context
= after_context
= False
708 #debug(' '.join(map(str, (file, head, tail, after_context, before_context))))
711 # define these locally as it makes the loop run slightly faster
712 append
= lines
.append
713 count_match
= lines
.count_match
714 separator
= lines
.append_separator
717 if check_string(s
, regexp
, hilight
, exact
):
722 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
725 file_object
= open(file, 'r')
729 if tail
or before_context
:
730 # for these options, I need to seek in the file, but is slower and uses a good deal of
731 # memory if the log is too big, so we do this *only* for these options.
732 file_lines
= file_object
.readlines()
735 # instead of searching in the whole file and later pick the last few lines, we
736 # reverse the log, search until count reached and reverse it again, that way is a lot
739 # don't invert context switches
740 before_context
, after_context
= after_context
, before_context
743 before_context_range
= list(range(1, before_context
+ 1))
744 before_context_range
.reverse()
749 while line_idx
< len(file_lines
):
750 line
= file_lines
[line_idx
]
756 for id in before_context_range
:
758 context_line
= file_lines
[line_idx
- id]
759 if check(context_line
):
760 # match in before context, that means we appended these same lines in a
761 # previous match, so we delete them merging both paragraphs
763 del lines
[id - before_context
- 1:]
773 while id < after_context
+ offset
:
776 context_line
= file_lines
[line_idx
+ id]
777 _context_line
= check(context_line
)
780 context_line
= _context_line
# so match is hilighted with --hilight
787 if limit
and lines
.matches_count
>= limit
:
797 for line
in file_object
:
800 count
or append(line
)
804 while id < after_context
+ offset
:
807 context_line
= next(file_object
)
808 _context_line
= check(context_line
)
811 context_line
= _context_line
813 count
or append(context_line
)
814 except StopIteration:
817 if limit
and lines
.matches_count
>= limit
:
823 def grep_buffer(buffer, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
,
825 """Return a list of lines that match 'regexp' in 'buffer', if no regexp returns all lines."""
828 tail
= head
= after_context
= before_context
= False
831 before_context
= after_context
= False
832 #debug(' '.join(map(str, (tail, head, after_context, before_context, count, exact, hilight))))
834 # Using /grep in grep's buffer can lead to some funny effects
835 # We should take measures if that's the case
836 def make_get_line_funcion():
837 """Returns a function for get lines from the infolist, depending if the buffer is grep's or
839 string_remove_color
= weechat
.string_remove_color
840 infolist_string
= weechat
.infolist_string
841 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
842 if grep_buffer
and buffer == grep_buffer
:
843 def function(infolist
):
844 prefix
= infolist_string(infolist
, 'prefix')
845 message
= infolist_string(infolist
, 'message')
846 if prefix
: # only our messages have prefix, ignore it
850 infolist_time
= weechat
.infolist_time
851 def function(infolist
):
852 prefix
= string_remove_color(infolist_string(infolist
, 'prefix'), '')
853 message
= string_remove_color(infolist_string(infolist
, 'message'), '')
854 date
= infolist_time(infolist
, 'date')
855 # since WeeChat 2.2, infolist_time returns a long integer
856 # instead of a string
857 if not isinstance(date
, str):
858 date
= time
.strftime('%F %T', time
.localtime(int(date
)))
859 return '%s\t%s\t%s' %(date
, prefix
, message
)
861 get_line
= make_get_line_funcion()
863 infolist
= weechat
.infolist_get('buffer_lines', buffer, '')
865 # like with grep_file() if we need the last few matching lines, we move the cursor to
866 # the end and search backwards
867 infolist_next
= weechat
.infolist_prev
868 infolist_prev
= weechat
.infolist_next
870 infolist_next
= weechat
.infolist_next
871 infolist_prev
= weechat
.infolist_prev
874 # define these locally as it makes the loop run slightly faster
875 append
= lines
.append
876 count_match
= lines
.count_match
877 separator
= lines
.append_separator
880 if check_string(s
, regexp
, hilight
, exact
):
885 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
888 before_context_range
= range(1, before_context
+ 1)
889 before_context_range
.reverse()
891 while infolist_next(infolist
):
892 line
= get_line(infolist
)
893 if line
is None: continue
899 for id in before_context_range
:
900 if not infolist_prev(infolist
):
902 for id in before_context_range
:
903 context_line
= get_line(infolist
)
904 if check(context_line
):
906 del lines
[id - before_context
- 1:]
910 infolist_next(infolist
)
911 count
or append(line
)
915 while id < after_context
+ offset
:
917 if infolist_next(infolist
):
918 context_line
= get_line(infolist
)
919 _context_line
= check(context_line
)
921 context_line
= _context_line
926 # in the main loop infolist_next will start again an cause an infinite loop
928 infolist_next
= lambda x
: 0
930 if limit
and lines
.matches_count
>= limit
:
932 weechat
.infolist_free(infolist
)
938 ### this is our main grep function
939 hook_file_grep
= None
940 def show_matching_lines():
942 Greps buffers in search_in_buffers or files in search_in_files and updates grep buffer with the
945 global pattern
, matchcase
, number
, count
, exact
, hilight
, invert
946 global tail
, head
, after_context
, before_context
947 global search_in_files
, search_in_buffers
, matched_lines
, home_dir
949 matched_lines
= linesDict()
950 #debug('buffers:%s \nlogs:%s' %(search_in_buffers, search_in_files))
954 if search_in_buffers
:
955 regexp
= make_regexp(pattern
, matchcase
)
956 for buffer in search_in_buffers
:
957 buffer_name
= weechat
.buffer_get_string(buffer, 'name')
958 matched_lines
[buffer_name
] = grep_buffer(buffer, head
, tail
, after_context
,
959 before_context
, count
, regexp
, hilight
, exact
, invert
)
963 size_limit
= get_config_int('size_limit', allow_empty_string
=True)
965 if size_limit
or size_limit
== 0:
966 size
= sum(map(get_size
, search_in_files
))
967 if size
> size_limit
* 1024:
969 elif size_limit
== '':
972 regexp
= make_regexp(pattern
, matchcase
)
974 global grep_options
, log_pairs
975 grep_options
= (head
, tail
, after_context
, before_context
,
976 count
, regexp
, hilight
, exact
, invert
)
978 log_pairs
= [(strip_home(log
), log
) for log
in search_in_files
]
982 for log_name
, log
in log_pairs
:
983 matched_lines
[log_name
] = grep_file(log
, *grep_options
)
986 global hook_file_grep
, grep_stdout
, grep_stderr
, pattern_tmpl
987 grep_stdout
= grep_stderr
= ''
988 hook_file_grep
= weechat
.hook_process(
990 get_config_int('timeout_secs') * 1000,
995 buffer_create("Searching for '%s' in %s worth of data..." % (
997 human_readable_size(size
)
1003 def grep_process(*args
):
1006 global grep_options
, log_pairs
1007 for log_name
, log
in log_pairs
:
1008 result
[log_name
] = grep_file(log
, *grep_options
)
1009 except Exception as e
:
1012 return pickle
.dumps(result
)
1014 grep_stdout
= grep_stderr
= ''
1016 def grep_process_cb(data
, command
, return_code
, out
, err
):
1017 global grep_stdout
, grep_stderr
, matched_lines
, hook_file_grep
1022 def set_buffer_error(message
):
1024 grep_buffer
= buffer_create()
1025 title
= weechat
.buffer_get_string(grep_buffer
, 'title')
1026 title
= title
+ ' %serror' % color_title
1027 weechat
.buffer_set(grep_buffer
, 'title', title
)
1029 if return_code
== weechat
.WEECHAT_HOOK_PROCESS_ERROR
:
1030 set_buffer_error("Background grep timed out")
1031 hook_file_grep
= None
1032 return WEECHAT_RC_OK
1034 elif return_code
>= 0:
1035 hook_file_grep
= None
1037 set_buffer_error(grep_stderr
)
1038 return WEECHAT_RC_OK
1041 data
= pickle
.loads(grep_stdout
)
1042 if isinstance(data
, Exception):
1044 matched_lines
.update(data
)
1045 except Exception as e
:
1046 set_buffer_error(repr(e
))
1047 return WEECHAT_RC_OK
1051 return WEECHAT_RC_OK
1053 def get_grep_file_status():
1054 global search_in_files
, matched_lines
, time_start
1055 elapsed
= now() - time_start
1056 if len(search_in_files
) == 1:
1057 log
= '%s (%s)' %(strip_home(search_in_files
[0]),
1058 human_readable_size(get_size(search_in_files
[0])))
1060 size
= sum(map(get_size
, search_in_files
))
1061 log
= '%s log files (%s)' %(len(search_in_files
), human_readable_size(size
))
1062 return 'Searching in %s, running for %.4f seconds. Interrupt it with "/grep stop" or "stop"' \
1063 ' in grep buffer.' %(log
, elapsed
)
1066 def buffer_update():
1067 """Updates our buffer with new lines."""
1068 global pattern_tmpl
, matched_lines
, pattern
, count
, hilight
, invert
, exact
1071 buffer = buffer_create()
1072 if get_config_boolean('clear_buffer'):
1073 weechat
.buffer_clear(buffer)
1074 matched_lines
.strip_separator() # remove first and last separators of each list
1075 len_total_lines
= len(matched_lines
)
1076 max_lines
= get_config_int('max_lines')
1077 if not count
and len_total_lines
> max_lines
:
1078 weechat
.buffer_clear(buffer)
1080 def _make_summary(log
, lines
, note
):
1081 return '%s matches "%s%s%s"%s in %s%s%s%s' \
1082 %(lines
.matches_count
, color_summary
, pattern_tmpl
, color_info
,
1083 invert
and ' (inverted)' or '',
1084 color_summary
, log
, color_reset
, note
)
1087 make_summary
= lambda log
, lines
: _make_summary(log
, lines
, ' (not shown)')
1089 def make_summary(log
, lines
):
1090 if lines
.stripped_lines
:
1092 note
= ' (last %s lines shown)' %len(lines
)
1094 note
= ' (not shown)'
1097 return _make_summary(log
, lines
, note
)
1099 global weechat_format
1101 # we don't want colors if there's match highlighting
1102 format_line
= lambda s
: '%s %s %s' %split
_line
(s
)
1105 global nick_dict
, weechat_format
1106 date
, nick
, msg
= split_line(s
)
1109 nick
= nick_dict
[nick
]
1112 nick_c
= color_nick(nick
)
1113 nick_dict
[nick
] = nick_c
1115 return '%s%s %s%s %s' %(color_date
, date
, nick
, color_reset
, msg
)
1121 print_line('Search for "%s%s%s"%s in %s%s%s.' %(color_summary
, pattern_tmpl
, color_info
,
1122 invert
and ' (inverted)' or '', color_summary
, matched_lines
, color_reset
),
1124 # print last <max_lines> lines
1125 if matched_lines
.get_matches_count():
1127 # with count we sort by matches lines instead of just lines.
1128 matched_lines_items
= matched_lines
.items_count()
1130 matched_lines_items
= matched_lines
.items()
1132 matched_lines
.get_last_lines(max_lines
)
1133 for log
, lines
in matched_lines_items
:
1134 if lines
.matches_count
:
1138 weechat_format
= True
1143 if line
== linesList
._sep
:
1145 prnt(buffer, context_sep
)
1149 error("Found garbage in log '%s', maybe it's corrupted" %log
)
1150 line
= line
.replace('\x00', '')
1151 prnt_date_tags(buffer, 0, 'no_highlight', format_line(line
))
1154 if count
or get_config_boolean('show_summary'):
1155 summary
= make_summary(log
, lines
)
1156 print_line(summary
, buffer)
1159 if not count
and lines
:
1162 print_line('No matches found.', buffer)
1168 time_total
= time_end
- time_start
1169 # percent of the total time used for grepping
1170 time_grep_pct
= (time_grep
- time_start
)/time_total
*100
1171 #debug('time: %.4f seconds (%.2f%%)' %(time_total, time_grep_pct))
1172 if not count
and len_total_lines
> max_lines
:
1173 note
= ' (last %s lines shown)' %len(matched_lines
)
1176 title
= "'q': close buffer | Search in %s%s%s %s matches%s | pattern \"%s%s%s\"%s %s | %.4f seconds (%.2f%%)" \
1177 %(color_title
, matched_lines
, color_reset
, matched_lines
.get_matches_count(), note
,
1178 color_title
, pattern_tmpl
, color_reset
, invert
and ' (inverted)' or '', format_options(),
1179 time_total
, time_grep_pct
)
1180 weechat
.buffer_set(buffer, 'title', title
)
1182 if get_config_boolean('go_to_buffer'):
1183 weechat
.buffer_set(buffer, 'display', '1')
1185 # free matched_lines so it can be removed from memory
1189 """Splits log's line 's' in 3 parts, date, nick and msg."""
1190 global weechat_format
1191 if weechat_format
and s
.count('\t') >= 2:
1192 date
, nick
, msg
= s
.split('\t', 2) # date, nick, message
1194 # looks like log isn't in weechat's format
1195 weechat_format
= False # incoming lines won't be formatted
1196 date
, nick
, msg
= '', '', s
1199 msg
= msg
.replace('\t', ' ')
1200 return date
, nick
, msg
1202 def print_line(s
, buffer=None, display
=False):
1203 """Prints 's' in script's buffer as 'script_nick'. For displaying search summaries."""
1205 buffer = buffer_create()
1206 say('%s%s' %(color_info
, s
), buffer)
1207 if display
and get_config_boolean('go_to_buffer'):
1208 weechat
.buffer_set(buffer, 'display', '1')
1210 def format_options():
1211 global matchcase
, number
, count
, exact
, hilight
, invert
1212 global tail
, head
, after_context
, before_context
1214 append
= options
.append
1215 insert
= options
.insert
1217 for i
, flag
in enumerate((count
, hilight
, matchcase
, exact
, invert
)):
1222 n
= get_config_int('default_tail_head')
1236 if before_context
and after_context
and (before_context
== after_context
):
1238 append(before_context
)
1242 append(before_context
)
1245 append(after_context
)
1247 s
= ''.join(map(str, options
)).strip()
1248 if s
and s
[0] != '-':
1252 def buffer_create(title
=None):
1253 """Returns our buffer pointer, creates and cleans the buffer if needed."""
1254 buffer = weechat
.buffer_search('python', SCRIPT_NAME
)
1256 buffer = weechat
.buffer_new(SCRIPT_NAME
, 'buffer_input', '', '', '')
1257 weechat
.buffer_set(buffer, 'time_for_each_line', '0')
1258 weechat
.buffer_set(buffer, 'nicklist', '0')
1259 weechat
.buffer_set(buffer, 'title', title
or 'grep output buffer')
1260 weechat
.buffer_set(buffer, 'localvar_set_no_log', '1')
1262 weechat
.buffer_set(buffer, 'title', title
)
1265 def buffer_input(data
, buffer, input_data
):
1266 """Repeats last search with 'input_data' as regexp."""
1268 cmd_grep_stop(buffer, input_data
)
1270 return WEECHAT_RC_OK
1271 if input_data
in ('q', 'Q'):
1272 weechat
.buffer_close(buffer)
1273 return weechat
.WEECHAT_RC_OK
1275 global search_in_buffers
, search_in_files
1278 if pattern
and (search_in_files
or search_in_buffers
):
1279 # check if the buffer pointers are still valid
1280 for pointer
in search_in_buffers
:
1281 infolist
= weechat
.infolist_get('buffer', pointer
, '')
1283 del search_in_buffers
[search_in_buffers
.index(pointer
)]
1284 weechat
.infolist_free(infolist
)
1286 cmd_grep_parsing(input_data
)
1287 except Exception as e
:
1288 error('Argument error, %s' % e
, buffer=buffer)
1289 return WEECHAT_RC_OK
1291 show_matching_lines()
1292 except Exception as e
:
1295 error("There isn't any previous search to repeat.", buffer=buffer)
1296 return WEECHAT_RC_OK
1300 """Resets global vars."""
1301 global home_dir
, cache_dir
, nick_dict
1302 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1303 global tail
, head
, after_context
, before_context
1305 head
= tail
= after_context
= before_context
= invert
= False
1306 matchcase
= count
= exact
= False
1307 pattern_tmpl
= pattern
= number
= None
1308 home_dir
= get_home()
1309 cache_dir
= {} # for avoid walking the dir tree more than once per command
1310 nick_dict
= {} # nick cache for don't calculate nick color every time
1312 def cmd_grep_parsing(args
):
1313 """Parses args for /grep and grep input buffer."""
1314 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1315 global tail
, head
, after_context
, before_context
1316 global log_name
, buffer_name
, only_buffers
, all
1317 opts
, args
= getopt
.gnu_getopt(args
.split(), 'cmHeahtivn:bA:B:C:o', ['count', 'matchcase', 'hilight',
1318 'exact', 'all', 'head', 'tail', 'number=', 'buffer', 'after-context=', 'before-context=',
1319 'context=', 'invert', 'only-match'])
1320 #debug(opts, 'opts: '); debug(args, 'args: ')
1322 if args
[0] == 'log':
1324 log_name
= args
.pop(0)
1325 elif args
[0] == 'buffer':
1327 buffer_name
= args
.pop(0)
1329 def tmplReplacer(match
):
1330 """This function will replace templates with regexps"""
1331 s
= match
.groups()[0]
1332 tmpl_args
= s
.split()
1333 tmpl_key
, _
, tmpl_args
= s
.partition(' ')
1335 template
= templates
[tmpl_key
]
1336 if callable(template
):
1337 r
= template(tmpl_args
)
1339 error("Template %s returned empty string "\
1340 "(WeeChat doesn't have enough data)." %t
)
1347 args
= ' '.join(args
) # join pattern for keep spaces
1350 pattern
= _tmplRe
.sub(tmplReplacer
, args
)
1351 debug('Using regexp: %s', pattern
)
1353 raise Exception('No pattern for grep the logs.')
1355 def positive_number(opt
, val
):
1366 raise Exception("argument for %s must be a positive integer." % opt
)
1368 for opt
, val
in opts
:
1369 opt
= opt
.strip('-')
1370 if opt
in ('c', 'count'):
1372 elif opt
in ('m', 'matchcase'):
1373 matchcase
= not matchcase
1374 elif opt
in ('H', 'hilight'):
1375 # hilight must be always a string!
1379 hilight
= '%s,%s' %(color_hilight
, color_reset
)
1380 # we pass the colors in the variable itself because check_string() must not use
1381 # weechat's module when applying the colors (this is for grep in a hooked process)
1382 elif opt
in ('e', 'exact', 'o', 'only-match'):
1385 elif opt
in ('a', 'all'):
1387 elif opt
in ('h', 'head'):
1390 elif opt
in ('t', 'tail'):
1393 elif opt
in ('b', 'buffer'):
1395 elif opt
in ('n', 'number'):
1396 number
= positive_number(opt
, val
)
1397 elif opt
in ('C', 'context'):
1398 n
= positive_number(opt
, val
)
1401 elif opt
in ('A', 'after-context'):
1402 after_context
= positive_number(opt
, val
)
1403 elif opt
in ('B', 'before-context'):
1404 before_context
= positive_number(opt
, val
)
1405 elif opt
in ('i', 'v', 'invert'):
1409 if number
is not None:
1418 n
= get_config_int('default_tail_head')
1424 def cmd_grep_stop(buffer, args
):
1425 global hook_file_grep
, pattern
, matched_lines
1428 weechat
.unhook(hook_file_grep
)
1429 hook_file_grep
= None
1431 s
= 'Search for \'%s\' stopped.' % pattern
1433 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
1435 weechat
.buffer_set(grep_buffer
, 'title', s
)
1438 say(get_grep_file_status(), buffer)
1441 def cmd_grep(data
, buffer, args
):
1442 """Search in buffers and logs."""
1443 global pattern
, matchcase
, head
, tail
, number
, count
, exact
, hilight
1445 cmd_grep_stop(buffer, args
)
1447 return WEECHAT_RC_OK
1450 weechat
.command('', '/help %s' %SCRIPT_COMMAND
)
1451 return WEECHAT_RC_OK
1454 global log_name
, buffer_name
, only_buffers
, all
1455 log_name
= buffer_name
= ''
1456 only_buffers
= all
= False
1460 cmd_grep_parsing(args
)
1461 except Exception as e
:
1462 error('Argument error, %s' % e
)
1463 return WEECHAT_RC_OK
1466 log_file
= search_buffer
= None
1468 log_file
= get_file_by_pattern(log_name
, all
)
1470 error("Couldn't find any log for %s. Try /logs" %log_name
)
1471 return WEECHAT_RC_OK
1473 search_buffer
= get_all_buffers()
1475 search_buffer
= get_buffer_by_name(buffer_name
)
1476 if not search_buffer
:
1477 # there's no buffer, try in the logs
1478 log_file
= get_file_by_name(buffer_name
)
1480 error("Logs or buffer for '%s' not found." %buffer_name
)
1481 return WEECHAT_RC_OK
1483 search_buffer
= [search_buffer
]
1485 search_buffer
= [buffer]
1488 global search_in_files
, search_in_buffers
1489 search_in_files
= []
1490 search_in_buffers
= []
1492 search_in_files
= log_file
1493 elif not only_buffers
:
1494 #debug(search_buffer)
1495 for pointer
in search_buffer
:
1496 log
= get_file_by_buffer(pointer
)
1497 #debug('buffer %s log %s' %(pointer, log))
1499 search_in_files
.append(log
)
1501 search_in_buffers
.append(pointer
)
1503 search_in_buffers
= search_buffer
1507 show_matching_lines()
1508 except Exception as e
:
1510 return WEECHAT_RC_OK
1512 def cmd_logs(data
, buffer, args
):
1513 """List files in Weechat's log dir."""
1516 sort_by_size
= False
1520 opts
, args
= getopt
.gnu_getopt(args
.split(), 's', ['size'])
1523 for opt
, var
in opts
:
1524 opt
= opt
.strip('-')
1525 if opt
in ('size', 's'):
1527 except Exception as e
:
1528 error('Argument error, %s' % e
)
1529 return WEECHAT_RC_OK
1531 # is there's a filter, filter_excludes should be False
1532 file_list
= dir_list(home_dir
, filter, filter_excludes
=not filter)
1534 file_list
.sort(key
=get_size
)
1538 file_sizes
= map(lambda x
: human_readable_size(get_size(x
)), file_list
)
1539 # calculate column lenght
1544 column_len
= len(bigest
) + 3
1548 buffer = buffer_create()
1549 if get_config_boolean('clear_buffer'):
1550 weechat
.buffer_clear(buffer)
1551 file_list
= zip(file_list
, file_sizes
)
1552 msg
= 'Found %s logs.' %len(file_list
)
1554 print_line(msg
, buffer, display
=True)
1555 for file, size
in file_list
:
1556 separator
= column_len
and '.'*(column_len
- len(file))
1557 prnt(buffer, '%s %s %s' %(strip_home(file), separator
, size
))
1559 print_line(msg
, buffer)
1560 return WEECHAT_RC_OK
1564 def completion_log_files(data
, completion_item
, buffer, completion
):
1565 #debug('completion: %s' %', '.join((data, completion_item, buffer, completion)))
1568 completion_list_add
= weechat
.hook_completion_list_add
1569 WEECHAT_LIST_POS_END
= weechat
.WEECHAT_LIST_POS_END
1570 for log
in dir_list(home_dir
):
1571 completion_list_add(completion
, log
[l
:], 0, WEECHAT_LIST_POS_END
)
1572 return WEECHAT_RC_OK
1574 def completion_grep_args(data
, completion_item
, buffer, completion
):
1575 for arg
in ('count', 'all', 'matchcase', 'hilight', 'exact', 'head', 'tail', 'number', 'buffer',
1576 'after-context', 'before-context', 'context', 'invert', 'only-match'):
1577 weechat
.hook_completion_list_add(completion
, '--' + arg
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1578 for tmpl
in templates
:
1579 weechat
.hook_completion_list_add(completion
, '%{' + tmpl
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1580 return WEECHAT_RC_OK
1584 # template placeholder
1585 _tmplRe
= re
.compile(r
'%\{(\w+.*?)(?:\}|$)')
1586 # will match 999.999.999.999 but I don't care
1587 ipAddress
= r
'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
1588 domain
= r
'[\w-]{2,}(?:\.[\w-]{2,})*\.[a-z]{2,}'
1589 url
= r
'\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?' % (domain
, ipAddress
)
1591 def make_url_regexp(args
):
1592 #debug('make url: %s', args)
1594 words
= r
'(?:%s)' %'|'.join(map(re
.escape
, args
.split()))
1595 return r
'(?:\w+://|www\.)[^\s]*%s[^\s]*(?:/[^\])>\s]*)?' %words
1599 def make_simple_regexp(pattern
):
1612 'url': make_url_regexp
,
1613 'escape': lambda s
: re
.escape(s
),
1614 'simple': make_simple_regexp
,
1619 def delete_bytecode():
1621 bytecode
= path
.join(script_path
, SCRIPT_NAME
+ '.pyc')
1622 if path
.isfile(bytecode
):
1624 return WEECHAT_RC_OK
1626 if __name__
== '__main__' and import_ok
and \
1627 weechat
.register(SCRIPT_NAME
, SCRIPT_AUTHOR
, SCRIPT_VERSION
, SCRIPT_LICENSE
, \
1628 SCRIPT_DESC
, 'delete_bytecode', ''):
1629 home_dir
= get_home()
1631 # for import ourselves
1633 script_path
= path
.dirname(__file__
)
1634 sys
.path
.append(script_path
)
1637 # check python version
1640 if sys
.version_info
> (2, 6):
1646 weechat
.hook_command(SCRIPT_COMMAND
, cmd_grep
.__doc
__,
1647 "[log <file> | buffer <name> | stop] [-a|--all] [-b|--buffer] [-c|--count] [-m|--matchcase] "
1648 "[-H|--hilight] [-o|--only-match] [-i|-v|--invert] [(-h|--head)|(-t|--tail) [-n|--number <n>]] "
1649 "[-A|--after-context <n>] [-B|--before-context <n>] [-C|--context <n> ] <expression>",
1652 log <file>: Search in one log that matches <file> in the logger path.
1653 Use '*' and '?' as wildcards.
1654 buffer <name>: Search in buffer <name>, if there's no buffer with <name> it will
1655 try to search for a log file.
1656 stop: Stops a currently running search.
1657 -a --all: Search in all open buffers.
1658 If used with 'log <file>' search in all logs that matches <file>.
1659 -b --buffer: Search only in buffers, not in file logs.
1660 -c --count: Just count the number of matched lines instead of showing them.
1661 -m --matchcase: Don't do case insensitive search.
1662 -H --hilight: Colour exact matches in output buffer.
1663 -o --only-match: Print only the matching part of the line (unique matches).
1664 -v -i --invert: Print lines that don't match the regular expression.
1665 -t --tail: Print the last 10 matching lines.
1666 -h --head: Print the first 10 matching lines.
1667 -n --number <n>: Overrides default number of lines for --tail or --head.
1668 -A --after-context <n>: Shows <n> lines of trailing context after matching lines.
1669 -B --before-context <n>: Shows <n> lines of leading context before matching lines.
1670 -C --context <n>: Same as using both --after-context and --before-context simultaneously.
1671 <expression>: Expression to search.
1674 Input line accepts most arguments of /grep, it'll repeat last search using the new
1675 arguments provided. You can't search in different logs from the buffer's input.
1676 Boolean arguments like --count, --tail, --head, --hilight, ... are toggleable
1678 Python regular expression syntax:
1679 See http://docs.python.org/lib/re-syntax.html
1682 %{url [text]}: Matches anything like an url, or an url with text.
1683 %{ip}: Matches anything that looks like an ip.
1684 %{domain}: Matches anything like a domain.
1685 %{escape text}: Escapes text in pattern.
1686 %{simple pattern}: Converts a pattern with '*' and '?' wildcards into a regexp.
1689 Search for urls with the word 'weechat' said by 'nick'
1690 /grep nick\\t.*%{url weechat}
1691 Search for '*.*' string
1694 # completion template
1695 "buffer %(buffers_names) %(grep_arguments)|%*"
1696 "||log %(grep_log_files) %(grep_arguments)|%*"
1698 "||%(grep_arguments)|%*",
1700 weechat
.hook_command('logs', cmd_logs
.__doc
__, "[-s|--size] [<filter>]",
1701 "-s --size: Sort logs by size.\n"
1702 " <filter>: Only show logs that match <filter>. Use '*' and '?' as wildcards.", '--size', 'cmd_logs', '')
1704 weechat
.hook_completion('grep_log_files', "list of log files",
1705 'completion_log_files', '')
1706 weechat
.hook_completion('grep_arguments', "list of arguments",
1707 'completion_grep_args', '')
1710 for opt
, val
in settings
.items():
1711 if not weechat
.config_is_set_plugin(opt
):
1712 weechat
.config_set_plugin(opt
, val
)
1715 color_date
= weechat
.color('brown')
1716 color_info
= weechat
.color('cyan')
1717 color_hilight
= weechat
.color('lightred')
1718 color_reset
= weechat
.color('reset')
1719 color_title
= weechat
.color('yellow')
1720 color_summary
= weechat
.color('lightcyan')
1721 color_delimiter
= weechat
.color('chat_delimiters')
1722 color_script_nick
= weechat
.color('chat_nick')
1725 script_nick
= '%s[%s%s%s]%s' %(color_delimiter
, color_script_nick
, SCRIPT_NAME
, color_delimiter
,
1727 script_nick_nocolor
= '[%s]' %SCRIPT_NAME
1728 # paragraph separator when using context options
1729 context_sep
= '%s\t%s--' %(script_nick
, color_info
)
1731 # -------------------------------------------------------------------------
1734 if weechat
.config_get_plugin('debug'):
1736 # custom debug module I use, allows me to inspect script's objects.
1738 debug
= pybuffer
.debugBuffer(globals(), '%s_debug' % SCRIPT_NAME
)
1740 def debug(s
, *args
):
1741 if not isinstance(s
, basestring
):
1745 prnt('', '%s\t%s' %(script_nick
, s
))
1750 # vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=100: