1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2009-2011 by Elián Hanisch <lambdae2@gmail.com>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 # Search in Weechat buffers and logs (for Weechat 0.3.*)
22 # Inspired by xt's grep.py
23 # Originally I just wanted to add some fixes in grep.py, but then
24 # I got carried away and rewrote everything, so new script.
28 # Search in logs or buffers, see /help grep
30 # Lists logs in ~/.weechat/logs, see /help logs
33 # * plugins.var.python.grep.clear_buffer:
34 # Clear the results buffer before each search. Valid values: on, off
36 # * plugins.var.python.grep.go_to_buffer:
37 # Automatically go to grep buffer when search is over. Valid values: on, off
39 # * plugins.var.python.grep.log_filter:
40 # Coma separated list of patterns that grep will use for exclude logs, e.g.
41 # if you use '*server/*' any log in the 'server' folder will be excluded
42 # when using the command '/grep log'
44 # * plugins.var.python.grep.show_summary:
45 # Shows summary for each log. Valid values: on, off
47 # * plugins.var.python.grep.max_lines:
48 # Grep will only print the last matched lines that don't surpass the value defined here.
50 # * plugins.var.python.grep.size_limit:
51 # Size limit in KiB, is used for decide whenever grepping should run in background or not. If
52 # the logs to grep have a total size bigger than this value then grep run as a new process.
53 # It can be used for force or disable background process, using '0' forces to always grep in
54 # background, while using '' (empty string) will disable it.
56 # * plugins.var.python.grep.default_tail_head:
57 # Config option for define default number of lines returned when using --head or --tail options.
58 # Can be overriden in the command with --number option.
62 # * try to figure out why hook_process chokes in long outputs (using a tempfile as a
64 # * possibly add option for defining time intervals
69 # 2017-07-23, Sébastien Helleu <flashcode@flashtux.org>
70 # version 0.7.8: fix modulo by zero when nick is empty string
72 # 2016-06-23, mickael9
73 # version 0.7.7: fix get_home function
76 # version 0.7.6: fix a typo
80 # '~' is now expaned to the home directory in the log file path so
81 # paths like '~/logs/' should work.
84 # version 0.7.4: make q work to quit grep buffer (requested by: gb)
86 # 2014-03-29, Felix Eckhofer <felix@tribut.de>
87 # version 0.7.3: fix typo
90 # version 0.7.2: bug fixes
94 # * use TempFile so temporal files are guaranteed to be deleted.
95 # * enable Archlinux workaround.
100 # * using --only-match shows only unique strings.
101 # * fixed bug that inverted -B -A switches when used with -t
104 # version 0.6.8: by xt <xt@bash.no>
105 # * supress highlights when printing in grep buffer
108 # version 0.6.7: by xt <xt@bash.no>
109 # * better temporary file:
110 # use tempfile.mkstemp. to create a temp file in log dir,
111 # makes it safer with regards to write permission and multi user
114 # version 0.6.6: bug fixes
115 # * use WEECHAT_LIST_POS_END in log file completion, makes completion faster
116 # * disable bytecode if using python 2.6
117 # * use single quotes in command string
118 # * fix bug that could change buffer's title when using /grep stop
121 # version 0.6.5: disable bytecode is a 2.6 feature, instead, resort to delete the bytecode manually
124 # version 0.6.4: bug fix
125 # version 0.6.3: added options --invert --only-match (replaces --exact, which is still available
126 # but removed from help)
127 # * use new 'irc_nick_color' info
128 # * don't generate bytecode when spawning a new process
129 # * show active options in buffer title
132 # version 0.6.2: removed 2.6-ish code
133 # version 0.6.1: fixed bug when grepping in grep's buffer
136 # version 0.6.0: implemented grep in background
137 # * improved context lines presentation.
138 # * grepping for big (or many) log files runs in a weechat_process.
139 # * added /grep stop.
140 # * added 'size_limit' option
141 # * fixed a infolist leak when grepping buffers
142 # * added 'default_tail_head' option
143 # * results are sort by line count
144 # * don't die if log is corrupted (has NULL chars in it)
145 # * changed presentation of /logs
146 # * log path completion doesn't suck anymore
147 # * removed all tabs, because I learned how to configure Vim so that spaces aren't annoying
148 # anymore. This was the script's original policy.
151 # version 0.5.5: rename script to 'grep.py' (FlashCode <flashcode@flashtux.org>).
154 # version 0.5.4.1: fix index error when using --after/before-context options.
157 # version 0.5.4: new features
158 # * added --after-context and --before-context options.
159 # * added --context as a shortcut for using both -A -B options.
162 # version 0.5.3: improvements for long grep output
163 # * grep buffer input accepts the same flags as /grep for repeat a search with different
165 # * tweaks in grep's output.
166 # * max_lines option added for limit grep's output.
167 # * code in update_buffer() optimized.
168 # * time stats in buffer title.
169 # * added go_to_buffer config option.
170 # * added --buffer for search only in buffers.
174 # version 0.5.2: made it python-2.4.x compliant
177 # version 0.5.1: some refactoring, show_summary option added.
180 # version 0.5: rewritten from xt's grep.py
181 # * fixed searching in non weechat logs, for cases like, if you're
182 # switching from irssi and rename and copy your irssi logs to %h/logs
183 # * fixed "timestamp rainbow" when you /grep in grep's buffer
184 # * allow to search in other buffers other than current or in logs
185 # of currently closed buffers with cmd 'buffer'
186 # * allow to search in any log file in %h/logs with cmd 'log'
187 # * added --count for return the number of matched lines
188 # * added --matchcase for case sensible search
189 # * added --hilight for color matches
190 # * added --head and --tail options, and --number
191 # * added command /logs for list files in %h/logs
192 # * added config option for clear the buffer before a search
193 # * added config option for filter logs we don't want to grep
194 # * added the posibility to repeat last search with another regexp by writing
195 # it in grep's buffer
196 # * changed spaces for tabs in the code, which is my preference
201 import sys
, getopt
, time
, os
, re
, tempfile
205 from weechat
import WEECHAT_RC_OK
, prnt
, prnt_date_tags
211 SCRIPT_AUTHOR
= "Elián Hanisch <lambdae2@gmail.com>"
212 SCRIPT_VERSION
= "0.7.8"
213 SCRIPT_LICENSE
= "GPL3"
214 SCRIPT_DESC
= "Search in buffers and logs"
215 SCRIPT_COMMAND
= "grep"
217 ### Default Settings ###
219 'clear_buffer' : 'off',
221 'go_to_buffer' : 'on',
222 'max_lines' : '4000',
223 'show_summary' : 'on',
224 'size_limit' : '2048',
225 'default_tail_head' : '10',
228 ### Class definitions ###
229 class linesDict(dict):
231 Class for handling matched lines in more than one buffer.
232 linesDict[buffer_name] = matched_lines_list
234 def __setitem__(self
, key
, value
):
235 assert isinstance(value
, list)
237 dict.__setitem
__(self
, key
, value
)
239 dict.__getitem
__(self
, key
).extend(value
)
241 def get_matches_count(self
):
242 """Return the sum of total matches stored."""
243 if dict.__len
__(self
):
244 return sum(map(lambda L
: L
.matches_count
, self
.itervalues()))
249 """Return the sum of total lines stored."""
250 if dict.__len
__(self
):
251 return sum(map(len, self
.itervalues()))
256 """Returns buffer count or buffer name if there's just one stored."""
259 return self
.keys()[0]
266 """Returns a list of items sorted by line count."""
267 items
= dict.items(self
)
268 items
.sort(key
=lambda i
: len(i
[1]))
271 def items_count(self
):
272 """Returns a list of items sorted by match count."""
273 items
= dict.items(self
)
274 items
.sort(key
=lambda i
: i
[1].matches_count
)
277 def strip_separator(self
):
278 for L
in self
.itervalues():
281 def get_last_lines(self
, n
):
282 total_lines
= len(self
)
283 #debug('total: %s n: %s' %(total_lines, n))
287 for k
, v
in reversed(self
.items()):
292 v
.stripped_lines
= l
-n
298 class linesList(list):
299 """Class for list of matches, since sometimes I need to add lines that aren't matches, I need an
300 independent counter."""
302 def __init__(self
, *args
):
303 list.__init
__(self
, *args
)
304 self
.matches_count
= 0
305 self
.stripped_lines
= 0
307 def append(self
, item
):
308 """Append lines, can be a string or a list with strings."""
309 if isinstance(item
, str):
310 list.append(self
, item
)
314 def append_separator(self
):
315 """adds a separator into the list, makes sure it doen't add two together."""
317 if (self
and self
[-1] != s
) or not self
:
325 def count_match(self
, item
=None):
326 if item
is None or isinstance(item
, str):
327 self
.matches_count
+= 1
329 self
.matches_count
+= len(item
)
331 def strip_separator(self
):
332 """removes separators if there are first or/and last in the list."""
340 ### Misc functions ###
344 return os
.stat(f
).st_size
348 sizeDict
= {0:'b', 1:'KiB', 2:'MiB', 3:'GiB', 4:'TiB'}
349 def human_readable_size(size
):
354 return '%.2f %s' %(size
, sizeDict
.get(power
, ''))
356 def color_nick(nick
):
357 """Returns coloured nick, with coloured mode if any."""
358 if not nick
: return ''
359 wcolor
= weechat
.color
360 config_string
= lambda s
: weechat
.config_string(weechat
.config_get(s
))
361 config_int
= lambda s
: weechat
.config_integer(weechat
.config_get(s
))
363 prefix
= config_string('irc.look.nick_prefix')
364 suffix
= config_string('irc.look.nick_suffix')
365 prefix_c
= suffix_c
= wcolor(config_string('weechat.color.chat_delimiters'))
366 if nick
[0] == prefix
:
369 prefix
= prefix_c
= ''
370 if nick
[-1] == suffix
:
372 suffix
= wcolor(color_delimiter
) + suffix
374 suffix
= suffix_c
= ''
378 mode
, nick
= nick
[0], nick
[1:]
379 mode_color
= wcolor(config_string('weechat.color.nicklist_prefix%d' \
380 %(modes
.find(mode
) + 1)))
382 mode
= mode_color
= ''
386 nick_color
= weechat
.info_get('irc_nick_color', nick
)
388 # probably we're in WeeChat 0.3.0
389 #debug('no irc_nick_color')
390 color_nicks_number
= config_int('weechat.look.color_nicks_number')
391 idx
= (sum(map(ord, nick
))%color
_nicks
_number
) + 1
392 nick_color
= wcolor(config_string('weechat.color.chat_nick_color%02d' %idx))
393 return ''.join((prefix_c
, prefix
, mode_color
, mode
, nick_color
, nick
, suffix_c
, suffix
))
395 ### Config and value validation ###
396 boolDict
= {'on':True, 'off':False}
397 def get_config_boolean(config
):
398 value
= weechat
.config_get_plugin(config
)
400 return boolDict
[value
]
402 default
= settings
[config
]
403 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
404 error("'%s' is invalid, allowed: 'on', 'off'" %value
)
405 return boolDict
[default
]
407 def get_config_int(config
, allow_empty_string
=False):
408 value
= weechat
.config_get_plugin(config
)
412 if value
== '' and allow_empty_string
:
414 default
= settings
[config
]
415 error("Error while fetching config '%s'. Using default value '%s'." %(config
, default
))
416 error("'%s' is not a number." %value
)
419 def get_config_log_filter():
420 filter = weechat
.config_get_plugin('log_filter')
422 return filter.split(',')
427 home
= weechat
.config_string(weechat
.config_get('logger.file.path'))
428 home
= home
.replace('%h', weechat
.info_get('weechat_dir', ''))
429 home
= path
.abspath(path
.expanduser(home
))
432 def strip_home(s
, dir=''):
433 """Strips home dir from the begging of the log path, this makes them sorter."""
443 script_nick
= SCRIPT_NAME
444 def error(s
, buffer=''):
446 prnt(buffer, '%s%s %s' %(weechat
.prefix('error'), script_nick
, s
))
447 if weechat
.config_get_plugin('debug'):
449 if traceback
.sys
.exc_type
:
450 trace
= traceback
.format_exc()
453 def say(s
, buffer=''):
455 prnt_date_tags(buffer, 0, 'no_highlight', '%s\t%s' %(script_nick
, s
))
459 ### Log files and buffers ###
460 cache_dir
= {} # note: don't remove, needed for completion if the script was loaded recently
461 def dir_list(dir, filter_list
=(), filter_excludes
=True, include_dir
=False):
462 """Returns a list of files in 'dir' and its subdirs."""
465 from fnmatch
import fnmatch
466 #debug('dir_list: listing in %s' %dir)
467 key
= (dir, include_dir
)
469 return cache_dir
[key
]
473 filter_list
= filter_list
or get_config_log_filter()
477 file = file[dir_len
:] # pattern shouldn't match home dir
478 for pattern
in filter_list
:
479 if fnmatch(file, pattern
):
480 return filter_excludes
481 return not filter_excludes
483 filter = lambda f
: not filter_excludes
486 extend
= file_list
.extend
489 for basedir
, subdirs
, files
in walk(dir):
491 # subdirs = map(lambda s : join(s, ''), subdirs)
492 # files.extend(subdirs)
493 files_path
= map(lambda f
: join(basedir
, f
), files
)
494 files_path
= [ file for file in files_path
if not filter(file) ]
498 cache_dir
[key
] = file_list
499 #debug('dir_list: got %s' %str(file_list))
502 def get_file_by_pattern(pattern
, all
=False):
503 """Returns the first log whose path matches 'pattern',
504 if all is True returns all logs that matches."""
505 if not pattern
: return []
506 #debug('get_file_by_filename: searching for %s.' %pattern)
507 # do envvar expandsion and check file
508 file = path
.expanduser(pattern
)
509 file = path
.expandvars(file)
510 if path
.isfile(file):
512 # lets see if there's a matching log
514 file = path
.join(home_dir
, pattern
)
515 if path
.isfile(file):
518 from fnmatch
import fnmatch
520 file_list
= dir_list(home_dir
)
522 for log
in file_list
:
524 if fnmatch(basename
, pattern
):
526 #debug('get_file_by_filename: got %s.' %file)
532 def get_file_by_buffer(buffer):
533 """Given buffer pointer, finds log's path or returns None."""
534 #debug('get_file_by_buffer: searching for %s' %buffer)
535 infolist
= weechat
.infolist_get('logger_buffer', '', '')
536 if not infolist
: return
538 while weechat
.infolist_next(infolist
):
539 pointer
= weechat
.infolist_pointer(infolist
, 'buffer')
540 if pointer
== buffer:
541 file = weechat
.infolist_string(infolist
, 'log_filename')
542 if weechat
.infolist_integer(infolist
, 'log_enabled'):
543 #debug('get_file_by_buffer: got %s' %file)
546 # debug('get_file_by_buffer: got %s but log not enabled' %file)
548 #debug('infolist gets freed')
549 weechat
.infolist_free(infolist
)
551 def get_file_by_name(buffer_name
):
552 """Given a buffer name, returns its log path or None. buffer_name should be in 'server.#channel'
553 or '#channel' format."""
554 #debug('get_file_by_name: searching for %s' %buffer_name)
555 # common mask options
556 config_masks
= ('logger.mask.irc', 'logger.file.mask')
557 # since there's no buffer pointer, we try to replace some local vars in mask, like $channel and
558 # $server, then replace the local vars left with '*', and use it as a mask for get the path with
559 # get_file_by_pattern
560 for config
in config_masks
:
561 mask
= weechat
.config_string(weechat
.config_get(config
))
562 #debug('get_file_by_name: mask: %s' %mask)
564 mask
= mask
.replace('$name', buffer_name
)
565 elif '$channel' in mask
or '$server' in mask
:
566 if '.' in buffer_name
and \
567 '#' not in buffer_name
[:buffer_name
.find('.')]: # the dot isn't part of the channel name
568 # ^ I'm asuming channel starts with #, i'm lazy.
569 server
, channel
= buffer_name
.split('.', 1)
571 server
, channel
= '*', buffer_name
572 if '$channel' in mask
:
573 mask
= mask
.replace('$channel', channel
)
574 if '$server' in mask
:
575 mask
= mask
.replace('$server', server
)
576 # change the unreplaced vars by '*'
577 from string
import letters
579 # vars for time formatting
580 mask
= mask
.replace('%', '$')
582 masks
= mask
.split('$')
583 masks
= map(lambda s
: s
.lstrip(letters
), masks
)
584 mask
= '*'.join(masks
)
587 #debug('get_file_by_name: using mask %s' %mask)
588 file = get_file_by_pattern(mask
)
589 #debug('get_file_by_name: got file %s' %file)
594 def get_buffer_by_name(buffer_name
):
595 """Given a buffer name returns its buffer pointer or None."""
596 #debug('get_buffer_by_name: searching for %s' %buffer_name)
597 pointer
= weechat
.buffer_search('', buffer_name
)
600 infolist
= weechat
.infolist_get('buffer', '', '')
601 while weechat
.infolist_next(infolist
):
602 short_name
= weechat
.infolist_string(infolist
, 'short_name')
603 name
= weechat
.infolist_string(infolist
, 'name')
604 if buffer_name
in (short_name
, name
):
605 #debug('get_buffer_by_name: found %s' %name)
606 pointer
= weechat
.buffer_search('', name
)
609 weechat
.infolist_free(infolist
)
610 #debug('get_buffer_by_name: got %s' %pointer)
613 def get_all_buffers():
614 """Returns list with pointers of all open buffers."""
616 infolist
= weechat
.infolist_get('buffer', '', '')
617 while weechat
.infolist_next(infolist
):
618 buffers
.append(weechat
.infolist_pointer(infolist
, 'pointer'))
619 weechat
.infolist_free(infolist
)
620 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
621 if grep_buffer
and grep_buffer
in buffers
:
622 # remove it from list
623 del buffers
[buffers
.index(grep_buffer
)]
627 def make_regexp(pattern
, matchcase
=False):
628 """Returns a compiled regexp."""
629 if pattern
in ('.', '.*', '.?', '.+'):
630 # because I don't need to use a regexp if we're going to match all lines
632 # matching takes a lot more time if pattern starts or ends with .* and it isn't needed.
633 if pattern
[:2] == '.*':
634 pattern
= pattern
[2:]
635 if pattern
[-2:] == '.*':
636 pattern
= pattern
[:-2]
639 regexp
= re
.compile(pattern
, re
.IGNORECASE
)
641 regexp
= re
.compile(pattern
)
643 raise Exception, 'Bad pattern, %s' %e
646 def check_string(s
, regexp
, hilight
='', exact
=False):
647 """Checks 's' with a regexp and returns it if is a match."""
652 matchlist
= regexp
.findall(s
)
654 if isinstance(matchlist
[0], tuple):
655 # join tuples (when there's more than one match group in regexp)
656 return [ ' '.join(t
) for t
in matchlist
]
660 matchlist
= regexp
.findall(s
)
662 if isinstance(matchlist
[0], tuple):
664 matchlist
= [ item
for L
in matchlist
for item
in L
if item
]
665 matchlist
= list(set(matchlist
)) # remove duplicates if any
667 color_hilight
, color_reset
= hilight
.split(',', 1)
669 s
= s
.replace(m
, '%s%s%s' % (color_hilight
, m
, color_reset
))
672 # no need for findall() here
673 elif regexp
.search(s
):
676 def grep_file(file, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
, invert
):
677 """Return a list of lines that match 'regexp' in 'file', if no regexp returns all lines."""
679 tail
= head
= after_context
= before_context
= False
682 before_context
= after_context
= False
686 #debug(' '.join(map(str, (file, head, tail, after_context, before_context))))
689 # define these locally as it makes the loop run slightly faster
690 append
= lines
.append
691 count_match
= lines
.count_match
692 separator
= lines
.append_separator
695 if check_string(s
, regexp
, hilight
, exact
):
700 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
703 file_object
= open(file, 'r')
707 if tail
or before_context
:
708 # for these options, I need to seek in the file, but is slower and uses a good deal of
709 # memory if the log is too big, so we do this *only* for these options.
710 file_lines
= file_object
.readlines()
713 # instead of searching in the whole file and later pick the last few lines, we
714 # reverse the log, search until count reached and reverse it again, that way is a lot
717 # don't invert context switches
718 before_context
, after_context
= after_context
, before_context
721 before_context_range
= range(1, before_context
+ 1)
722 before_context_range
.reverse()
727 while line_idx
< len(file_lines
):
728 line
= file_lines
[line_idx
]
734 for id in before_context_range
:
736 context_line
= file_lines
[line_idx
- id]
737 if check(context_line
):
738 # match in before context, that means we appended these same lines in a
739 # previous match, so we delete them merging both paragraphs
741 del lines
[id - before_context
- 1:]
751 while id < after_context
+ offset
:
754 context_line
= file_lines
[line_idx
+ id]
755 _context_line
= check(context_line
)
758 context_line
= _context_line
# so match is hilighted with --hilight
765 if limit
and lines
.matches_count
>= limit
:
775 for line
in file_object
:
778 count
or append(line
)
782 while id < after_context
+ offset
:
785 context_line
= file_object
.next()
786 _context_line
= check(context_line
)
789 context_line
= _context_line
791 count
or append(context_line
)
792 except StopIteration:
795 if limit
and lines
.matches_count
>= limit
:
801 def grep_buffer(buffer, head
, tail
, after_context
, before_context
, count
, regexp
, hilight
, exact
,
803 """Return a list of lines that match 'regexp' in 'buffer', if no regexp returns all lines."""
806 tail
= head
= after_context
= before_context
= False
809 before_context
= after_context
= False
810 #debug(' '.join(map(str, (tail, head, after_context, before_context, count, exact, hilight))))
812 # Using /grep in grep's buffer can lead to some funny effects
813 # We should take measures if that's the case
814 def make_get_line_funcion():
815 """Returns a function for get lines from the infolist, depending if the buffer is grep's or
817 string_remove_color
= weechat
.string_remove_color
818 infolist_string
= weechat
.infolist_string
819 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
820 if grep_buffer
and buffer == grep_buffer
:
821 def function(infolist
):
822 prefix
= infolist_string(infolist
, 'prefix')
823 message
= infolist_string(infolist
, 'message')
824 if prefix
: # only our messages have prefix, ignore it
828 infolist_time
= weechat
.infolist_time
829 def function(infolist
):
830 prefix
= string_remove_color(infolist_string(infolist
, 'prefix'), '')
831 message
= string_remove_color(infolist_string(infolist
, 'message'), '')
832 date
= infolist_time(infolist
, 'date')
833 return '%s\t%s\t%s' %(date
, prefix
, message
)
835 get_line
= make_get_line_funcion()
837 infolist
= weechat
.infolist_get('buffer_lines', buffer, '')
839 # like with grep_file() if we need the last few matching lines, we move the cursor to
840 # the end and search backwards
841 infolist_next
= weechat
.infolist_prev
842 infolist_prev
= weechat
.infolist_next
844 infolist_next
= weechat
.infolist_next
845 infolist_prev
= weechat
.infolist_prev
848 # define these locally as it makes the loop run slightly faster
849 append
= lines
.append
850 count_match
= lines
.count_match
851 separator
= lines
.append_separator
854 if check_string(s
, regexp
, hilight
, exact
):
859 check
= lambda s
: check_string(s
, regexp
, hilight
, exact
)
862 before_context_range
= range(1, before_context
+ 1)
863 before_context_range
.reverse()
865 while infolist_next(infolist
):
866 line
= get_line(infolist
)
867 if line
is None: continue
873 for id in before_context_range
:
874 if not infolist_prev(infolist
):
876 for id in before_context_range
:
877 context_line
= get_line(infolist
)
878 if check(context_line
):
880 del lines
[id - before_context
- 1:]
884 infolist_next(infolist
)
885 count
or append(line
)
889 while id < after_context
+ offset
:
891 if infolist_next(infolist
):
892 context_line
= get_line(infolist
)
893 _context_line
= check(context_line
)
895 context_line
= _context_line
900 # in the main loop infolist_next will start again an cause an infinite loop
902 infolist_next
= lambda x
: 0
904 if limit
and lines
.matches_count
>= limit
:
906 weechat
.infolist_free(infolist
)
912 ### this is our main grep function
913 hook_file_grep
= None
914 def show_matching_lines():
916 Greps buffers in search_in_buffers or files in search_in_files and updates grep buffer with the
919 global pattern
, matchcase
, number
, count
, exact
, hilight
, invert
920 global tail
, head
, after_context
, before_context
921 global search_in_files
, search_in_buffers
, matched_lines
, home_dir
923 matched_lines
= linesDict()
924 #debug('buffers:%s \nlogs:%s' %(search_in_buffers, search_in_files))
928 if search_in_buffers
:
929 regexp
= make_regexp(pattern
, matchcase
)
930 for buffer in search_in_buffers
:
931 buffer_name
= weechat
.buffer_get_string(buffer, 'name')
932 matched_lines
[buffer_name
] = grep_buffer(buffer, head
, tail
, after_context
,
933 before_context
, count
, regexp
, hilight
, exact
, invert
)
937 size_limit
= get_config_int('size_limit', allow_empty_string
=True)
939 if size_limit
or size_limit
== 0:
940 size
= sum(map(get_size
, search_in_files
))
941 if size
> size_limit
* 1024:
943 elif size_limit
== '':
948 regexp
= make_regexp(pattern
, matchcase
)
949 for log
in search_in_files
:
950 log_name
= strip_home(log
)
951 matched_lines
[log_name
] = grep_file(log
, head
, tail
, after_context
, before_context
,
952 count
, regexp
, hilight
, exact
, invert
)
955 # we hook a process so grepping runs in background.
956 #debug('on background')
957 global hook_file_grep
, script_path
, bytecode
958 timeout
= 1000*60*5 # 5 min
960 quotify
= lambda s
: '"%s"' %s
961 files_string
= ', '.join(map(quotify
, search_in_files
))
964 # we keep the file descriptor as a global var so it isn't deleted until next grep
965 tmpFile
= tempfile
.NamedTemporaryFile(prefix
=SCRIPT_NAME
,
966 dir=weechat
.info_get('weechat_dir', ''))
967 cmd
= grep_process_cmd
%dict
(logs
=files_string
, head
=head
, pattern
=pattern
, tail
=tail
,
968 hilight
=hilight
, after_context
=after_context
, before_context
=before_context
,
969 exact
=exact
, matchcase
=matchcase
, home_dir
=home_dir
, script_path
=script_path
,
970 count
=count
, invert
=invert
, bytecode
=bytecode
, filename
=tmpFile
.name
,
971 python
=weechat
.info_get('python2_bin', '') or 'python')
974 hook_file_grep
= weechat
.hook_process(cmd
, timeout
, 'grep_file_callback', tmpFile
.name
)
977 buffer_create("Searching for '%s' in %s worth of data..." %(pattern_tmpl
,
978 human_readable_size(size
)))
982 # defined here for commodity
983 grep_process_cmd
= """%(python)s -%(bytecode)sc '
984 import sys, cPickle, os
985 sys.path.append("%(script_path)s") # add WeeChat script dir so we can import grep
986 from grep import make_regexp, grep_file, strip_home
989 regexp = make_regexp("%(pattern)s", %(matchcase)s)
992 log_name = strip_home(log, "%(home_dir)s")
993 lines = grep_file(log, %(head)s, %(tail)s, %(after_context)s, %(before_context)s,
994 %(count)s, regexp, "%(hilight)s", %(exact)s, %(invert)s)
996 fd = open("%(filename)s", "wb")
997 cPickle.dump(d, fd, -1)
1000 print >> sys.stderr, e'
1003 grep_stdout
= grep_stderr
= ''
1004 def grep_file_callback(filename
, command
, rc
, stdout
, stderr
):
1005 global hook_file_grep
, grep_stderr
, grep_stdout
1006 global matched_lines
1007 #debug("rc: %s\nstderr: %s\nstdout: %s" %(rc, repr(stderr), repr(stdout)))
1009 grep_stdout
+= stdout
1011 grep_stderr
+= stderr
1014 def set_buffer_error():
1015 grep_buffer
= buffer_create()
1016 title
= weechat
.buffer_get_string(grep_buffer
, 'title')
1017 title
= title
+ ' %serror' %color
_title
1018 weechat
.buffer_set(grep_buffer
, 'title', title
)
1026 elif path
.exists(filename
):
1030 fd
= open(filename
, 'rb')
1031 d
= cPickle
.load(fd
)
1032 matched_lines
.update(d
)
1034 except Exception, e
:
1042 grep_stdout
= grep_stderr
= ''
1043 hook_file_grep
= None
1044 return WEECHAT_RC_OK
1046 def get_grep_file_status():
1047 global search_in_files
, matched_lines
, time_start
1048 elapsed
= now() - time_start
1049 if len(search_in_files
) == 1:
1050 log
= '%s (%s)' %(strip_home(search_in_files
[0]),
1051 human_readable_size(get_size(search_in_files
[0])))
1053 size
= sum(map(get_size
, search_in_files
))
1054 log
= '%s log files (%s)' %(len(search_in_files
), human_readable_size(size
))
1055 return 'Searching in %s, running for %.4f seconds. Interrupt it with "/grep stop" or "stop"' \
1056 ' in grep buffer.' %(log
, elapsed
)
1059 def buffer_update():
1060 """Updates our buffer with new lines."""
1061 global pattern_tmpl
, matched_lines
, pattern
, count
, hilight
, invert
, exact
1064 buffer = buffer_create()
1065 if get_config_boolean('clear_buffer'):
1066 weechat
.buffer_clear(buffer)
1067 matched_lines
.strip_separator() # remove first and last separators of each list
1068 len_total_lines
= len(matched_lines
)
1069 max_lines
= get_config_int('max_lines')
1070 if not count
and len_total_lines
> max_lines
:
1071 weechat
.buffer_clear(buffer)
1073 def _make_summary(log
, lines
, note
):
1074 return '%s matches "%s%s%s"%s in %s%s%s%s' \
1075 %(lines
.matches_count
, color_summary
, pattern_tmpl
, color_info
,
1076 invert
and ' (inverted)' or '',
1077 color_summary
, log
, color_reset
, note
)
1080 make_summary
= lambda log
, lines
: _make_summary(log
, lines
, ' (not shown)')
1082 def make_summary(log
, lines
):
1083 if lines
.stripped_lines
:
1085 note
= ' (last %s lines shown)' %len(lines
)
1087 note
= ' (not shown)'
1090 return _make_summary(log
, lines
, note
)
1092 global weechat_format
1094 # we don't want colors if there's match highlighting
1095 format_line
= lambda s
: '%s %s %s' %split
_line
(s
)
1098 global nick_dict
, weechat_format
1099 date
, nick
, msg
= split_line(s
)
1102 nick
= nick_dict
[nick
]
1105 nick_c
= color_nick(nick
)
1106 nick_dict
[nick
] = nick_c
1108 return '%s%s %s%s %s' %(color_date
, date
, nick
, color_reset
, msg
)
1114 print_line('Search for "%s%s%s"%s in %s%s%s.' %(color_summary
, pattern_tmpl
, color_info
,
1115 invert
and ' (inverted)' or '', color_summary
, matched_lines
, color_reset
),
1117 # print last <max_lines> lines
1118 if matched_lines
.get_matches_count():
1120 # with count we sort by matches lines instead of just lines.
1121 matched_lines_items
= matched_lines
.items_count()
1123 matched_lines_items
= matched_lines
.items()
1125 matched_lines
.get_last_lines(max_lines
)
1126 for log
, lines
in matched_lines_items
:
1127 if lines
.matches_count
:
1131 weechat_format
= True
1136 if line
== linesList
._sep
:
1138 prnt(buffer, context_sep
)
1142 error("Found garbage in log '%s', maybe it's corrupted" %log
)
1143 line
= line
.replace('\x00', '')
1144 prnt_date_tags(buffer, 0, 'no_highlight', format_line(line
))
1147 if count
or get_config_boolean('show_summary'):
1148 summary
= make_summary(log
, lines
)
1149 print_line(summary
, buffer)
1152 if not count
and lines
:
1155 print_line('No matches found.', buffer)
1161 time_total
= time_end
- time_start
1162 # percent of the total time used for grepping
1163 time_grep_pct
= (time_grep
- time_start
)/time_total
*100
1164 #debug('time: %.4f seconds (%.2f%%)' %(time_total, time_grep_pct))
1165 if not count
and len_total_lines
> max_lines
:
1166 note
= ' (last %s lines shown)' %len(matched_lines
)
1169 title
= "'q': close buffer | Search in %s%s%s %s matches%s | pattern \"%s%s%s\"%s %s | %.4f seconds (%.2f%%)" \
1170 %(color_title
, matched_lines
, color_reset
, matched_lines
.get_matches_count(), note
,
1171 color_title
, pattern_tmpl
, color_reset
, invert
and ' (inverted)' or '', format_options(),
1172 time_total
, time_grep_pct
)
1173 weechat
.buffer_set(buffer, 'title', title
)
1175 if get_config_boolean('go_to_buffer'):
1176 weechat
.buffer_set(buffer, 'display', '1')
1178 # free matched_lines so it can be removed from memory
1182 """Splits log's line 's' in 3 parts, date, nick and msg."""
1183 global weechat_format
1184 if weechat_format
and s
.count('\t') >= 2:
1185 date
, nick
, msg
= s
.split('\t', 2) # date, nick, message
1187 # looks like log isn't in weechat's format
1188 weechat_format
= False # incoming lines won't be formatted
1189 date
, nick
, msg
= '', '', s
1192 msg
= msg
.replace('\t', ' ')
1193 return date
, nick
, msg
1195 def print_line(s
, buffer=None, display
=False):
1196 """Prints 's' in script's buffer as 'script_nick'. For displaying search summaries."""
1198 buffer = buffer_create()
1199 say('%s%s' %(color_info
, s
), buffer)
1200 if display
and get_config_boolean('go_to_buffer'):
1201 weechat
.buffer_set(buffer, 'display', '1')
1203 def format_options():
1204 global matchcase
, number
, count
, exact
, hilight
, invert
1205 global tail
, head
, after_context
, before_context
1207 append
= options
.append
1208 insert
= options
.insert
1210 for i
, flag
in enumerate((count
, hilight
, matchcase
, exact
, invert
)):
1215 n
= get_config_int('default_tail_head')
1229 if before_context
and after_context
and (before_context
== after_context
):
1231 append(before_context
)
1235 append(before_context
)
1238 append(after_context
)
1240 s
= ''.join(map(str, options
)).strip()
1241 if s
and s
[0] != '-':
1245 def buffer_create(title
=None):
1246 """Returns our buffer pointer, creates and cleans the buffer if needed."""
1247 buffer = weechat
.buffer_search('python', SCRIPT_NAME
)
1249 buffer = weechat
.buffer_new(SCRIPT_NAME
, 'buffer_input', '', '', '')
1250 weechat
.buffer_set(buffer, 'time_for_each_line', '0')
1251 weechat
.buffer_set(buffer, 'nicklist', '0')
1252 weechat
.buffer_set(buffer, 'title', title
or 'grep output buffer')
1253 weechat
.buffer_set(buffer, 'localvar_set_no_log', '1')
1255 weechat
.buffer_set(buffer, 'title', title
)
1258 def buffer_input(data
, buffer, input_data
):
1259 """Repeats last search with 'input_data' as regexp."""
1261 cmd_grep_stop(buffer, input_data
)
1263 return WEECHAT_RC_OK
1264 if input_data
in ('q', 'Q'):
1265 weechat
.buffer_close(buffer)
1266 return weechat
.WEECHAT_RC_OK
1268 global search_in_buffers
, search_in_files
1271 if pattern
and (search_in_files
or search_in_buffers
):
1272 # check if the buffer pointers are still valid
1273 for pointer
in search_in_buffers
:
1274 infolist
= weechat
.infolist_get('buffer', pointer
, '')
1276 del search_in_buffers
[search_in_buffers
.index(pointer
)]
1277 weechat
.infolist_free(infolist
)
1279 cmd_grep_parsing(input_data
)
1280 except Exception, e
:
1281 error('Argument error, %s' %e, buffer=buffer)
1282 return WEECHAT_RC_OK
1284 show_matching_lines()
1285 except Exception, e
:
1288 error("There isn't any previous search to repeat.", buffer=buffer)
1289 return WEECHAT_RC_OK
1293 """Resets global vars."""
1294 global home_dir
, cache_dir
, nick_dict
1295 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1296 global tail
, head
, after_context
, before_context
1298 head
= tail
= after_context
= before_context
= invert
= False
1299 matchcase
= count
= exact
= False
1300 pattern_tmpl
= pattern
= number
= None
1301 home_dir
= get_home()
1302 cache_dir
= {} # for avoid walking the dir tree more than once per command
1303 nick_dict
= {} # nick cache for don't calculate nick color every time
1305 def cmd_grep_parsing(args
):
1306 """Parses args for /grep and grep input buffer."""
1307 global pattern_tmpl
, pattern
, matchcase
, number
, count
, exact
, hilight
, invert
1308 global tail
, head
, after_context
, before_context
1309 global log_name
, buffer_name
, only_buffers
, all
1310 opts
, args
= getopt
.gnu_getopt(args
.split(), 'cmHeahtivn:bA:B:C:o', ['count', 'matchcase', 'hilight',
1311 'exact', 'all', 'head', 'tail', 'number=', 'buffer', 'after-context=', 'before-context=',
1312 'context=', 'invert', 'only-match'])
1313 #debug(opts, 'opts: '); debug(args, 'args: ')
1315 if args
[0] == 'log':
1317 log_name
= args
.pop(0)
1318 elif args
[0] == 'buffer':
1320 buffer_name
= args
.pop(0)
1322 def tmplReplacer(match
):
1323 """This function will replace templates with regexps"""
1324 s
= match
.groups()[0]
1325 tmpl_args
= s
.split()
1326 tmpl_key
, _
, tmpl_args
= s
.partition(' ')
1328 template
= templates
[tmpl_key
]
1329 if callable(template
):
1330 r
= template(tmpl_args
)
1332 error("Template %s returned empty string "\
1333 "(WeeChat doesn't have enough data)." %t
)
1340 args
= ' '.join(args
) # join pattern for keep spaces
1343 pattern
= _tmplRe
.sub(tmplReplacer
, args
)
1344 debug('Using regexp: %s', pattern
)
1346 raise Exception, 'No pattern for grep the logs.'
1348 def positive_number(opt
, val
):
1359 raise Exception, "argument for %s must be a positive integer." %opt
1361 for opt
, val
in opts
:
1362 opt
= opt
.strip('-')
1363 if opt
in ('c', 'count'):
1365 elif opt
in ('m', 'matchcase'):
1366 matchcase
= not matchcase
1367 elif opt
in ('H', 'hilight'):
1368 # hilight must be always a string!
1372 hilight
= '%s,%s' %(color_hilight
, color_reset
)
1373 # we pass the colors in the variable itself because check_string() must not use
1374 # weechat's module when applying the colors (this is for grep in a hooked process)
1375 elif opt
in ('e', 'exact', 'o', 'only-match'):
1378 elif opt
in ('a', 'all'):
1380 elif opt
in ('h', 'head'):
1383 elif opt
in ('t', 'tail'):
1386 elif opt
in ('b', 'buffer'):
1388 elif opt
in ('n', 'number'):
1389 number
= positive_number(opt
, val
)
1390 elif opt
in ('C', 'context'):
1391 n
= positive_number(opt
, val
)
1394 elif opt
in ('A', 'after-context'):
1395 after_context
= positive_number(opt
, val
)
1396 elif opt
in ('B', 'before-context'):
1397 before_context
= positive_number(opt
, val
)
1398 elif opt
in ('i', 'v', 'invert'):
1402 if number
is not None:
1411 n
= get_config_int('default_tail_head')
1417 def cmd_grep_stop(buffer, args
):
1418 global hook_file_grep
, pattern
, matched_lines
, tmpFile
1421 weechat
.unhook(hook_file_grep
)
1422 hook_file_grep
= None
1423 s
= 'Search for \'%s\' stopped.' %pattern
1425 grep_buffer
= weechat
.buffer_search('python', SCRIPT_NAME
)
1427 weechat
.buffer_set(grep_buffer
, 'title', s
)
1431 say(get_grep_file_status(), buffer)
1434 def cmd_grep(data
, buffer, args
):
1435 """Search in buffers and logs."""
1436 global pattern
, matchcase
, head
, tail
, number
, count
, exact
, hilight
1438 cmd_grep_stop(buffer, args
)
1440 return WEECHAT_RC_OK
1443 weechat
.command('', '/help %s' %SCRIPT_COMMAND
)
1444 return WEECHAT_RC_OK
1447 global log_name
, buffer_name
, only_buffers
, all
1448 log_name
= buffer_name
= ''
1449 only_buffers
= all
= False
1453 cmd_grep_parsing(args
)
1454 except Exception, e
:
1455 error('Argument error, %s' %e)
1456 return WEECHAT_RC_OK
1459 log_file
= search_buffer
= None
1461 log_file
= get_file_by_pattern(log_name
, all
)
1463 error("Couldn't find any log for %s. Try /logs" %log_name
)
1464 return WEECHAT_RC_OK
1466 search_buffer
= get_all_buffers()
1468 search_buffer
= get_buffer_by_name(buffer_name
)
1469 if not search_buffer
:
1470 # there's no buffer, try in the logs
1471 log_file
= get_file_by_name(buffer_name
)
1473 error("Logs or buffer for '%s' not found." %buffer_name
)
1474 return WEECHAT_RC_OK
1476 search_buffer
= [search_buffer
]
1478 search_buffer
= [buffer]
1481 global search_in_files
, search_in_buffers
1482 search_in_files
= []
1483 search_in_buffers
= []
1485 search_in_files
= log_file
1486 elif not only_buffers
:
1487 #debug(search_buffer)
1488 for pointer
in search_buffer
:
1489 log
= get_file_by_buffer(pointer
)
1490 #debug('buffer %s log %s' %(pointer, log))
1492 search_in_files
.append(log
)
1494 search_in_buffers
.append(pointer
)
1496 search_in_buffers
= search_buffer
1500 show_matching_lines()
1501 except Exception, e
:
1503 return WEECHAT_RC_OK
1505 def cmd_logs(data
, buffer, args
):
1506 """List files in Weechat's log dir."""
1509 sort_by_size
= False
1513 opts
, args
= getopt
.gnu_getopt(args
.split(), 's', ['size'])
1516 for opt
, var
in opts
:
1517 opt
= opt
.strip('-')
1518 if opt
in ('size', 's'):
1520 except Exception, e
:
1521 error('Argument error, %s' %e)
1522 return WEECHAT_RC_OK
1524 # is there's a filter, filter_excludes should be False
1525 file_list
= dir_list(home_dir
, filter, filter_excludes
=not filter)
1527 file_list
.sort(key
=get_size
)
1531 file_sizes
= map(lambda x
: human_readable_size(get_size(x
)), file_list
)
1532 # calculate column lenght
1537 column_len
= len(bigest
) + 3
1541 buffer = buffer_create()
1542 if get_config_boolean('clear_buffer'):
1543 weechat
.buffer_clear(buffer)
1544 file_list
= zip(file_list
, file_sizes
)
1545 msg
= 'Found %s logs.' %len(file_list
)
1547 print_line(msg
, buffer, display
=True)
1548 for file, size
in file_list
:
1549 separator
= column_len
and '.'*(column_len
- len(file))
1550 prnt(buffer, '%s %s %s' %(strip_home(file), separator
, size
))
1552 print_line(msg
, buffer)
1553 return WEECHAT_RC_OK
1557 def completion_log_files(data
, completion_item
, buffer, completion
):
1558 #debug('completion: %s' %', '.join((data, completion_item, buffer, completion)))
1561 completion_list_add
= weechat
.hook_completion_list_add
1562 WEECHAT_LIST_POS_END
= weechat
.WEECHAT_LIST_POS_END
1563 for log
in dir_list(home_dir
):
1564 completion_list_add(completion
, log
[l
:], 0, WEECHAT_LIST_POS_END
)
1565 return WEECHAT_RC_OK
1567 def completion_grep_args(data
, completion_item
, buffer, completion
):
1568 for arg
in ('count', 'all', 'matchcase', 'hilight', 'exact', 'head', 'tail', 'number', 'buffer',
1569 'after-context', 'before-context', 'context', 'invert', 'only-match'):
1570 weechat
.hook_completion_list_add(completion
, '--' + arg
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1571 for tmpl
in templates
:
1572 weechat
.hook_completion_list_add(completion
, '%{' + tmpl
, 0, weechat
.WEECHAT_LIST_POS_SORT
)
1573 return WEECHAT_RC_OK
1577 # template placeholder
1578 _tmplRe
= re
.compile(r
'%\{(\w+.*?)(?:\}|$)')
1579 # will match 999.999.999.999 but I don't care
1580 ipAddress
= r
'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
1581 domain
= r
'[\w-]{2,}(?:\.[\w-]{2,})*\.[a-z]{2,}'
1582 url
= r
'\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?' % (domain
, ipAddress
)
1584 def make_url_regexp(args
):
1585 #debug('make url: %s', args)
1587 words
= r
'(?:%s)' %'|'.join(map(re
.escape
, args
.split()))
1588 return r
'(?:\w+://|www\.)[^\s]*%s[^\s]*(?:/[^\])>\s]*)?' %words
1592 def make_simple_regexp(pattern
):
1605 'url': make_url_regexp
,
1606 'escape': lambda s
: re
.escape(s
),
1607 'simple': make_simple_regexp
,
1612 def delete_bytecode():
1614 bytecode
= path
.join(script_path
, SCRIPT_NAME
+ '.pyc')
1615 if path
.isfile(bytecode
):
1617 return WEECHAT_RC_OK
1619 if __name__
== '__main__' and import_ok
and \
1620 weechat
.register(SCRIPT_NAME
, SCRIPT_AUTHOR
, SCRIPT_VERSION
, SCRIPT_LICENSE
, \
1621 SCRIPT_DESC
, 'delete_bytecode', ''):
1622 home_dir
= get_home()
1624 # for import ourselves
1626 script_path
= path
.dirname(__file__
)
1627 sys
.path
.append(script_path
)
1630 # check python version
1633 if sys
.version_info
> (2, 6):
1639 weechat
.hook_command(SCRIPT_COMMAND
, cmd_grep
.__doc
__,
1640 "[log <file> | buffer <name> | stop] [-a|--all] [-b|--buffer] [-c|--count] [-m|--matchcase] "
1641 "[-H|--hilight] [-o|--only-match] [-i|-v|--invert] [(-h|--head)|(-t|--tail) [-n|--number <n>]] "
1642 "[-A|--after-context <n>] [-B|--before-context <n>] [-C|--context <n> ] <expression>",
1645 log <file>: Search in one log that matches <file> in the logger path.
1646 Use '*' and '?' as wildcards.
1647 buffer <name>: Search in buffer <name>, if there's no buffer with <name> it will
1648 try to search for a log file.
1649 stop: Stops a currently running search.
1650 -a --all: Search in all open buffers.
1651 If used with 'log <file>' search in all logs that matches <file>.
1652 -b --buffer: Search only in buffers, not in file logs.
1653 -c --count: Just count the number of matched lines instead of showing them.
1654 -m --matchcase: Don't do case insensitive search.
1655 -H --hilight: Colour exact matches in output buffer.
1656 -o --only-match: Print only the matching part of the line (unique matches).
1657 -v -i --invert: Print lines that don't match the regular expression.
1658 -t --tail: Print the last 10 matching lines.
1659 -h --head: Print the first 10 matching lines.
1660 -n --number <n>: Overrides default number of lines for --tail or --head.
1661 -A --after-context <n>: Shows <n> lines of trailing context after matching lines.
1662 -B --before-context <n>: Shows <n> lines of leading context before matching lines.
1663 -C --context <n>: Same as using both --after-context and --before-context simultaneously.
1664 <expression>: Expression to search.
1667 Input line accepts most arguments of /grep, it'll repeat last search using the new
1668 arguments provided. You can't search in different logs from the buffer's input.
1669 Boolean arguments like --count, --tail, --head, --hilight, ... are toggleable
1671 Python regular expression syntax:
1672 See http://docs.python.org/lib/re-syntax.html
1675 %{url [text]}: Matches anything like an url, or an url with text.
1676 %{ip}: Matches anything that looks like an ip.
1677 %{domain}: Matches anything like a domain.
1678 %{escape text}: Escapes text in pattern.
1679 %{simple pattern}: Converts a pattern with '*' and '?' wildcards into a regexp.
1682 Search for urls with the word 'weechat' said by 'nick'
1683 /grep nick\\t.*%{url weechat}
1684 Search for '*.*' string
1687 # completion template
1688 "buffer %(buffers_names) %(grep_arguments)|%*"
1689 "||log %(grep_log_files) %(grep_arguments)|%*"
1691 "||%(grep_arguments)|%*",
1693 weechat
.hook_command('logs', cmd_logs
.__doc
__, "[-s|--size] [<filter>]",
1694 "-s --size: Sort logs by size.\n"
1695 " <filter>: Only show logs that match <filter>. Use '*' and '?' as wildcards.", '--size', 'cmd_logs', '')
1697 weechat
.hook_completion('grep_log_files', "list of log files",
1698 'completion_log_files', '')
1699 weechat
.hook_completion('grep_arguments', "list of arguments",
1700 'completion_grep_args', '')
1703 for opt
, val
in settings
.iteritems():
1704 if not weechat
.config_is_set_plugin(opt
):
1705 weechat
.config_set_plugin(opt
, val
)
1708 color_date
= weechat
.color('brown')
1709 color_info
= weechat
.color('cyan')
1710 color_hilight
= weechat
.color('lightred')
1711 color_reset
= weechat
.color('reset')
1712 color_title
= weechat
.color('yellow')
1713 color_summary
= weechat
.color('lightcyan')
1714 color_delimiter
= weechat
.color('chat_delimiters')
1715 color_script_nick
= weechat
.color('chat_nick')
1718 script_nick
= '%s[%s%s%s]%s' %(color_delimiter
, color_script_nick
, SCRIPT_NAME
, color_delimiter
,
1720 script_nick_nocolor
= '[%s]' %SCRIPT_NAME
1721 # paragraph separator when using context options
1722 context_sep
= '%s\t%s--' %(script_nick
, color_info
)
1724 # -------------------------------------------------------------------------
1727 if weechat
.config_get_plugin('debug'):
1729 # custom debug module I use, allows me to inspect script's objects.
1731 debug
= pybuffer
.debugBuffer(globals(), '%s_debug' % SCRIPT_NAME
)
1733 def debug(s
, *args
):
1734 if not isinstance(s
, basestring
):
1738 prnt('', '%s\t%s' %(script_nick
, s
))
1743 # vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=100: