update weechat perl and python plugins

This commit is contained in:
creme 2020-01-30 10:42:14 +01:00
parent e11d583d8c
commit 4b338c0682
Signed by untrusted user: creme
GPG Key ID: C147C3B7FBDF08D0
6 changed files with 1183 additions and 883 deletions

View File

@ -1,6 +1,6 @@
#
# highmon.pl - Highlight Monitoring for weechat 0.3.0
# Version 2.5
# Version 2.6
#
# Add 'Highlight Monitor' buffer/bar to log all highlights in one spot
#
@ -73,6 +73,8 @@
# Bugs and feature requests at: https://github.com/KenjiE20/highmon
# History:
# 2019-05-13, HubbeKing <hubbe128@gmail.com>
# v2.6: -add: send "logger_backlog" signal on buffer open if logging is enabled
# 2014-08-16, KenjiE20 <longbow@longbowslair.co.uk>:
# v2.5: -add: clearbar command to clear bar output
# -add: firstrun output prompt to check the help text for set up hints as they were being missed
@ -306,7 +308,7 @@ sub highmon_buffer_open
# Turn off notify, highlights
if ($highmon_buffer ne "")
{
if (weechat::config_get_plugin("hotlist_show" eq "off"))
if (weechat::config_get_plugin("hotlist_show") eq "off")
{
weechat::buffer_set($highmon_buffer, "notify", "0");
}
@ -317,6 +319,11 @@ sub highmon_buffer_open
{
weechat::buffer_set($highmon_buffer, "localvar_set_no_log", "1");
}
# send "logger_backlog" signal if logging is enabled to display backlog
if (weechat::config_get_plugin("logging") eq "on")
{
weechat::hook_signal_send("logger_backlog", weechat::WEECHAT_HOOK_SIGNAL_POINTER, $highmon_buffer)
}
}
return weechat::WEECHAT_RC_OK;
}
@ -1124,7 +1131,7 @@ sub format_buffer_name
}
# Check result of register, and attempt to behave in a sane manner
if (!weechat::register("highmon", "KenjiE20", "2.5", "GPL3", "Highlight Monitor", "", ""))
if (!weechat::register("highmon", "KenjiE20", "2.6", "GPL3", "Highlight Monitor", "", ""))
{
# Double load
weechat::print ("", "\tHighmon is already loaded");

View File

@ -1,6 +1,6 @@
#
# Copyright (C) 2008-2014 Sebastien Helleu <flashcode@flashtux.org>
# Copyright (C) 2010-2014 Nils Görs <weechatter@arcor.de>
# Copyright (C) 2008-2017 Sebastien Helleu <flashcode@flashtux.org>
# Copyright (C) 2010-2017 Nils Görs <weechatter@arcor.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@ -19,6 +19,21 @@
#
# History:
#
# 2017-04-14, nils_2 <freenode.#weechat>
# version 4.3: add option "use_color" (https://github.com/weechat/scripts/issues/93)
# 2016-07-08, nils_2 <weechatter@arcor.de>
# version 4.2: add diff function
# 2016-02-06, Sebastien Helleu <flashcode@flashtux.org>:
# version 4.1: remove debug print
# 2015-12-24, Sebastien Helleu <flashcode@flashtux.org>:
# version 4.0: add support of parent options (inherited values in irc servers)
# with WeeChat >= 1.4
# 2015-05-16, Sebastien Helleu <flashcode@flashtux.org>:
# version 3.9: fix cursor position when editing an option with WeeChat >= 1.2
# 2015-05-02, arza <arza@arza.us>:
# version 3.8: don't append "null" to /set when setting an undefined setting
# 2015-05-01, nils_2 <weechatter@arcor.de>:
# version 3.7: fix two perl warnings (reported by t3chguy)
# 2014-09-30, arza <arza@arza.us>:
# version 3.6: fix current line counter when options aren't found
# 2014-06-03, nils_2 <weechatter@arcor.de>:
@ -117,7 +132,7 @@
use strict;
my $PRGNAME = "iset";
my $VERSION = "3.6";
my $VERSION = "4.3";
my $DESCR = "Interactive Set for configuration options";
my $AUTHOR = "Sebastien Helleu <flashcode\@flashtux.org>";
my $LICENSE = "GPL3";
@ -129,9 +144,11 @@ my $iset_buffer = "";
my $wee_version_number = 0;
my @iset_focus = ();
my @options_names = ();
my @options_parent_names = ();
my @options_types = ();
my @options_values = ();
my @options_default_values = ();
my @options_parent_values = ();
my @options_is_null = ();
my $option_max_length = 0;
my $current_line = 0;
@ -139,7 +156,7 @@ my $filter = "*";
my $description = "";
my $options_name_copy = "";
my $iset_filter_title = "";
# search modes: 0 = index() on value, 1 = grep() on value, 2 = grep() on option, 3 = grep on option & value
# search modes: 0 = index() on value, 1 = grep() on value, 2 = grep() on option, 3 = grep on option & value, 4 = diff all, 5 = diff parts
my $search_mode = 2;
my $search_value = "";
my $help_text_keys = "alt + space: toggle, +/-: increase/decrease, enter: change, ir: reset, iu: unset, v: toggle help bar";
@ -189,6 +206,12 @@ sub iset_title
$filter = "*" if ($filter eq "");
$show_filter = $filter;
}
elsif ($search_mode == 4 or $search_mode == 5)
{
$iset_filter_title = "diff: ";
$show_filter = "all";
$show_filter = $search_value if $search_mode == 5;
}
elsif ($search_mode eq 3)
{
$iset_filter_title = "(option) ";
@ -237,6 +260,10 @@ sub iset_create_filter
sub iset_buffer_input
{
my ($data, $buffer, $string) = ($_[0], $_[1], $_[2]);
# string begins with space?
return weechat::WEECHAT_RC_OK if (substr($string, 0, 1 ) eq " ");
if ($string eq "q")
{
weechat::buffer_close($buffer);
@ -257,6 +284,23 @@ sub iset_buffer_input
weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value);
}
}
# show all diff values
elsif ($string eq "d")
{
$search_mode = 4;
# iset_title();
iset_create_filter("*");
iset_get_options("*");
}
elsif ( $array_count >= 2 and $cmd_array[0] eq "d")
{
$search_mode = 5;
$search_value = substr($cmd_array[1], 0); # cut value_search_char
$search_value = substr($cmd_array[2], 0) if ( $array_count > 2); # cut value_search_char
iset_create_filter($search_value);
iset_get_options($search_value);
}
else
{
$search_mode = 2;
@ -274,7 +318,8 @@ sub iset_buffer_input
{
iset_create_filter($string);
iset_get_options($search_value);
}else
}
else
{
iset_create_filter($string);
iset_get_options("");
@ -343,9 +388,11 @@ sub iset_get_options
$search_value = $var_value;
@iset_focus = ();
@options_names = ();
@options_parent_names = ();
@options_types = ();
@options_values = ();
@options_default_values = ();
@options_parent_values = ();
@options_is_null = ();
$option_max_length = 0;
my %options_internal = ();
@ -361,19 +408,44 @@ sub iset_get_options
{
$key = sprintf("%08d", $i);
my $name = weechat::infolist_string($infolist, "full_name");
my $parent_name = weechat::infolist_string($infolist, "parent_name");
next if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 0 and index ($name, "plugins.desc.") != -1);
my $type = weechat::infolist_string($infolist, "type");
my $value = weechat::infolist_string($infolist, "value");
my $default_value = weechat::infolist_string($infolist, "default_value");
my $parent_value;
if ($parent_name && (($wee_version_number < 0x00040300) || (weechat::infolist_search_var($infolist, "parent_value"))))
{
$parent_value = weechat::infolist_string($infolist, "parent_value");
}
my $is_null = weechat::infolist_integer($infolist, "value_is_null");
if ($search_mode == 3)
{
my $value = weechat::infolist_string($infolist, "value");
if ( grep /\Q$var_value/,lc($value) )
{
$options_internal{$name}{"parent_name"} = $parent_name;
$options_internal{$name}{"type"} = $type;
$options_internal{$name}{"value"} = $value;
$options_internal{$name}{"default_value"} = $default_value;
$options_internal{$name}{"parent_value"} = $parent_value;
$options_internal{$name}{"is_null"} = $is_null;
$option_max_length = length($name) if (length($name) > $option_max_length);
$iset_struct{$key} = $options_internal{$name};
push(@iset_focus, $iset_struct{$key});
}
}
# search for diff?
elsif ( $search_mode == 4 or $search_mode == 5)
{
if ($value ne $default_value )
{
$options_internal{$name}{"parent_name"} = $parent_name;
$options_internal{$name}{"type"} = $type;
$options_internal{$name}{"value"} = $value;
$options_internal{$name}{"default_value"} = $default_value;
$options_internal{$name}{"parent_value"} = $parent_value;
$options_internal{$name}{"is_null"} = $is_null;
$option_max_length = length($name) if (length($name) > $option_max_length);
$iset_struct{$key} = $options_internal{$name};
@ -382,9 +454,11 @@ sub iset_get_options
}
else
{
$options_internal{$name}{"parent_name"} = $parent_name;
$options_internal{$name}{"type"} = $type;
$options_internal{$name}{"value"} = $value;
$options_internal{$name}{"default_value"} = $default_value;
$options_internal{$name}{"parent_value"} = $parent_value;
$options_internal{$name}{"is_null"} = $is_null;
$option_max_length = length($name) if (length($name) > $option_max_length);
$iset_struct{$key} = $options_internal{$name};
@ -397,9 +471,11 @@ sub iset_get_options
foreach my $name (sort keys %options_internal)
{
push(@options_names, $name);
push(@options_parent_names, $options_internal{$name}{"parent_name"});
push(@options_types, $options_internal{$name}{"type"});
push(@options_values, $options_internal{$name}{"value"});
push(@options_default_values, $options_internal{$name}{"default_value"});
push(@options_parent_values, $options_internal{$name}{"parent_value"});
push(@options_is_null, $options_internal{$name}{"is_null"});
}
}
@ -422,9 +498,11 @@ sub iset_search_values
{
my ($var_value,$search_mode) = ($_[0],$_[1]);
@options_names = ();
@options_parent_names = ();
@options_types = ();
@options_values = ();
@options_default_values = ();
@options_parent_values = ();
@options_is_null = ();
$option_max_length = 0;
my %options_internal = ();
@ -433,18 +511,26 @@ sub iset_search_values
while (weechat::infolist_next($infolist))
{
my $name = weechat::infolist_string($infolist, "full_name");
my $parent_name = weechat::infolist_string($infolist, "parent_name");
next if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 0 and index ($name, "plugins.desc.") != -1);
my $type = weechat::infolist_string($infolist, "type");
my $is_null = weechat::infolist_integer($infolist, "value_is_null");
my $value = weechat::infolist_string($infolist, "value");
my $default_value = weechat::infolist_string($infolist, "default_value");
my $parent_value;
if ($parent_name && (($wee_version_number < 0x00040300) || (weechat::infolist_search_var($infolist, "parent_value"))))
{
$parent_value = weechat::infolist_string($infolist, "parent_value");
}
if ($search_mode)
{
if ( grep /\Q$var_value/,lc($value) )
{
$options_internal{$name}{"parent_name"} = $parent_name;
$options_internal{$name}{"type"} = $type;
$options_internal{$name}{"value"} = $value;
$options_internal{$name}{"default_value"} = $default_value;
$options_internal{$name}{"parent_value"} = $parent_value;
$options_internal{$name}{"is_null"} = $is_null;
$option_max_length = length($name) if (length($name) > $option_max_length);
}
@ -454,9 +540,11 @@ sub iset_search_values
# if ($value =~ /\Q$var_value/si)
if (lc($value) eq $var_value)
{
$options_internal{$name}{"parent_name"} = $parent_name;
$options_internal{$name}{"type"} = $type;
$options_internal{$name}{"value"} = $value;
$options_internal{$name}{"default_value"} = $default_value;
$options_internal{$name}{"parent_value"} = $parent_value;
$options_internal{$name}{"is_null"} = $is_null;
$option_max_length = length($name) if (length($name) > $option_max_length);
}
@ -467,9 +555,11 @@ sub iset_search_values
foreach my $name (sort keys %options_internal)
{
push(@options_names, $name);
push(@options_parent_names, $options_internal{$name}{"parent_name"});
push(@options_types, $options_internal{$name}{"type"});
push(@options_values, $options_internal{$name}{"value"});
push(@options_default_values, $options_internal{$name}{"default_value"});
push(@options_parent_values, $options_internal{$name}{"parent_value"});
push(@options_is_null, $options_internal{$name}{"is_null"});
}
}
@ -498,9 +588,11 @@ sub iset_refresh_line
my $color1 = weechat::color(weechat::config_color($options_iset{"color_option"}));
my $color2 = weechat::color(weechat::config_color($options_iset{"color_type"}));
my $color3 = "";
my $color4 = "";
if ($options_is_null[$y])
{
$color3 = weechat::color(weechat::config_color($options_iset{"color_value_undef"}));
$color4 = weechat::color(weechat::config_color($options_iset{"color_value"}));
}
elsif ($options_values[$y] ne $options_default_values[$y])
{
@ -517,6 +609,7 @@ sub iset_refresh_line
if ($options_is_null[$y])
{
$color3 = weechat::color(weechat::config_color($options_iset{"color_value_undef_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"}));
$color4 = weechat::color(weechat::config_color($options_iset{"color_value_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"}));
}
elsif ($options_values[$y] ne $options_default_values[$y])
{
@ -528,7 +621,27 @@ sub iset_refresh_line
}
}
my $value = $options_values[$y];
$value = "(undef)" if ($options_is_null[$y]);
if (weechat::config_boolean($options_iset{"use_color"}) == 1 and $options_types[$y] eq "color")
{
$value = weechat::color($options_values[$y]) . $options_values[$y];
}
if ($options_is_null[$y])
{
$value = "null";
if ($options_parent_names[$y])
{
if (defined $options_parent_values[$y])
{
my $around_parent = "";
$around_parent = "\"" if ($options_types[$y] eq "string");
$value .= $color1." -> ".$color4.$around_parent.$options_parent_values[$y].$around_parent;
}
else
{
$value .= $color1." -> ".$color3."null";
}
}
}
my $strline = sprintf($format,
$color1, $options_names[$y], $padding,
$color2, $options_types[$y],
@ -702,6 +815,39 @@ sub iset_get_option_name_index
return -1;
}
sub iset_refresh_option
{
my $option_name = $_[0];
my $index = $_[1];
my $infolist = weechat::infolist_get("option", "", $option_name);
if ($infolist)
{
weechat::infolist_next($infolist);
if (weechat::infolist_fields($infolist))
{
$options_parent_names[$index] = weechat::infolist_string($infolist, "parent_name");
$options_types[$index] = weechat::infolist_string($infolist, "type");
$options_values[$index] = weechat::infolist_string($infolist, "value");
$options_default_values[$index] = weechat::infolist_string($infolist, "default_value");
$options_is_null[$index] = weechat::infolist_integer($infolist, "value_is_null");
$options_parent_values[$index] = undef;
if ($options_parent_names[$index]
&& (($wee_version_number < 0x00040300) || (weechat::infolist_search_var($infolist, "parent_value"))))
{
$options_parent_values[$index] = weechat::infolist_string($infolist, "parent_value");
}
iset_refresh_line($index);
iset_title() if ($option_name eq "iset.look.show_current_line");
}
else
{
iset_full_refresh(1); # if not found, refresh fully without clearing buffer
weechat::print_y($iset_buffer, $#options_names + 1, "");
}
weechat::infolist_free($infolist);
}
}
sub iset_config_cb
{
my ($data, $option_name, $value) = ($_[0], $_[1], $_[2]);
@ -714,25 +860,14 @@ sub iset_config_cb
if ($index >= 0)
{
# refresh info about changed option
my $infolist = weechat::infolist_get("option", "", $option_name);
if ($infolist)
iset_refresh_option($option_name, $index);
# refresh any other option having this changed option as parent
foreach my $i (0 .. $#options_names)
{
weechat::infolist_next($infolist);
if (weechat::infolist_fields($infolist))
if ($options_parent_names[$i] eq $option_name)
{
$options_types[$index] = weechat::infolist_string($infolist, "type");
$options_values[$index] = weechat::infolist_string($infolist, "value");
$options_default_values[$index] = weechat::infolist_string($infolist, "default_value");
$options_is_null[$index] = weechat::infolist_integer($infolist, "value_is_null");
iset_refresh_line($index);
iset_title() if ($option_name eq "iset.look.show_current_line");
iset_refresh_option($options_names[$i], $i);
}
else
{
iset_full_refresh(1); # if not found, refresh fully without clearing buffer
weechat::print_y($iset_buffer, $#options_names + 1, "");
}
weechat::infolist_free($infolist);
}
}
else
@ -807,20 +942,37 @@ sub iset_cmd_cb
{
# f/s option =value
# option =value
$search_mode = 2;
$search_mode = 2; # grep on option
if ( $array_count >= 2 and $cmd_array[0] ne "f" or $cmd_array[0] ne "s")
{
if ( defined $cmd_array[1] and substr($cmd_array[1], 0, 1) eq weechat::config_string($options_iset{"value_search_char"})
or defined $cmd_array[2] and substr($cmd_array[2], 0, 1) eq weechat::config_string($options_iset{"value_search_char"}) )
{
$search_mode = 3;
$search_mode = 3; # grep on option and value
$search_value = substr($cmd_array[1], 1); # cut value_search_char
$search_value = substr($cmd_array[2], 1) if ( $array_count > 2); # cut value_search_char
}
}
# show all diff values
if ( $args eq "d")
{
$search_mode = 4;
$search_value = "*";
$args = $search_value;
}
if ( $array_count >= 2 and $cmd_array[0] eq "d")
{
$search_mode = 5;
$search_value = substr($cmd_array[1], 0); # cut value_search_char
$search_value = substr($cmd_array[2], 0) if ( $array_count > 2); # cut value_search_char
$args = $search_value;
}
iset_create_filter($args);
$filter_set = 1;
my $ptrbuf = weechat::buffer_search($LANG, $PRGNAME);
if ($ptrbuf eq "")
{
iset_init();
@ -976,22 +1128,34 @@ sub iset_cmd_cb
my $value = $options_values[$current_line];
if ($options_is_null[$current_line])
{
$value = "null";
$value = "";
}
else
{
$quote = "\"" if ($options_types[$current_line] eq "string");
}
my $set_command = "/set";
$set_command = "/mute " . $set_command if (weechat::config_boolean($options_iset{"use_mute"}) == 1);
$value = " ".$quote.$value.$quote if ($value ne "" or $quote ne "");
weechat::buffer_set($iset_buffer, "input", $set_command." ".$options_names[$current_line]." ".$quote.$value.$quote);
weechat::command($iset_buffer, "/input move_beginning_of_line");
weechat::command($iset_buffer, "/input move_next_word");
weechat::command($iset_buffer, "/input move_next_word");
weechat::command($iset_buffer, "/input move_next_word") if (weechat::config_boolean($options_iset{"use_mute"}) == 1);
weechat::command($iset_buffer, "/input move_next_char");
weechat::command($iset_buffer, "/input move_next_char") if ($quote ne "");
my $set_command = "/set";
my $start_index = 5;
if (weechat::config_boolean($options_iset{"use_mute"}) == 1)
{
$set_command = "/mute ".$set_command;
$start_index += 11;
}
$set_command = $set_command." ".$options_names[$current_line].$value;
my $pos_space = index($set_command, " ", $start_index);
if ($pos_space < 0)
{
$pos_space = 9999;
}
else
{
$pos_space = $pos_space + 1;
$pos_space = $pos_space + 1 if ($quote ne "");
}
weechat::buffer_set($iset_buffer, "input", $set_command);
weechat::buffer_set($iset_buffer, "input_pos", "".$pos_space);
}
}
weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1);
@ -1162,6 +1326,8 @@ sub iset_hsignal_mouse_cb
{
my ($data, $signal, %hash) = ($_[0], $_[1], %{$_[2]});
return weechat::WEECHAT_RC_OK unless (@options_types);
if ($hash{"_buffer_name"} eq $PRGNAME && ($hash{"_buffer_plugin"} eq $LANG))
{
if ($hash{"_key"} eq "button1")
@ -1349,6 +1515,10 @@ sub iset_config_init
$iset_config_file, $section_look,
"use_mute", "boolean", "/mute command will be used in input bar", "", 0, 0,
"off", "off", 0, "", "", "", "", "", "");
$options_iset{"use_color"} = weechat::config_new_option(
$iset_config_file, $section_look,
"use_color", "boolean", "display the color value in the corresponding color", "", 0, 0,
"off", "off", 0, "", "", "full_refresh_cb", "", "", "");
}
sub iset_config_reload_cb
@ -1397,7 +1567,8 @@ $wee_version_number = weechat::info_get("version_number", "") || 0;
iset_config_init();
iset_config_read();
weechat::hook_command($PRGNAME, "Interactive set", "f <file> || s <section> || [=][=]<text>",
weechat::hook_command($PRGNAME, "Interactive set", "d <text> || f <file> || s <section> || [=][=]<text>",
"d <text> : show only changed options\n".
"f file : show options for a file\n".
"s section: show options for a section\n".
"text : show options with 'text' in name\n".
@ -1418,6 +1589,7 @@ weechat::hook_command($PRGNAME, "Interactive set", "f <file> || s <section> || [
"text,enter : set a new filter using command line (use '*' to see all options)\n".
"alt+'v' : toggle help bar on/off\n".
"alt+'p' : toggle option \"show_plugin_description\" on/off\n".
"q : as input in iset buffer to close it\n".
"\n".
"Mouse actions:\n".
"wheel up/down : move cursor up/down\n".
@ -1426,8 +1598,8 @@ weechat::hook_command($PRGNAME, "Interactive set", "f <file> || s <section> || [
"right button + drag left/right: increase/decrease value (for integer or color)\n".
"\n".
"Examples:\n".
" show options for file 'weechat'\n".
" /iset f weechat\n".
" show changed options in 'aspell' plugin\n".
" /iset d aspell\n".
" show options for file 'irc'\n".
" /iset f irc\n".
" show options for section 'look'\n".

View File

@ -43,6 +43,15 @@
# 2014-05-22, Nathaniel Wesley Filardo <PADEBR2M2JIQN02N9OO5JM0CTN8K689P@cmx.ietfng.org>
# version 0.2.5: Fix keyed channel support
#
# 2016-01-13, The fox in the shell <KellerFuchs@hashbang.sh>
# version 0.2.6: Support keeping chan list as secured data
#
# 2018-08-09, Julien Palard <julien@palard.fr>
# version 0.3.0: Support for Python 3
#
# 2019-09-28, fructose
# version 0.3.1: Error on invalid arguments
#
# @TODO: add options to ignore certain buffers
# @TODO: maybe add an option to enable autosaving on part/join messages
@ -51,7 +60,7 @@ import re
SCRIPT_NAME = "autojoin"
SCRIPT_AUTHOR = "xt <xt@bash.no>"
SCRIPT_VERSION = "0.2.5"
SCRIPT_VERSION = "0.3.1"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Configure autojoin for all servers according to currently joined channels"
SCRIPT_COMMAND = "autojoin"
@ -80,6 +89,7 @@ for option, default_value in settings.items():
if w.config_get_plugin(option) == "":
w.config_set_plugin(option, default_value)
def autosave_channels_on_quit(signal, callback, callback_data):
''' Autojoin current channels '''
if w.config_get_plugin(option) != "on":
@ -88,10 +98,8 @@ def autosave_channels_on_quit(signal, callback, callback_data):
items = find_channels()
# print/execute commands
for server, channels in items.iteritems():
channels = channels.rstrip(',')
command = "/set irc.server.%s.autojoin '%s'" % (server, channels)
w.command('', command)
for server, channels in items.items():
process_server(server, channels)
return w.WEECHAT_RC_OK
@ -104,44 +112,66 @@ def autosave_channels_on_activity(signal, callback, callback_data):
items = find_channels()
# print/execute commands
for server, channels in items.iteritems():
for server, channels in items.items():
nick = w.info_get('irc_nick', server)
pattern = "^:%s!.*(JOIN|PART) :?(#[^ ]*)( :.*$)?" % nick
match = re.match(pattern, callback_data)
if match: # check if nick is my nick. In that case: save
channel = match.group(2)
channels = channels.rstrip(',')
command = "/set irc.server.%s.autojoin '%s'" % (server, channels)
w.command('', command)
process_server(server, channels)
else: # someone else: ignore
continue
return w.WEECHAT_RC_OK
def autojoin_cb(data, buffer, args):
"""Old behaviour: doesn't save empty channel list"""
"""In fact should also save open buffers with a /part'ed channel"""
"""But I can't believe somebody would want that behaviour"""
if args == '--run':
run = True
elif args != '':
w.prnt('', 'Unexpected argument: %s' % args)
return w.WEECHAT_RC_ERROR
else:
run = False
# Old behaviour: doesn't save empty channel list
# In fact should also save open buffers with a /part'ed channel
# But I can't believe somebody would want that behaviour
items = find_channels()
# print/execute commands
for server, channels in items.iteritems():
for server, channels in items.items():
process_server(server, channels, run)
return w.WEECHAT_RC_OK
def process_server(server, channels, run=True):
option = "irc.server.%s.autojoin" % server
channels = channels.rstrip(',')
oldchans = w.config_string(w.config_get(option))
if not channels: # empty channel list
continue
command = '/set irc.server.%s.autojoin %s' % (server, channels)
if args == '--run':
return
# Note: re already caches the result of regexp compilation
sec = re.match('^\${sec\.data\.(.*)}$', oldchans)
if sec:
secvar = sec.group(1)
command = "/secure set %s %s" % (secvar, channels)
else:
command = "/set irc.server.%s.autojoin '%s'" % (server, channels)
if run:
w.command('', command)
else:
w.prnt('', command)
return w.WEECHAT_RC_OK
def find_channels():
"""Return list of servers and channels"""
#@TODO: make it return a dict with more options like "nicks_count etc."
# TODO: make it return a dict with more options like "nicks_count etc."
items = {}
infolist = w.infolist_get('irc_server', '', '')
# populate servers
@ -174,4 +204,3 @@ def find_channels():
w.infolist_free(infolist)
return items

View File

@ -53,6 +53,9 @@
# It can be used for force or disable background process, using '0' forces to always grep in
# background, while using '' (empty string) will disable it.
#
# * plugins.var.python.grep.timeout_secs:
# Timeout (in seconds) for background grepping.
#
# * plugins.var.python.grep.default_tail_head:
# Config option for define default number of lines returned when using --head or --tail options.
# Can be overriden in the command with --number option.
@ -66,6 +69,28 @@
#
# History:
#
# 2019-06-30, dabbill <dabbill@gmail.com>
# and Sébastien Helleu <flashcode@flashtux.org>
# version 0.8.2: make script compatible with Python 3
#
# 2018-04-10, Sébastien Helleu <flashcode@flashtux.org>
# version 0.8.1: fix infolist_time for WeeChat >= 2.2 (WeeChat returns a long
# integer instead of a string)
#
# 2017-09-20, mickael9
# version 0.8:
# * use weechat 1.5+ api for background processing (old method was unsafe and buggy)
# * add timeout_secs setting (was previously hardcoded to 5 mins)
#
# 2017-07-23, Sébastien Helleu <flashcode@flashtux.org>
# version 0.7.8: fix modulo by zero when nick is empty string
#
# 2016-06-23, mickael9
# version 0.7.7: fix get_home function
#
# 2015-11-26
# version 0.7.6: fix a typo
#
# 2015-01-31, Nicd-
# version 0.7.5:
# '~' is now expaned to the home directory in the log file path so
@ -189,7 +214,12 @@
###
from os import path
import sys, getopt, time, os, re, tempfile
import sys, getopt, time, os, re
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import weechat
@ -200,7 +230,7 @@ except ImportError:
SCRIPT_NAME = "grep"
SCRIPT_AUTHOR = "Elián Hanisch <lambdae2@gmail.com>"
SCRIPT_VERSION = "0.7.5"
SCRIPT_VERSION = "0.8.2"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Search in buffers and logs"
SCRIPT_COMMAND = "grep"
@ -214,6 +244,7 @@ settings = {
'show_summary' : 'on',
'size_limit' : '2048',
'default_tail_head' : '10',
'timeout_secs' : '300',
}
### Class definitions ###
@ -232,14 +263,14 @@ class linesDict(dict):
def get_matches_count(self):
"""Return the sum of total matches stored."""
if dict.__len__(self):
return sum(map(lambda L: L.matches_count, self.itervalues()))
return sum(map(lambda L: L.matches_count, self.values()))
else:
return 0
def __len__(self):
"""Return the sum of total lines stored."""
if dict.__len__(self):
return sum(map(len, self.itervalues()))
return sum(map(len, self.values()))
else:
return 0
@ -247,7 +278,7 @@ class linesDict(dict):
"""Returns buffer count or buffer name if there's just one stored."""
n = len(self.keys())
if n == 1:
return self.keys()[0]
return list(self.keys())[0]
elif n > 1:
return '%s logs' %n
else:
@ -255,18 +286,18 @@ class linesDict(dict):
def items(self):
"""Returns a list of items sorted by line count."""
items = dict.items(self)
items = list(dict.items(self))
items.sort(key=lambda i: len(i[1]))
return items
def items_count(self):
"""Returns a list of items sorted by match count."""
items = dict.items(self)
items = list(dict.items(self))
items.sort(key=lambda i: i[1].matches_count)
return items
def strip_separator(self):
for L in self.itervalues():
for L in self.values():
L.strip_separator()
def get_last_lines(self, n):
@ -275,7 +306,7 @@ class linesDict(dict):
if n >= total_lines:
# nothing to do
return
for k, v in reversed(self.items()):
for k, v in reversed(list(self.items())):
l = len(v)
if n > 0:
if l > n:
@ -372,6 +403,8 @@ def color_nick(nick):
else:
mode = mode_color = ''
# nick color
nick_color = ''
if nick:
nick_color = weechat.info_get('irc_nick_color', nick)
if not nick_color:
# probably we're in WeeChat 0.3.0
@ -414,8 +447,9 @@ def get_config_log_filter():
def get_home():
home = weechat.config_string(weechat.config_get('logger.file.path'))
home = home.replace('%h', weechat.info_get('weechat_dir', ''))
home = path.abspath(path.expanduser(home))
return home.replace('%h', weechat.info_get('weechat_dir', ''))
return home
def strip_home(s, dir=''):
"""Strips home dir from the begging of the log path, this makes them sorter."""
@ -627,8 +661,8 @@ def make_regexp(pattern, matchcase=False):
regexp = re.compile(pattern, re.IGNORECASE)
else:
regexp = re.compile(pattern)
except Exception, e:
raise Exception, 'Bad pattern, %s' %e
except Exception as e:
raise Exception('Bad pattern, %s' % e)
return regexp
def check_string(s, regexp, hilight='', exact=False):
@ -706,7 +740,7 @@ def grep_file(file, head, tail, after_context, before_context, count, regexp, hi
before_context, after_context = after_context, before_context
if before_context:
before_context_range = range(1, before_context + 1)
before_context_range = list(range(1, before_context + 1))
before_context_range.reverse()
limit = tail or head
@ -770,7 +804,7 @@ def grep_file(file, head, tail, after_context, before_context, count, regexp, hi
while id < after_context + offset:
id += 1
try:
context_line = file_object.next()
context_line = next(file_object)
_context_line = check(context_line)
if _context_line:
offset = id
@ -818,6 +852,10 @@ def grep_buffer(buffer, head, tail, after_context, before_context, count, regexp
prefix = string_remove_color(infolist_string(infolist, 'prefix'), '')
message = string_remove_color(infolist_string(infolist, 'message'), '')
date = infolist_time(infolist, 'date')
# since WeeChat 2.2, infolist_time returns a long integer
# instead of a string
if not isinstance(date, str):
date = time.strftime('%F %T', time.localtime(int(date)))
return '%s\t%s\t%s' %(date, prefix, message)
return function
get_line = make_get_line_funcion()
@ -931,104 +969,85 @@ def show_matching_lines():
elif size_limit == '':
background = False
regexp = make_regexp(pattern, matchcase)
global grep_options, log_pairs
grep_options = (head, tail, after_context, before_context,
count, regexp, hilight, exact, invert)
log_pairs = [(strip_home(log), log) for log in search_in_files]
if not background:
# run grep normally
regexp = make_regexp(pattern, matchcase)
for log in search_in_files:
log_name = strip_home(log)
matched_lines[log_name] = grep_file(log, head, tail, after_context, before_context,
count, regexp, hilight, exact, invert)
for log_name, log in log_pairs:
matched_lines[log_name] = grep_file(log, *grep_options)
buffer_update()
else:
# we hook a process so grepping runs in background.
#debug('on background')
global hook_file_grep, script_path, bytecode
timeout = 1000*60*5 # 5 min
quotify = lambda s: '"%s"' %s
files_string = ', '.join(map(quotify, search_in_files))
global tmpFile
# we keep the file descriptor as a global var so it isn't deleted until next grep
tmpFile = tempfile.NamedTemporaryFile(prefix=SCRIPT_NAME,
dir=weechat.info_get('weechat_dir', ''))
cmd = grep_process_cmd %dict(logs=files_string, head=head, pattern=pattern, tail=tail,
hilight=hilight, after_context=after_context, before_context=before_context,
exact=exact, matchcase=matchcase, home_dir=home_dir, script_path=script_path,
count=count, invert=invert, bytecode=bytecode, filename=tmpFile.name,
python=weechat.info_get('python2_bin', '') or 'python')
#debug(cmd)
hook_file_grep = weechat.hook_process(cmd, timeout, 'grep_file_callback', tmpFile.name)
global pattern_tmpl
global hook_file_grep, grep_stdout, grep_stderr, pattern_tmpl
grep_stdout = grep_stderr = ''
hook_file_grep = weechat.hook_process(
'func:grep_process',
get_config_int('timeout_secs') * 1000,
'grep_process_cb',
''
)
if hook_file_grep:
buffer_create("Searching for '%s' in %s worth of data..." %(pattern_tmpl,
human_readable_size(size)))
buffer_create("Searching for '%s' in %s worth of data..." % (
pattern_tmpl,
human_readable_size(size)
))
else:
buffer_update()
# defined here for commodity
grep_process_cmd = """%(python)s -%(bytecode)sc '
import sys, cPickle, os
sys.path.append("%(script_path)s") # add WeeChat script dir so we can import grep
from grep import make_regexp, grep_file, strip_home
logs = (%(logs)s, )
def grep_process(*args):
result = {}
try:
regexp = make_regexp("%(pattern)s", %(matchcase)s)
d = {}
for log in logs:
log_name = strip_home(log, "%(home_dir)s")
lines = grep_file(log, %(head)s, %(tail)s, %(after_context)s, %(before_context)s,
%(count)s, regexp, "%(hilight)s", %(exact)s, %(invert)s)
d[log_name] = lines
fd = open("%(filename)s", "wb")
cPickle.dump(d, fd, -1)
fd.close()
except Exception, e:
print >> sys.stderr, e'
"""
global grep_options, log_pairs
for log_name, log in log_pairs:
result[log_name] = grep_file(log, *grep_options)
except Exception as e:
result = e
return pickle.dumps(result)
grep_stdout = grep_stderr = ''
def grep_file_callback(filename, command, rc, stdout, stderr):
global hook_file_grep, grep_stderr, grep_stdout
global matched_lines
#debug("rc: %s\nstderr: %s\nstdout: %s" %(rc, repr(stderr), repr(stdout)))
if stdout:
grep_stdout += stdout
if stderr:
grep_stderr += stderr
if int(rc) >= 0:
def set_buffer_error():
def grep_process_cb(data, command, return_code, out, err):
global grep_stdout, grep_stderr, matched_lines, hook_file_grep
grep_stdout += out
grep_stderr += err
def set_buffer_error(message):
error(message)
grep_buffer = buffer_create()
title = weechat.buffer_get_string(grep_buffer, 'title')
title = title + ' %serror' % color_title
weechat.buffer_set(grep_buffer, 'title', title)
try:
if return_code == weechat.WEECHAT_HOOK_PROCESS_ERROR:
set_buffer_error("Background grep timed out")
hook_file_grep = None
return WEECHAT_RC_OK
elif return_code >= 0:
hook_file_grep = None
if grep_stderr:
error(grep_stderr)
set_buffer_error()
#elif grep_stdout:
#debug(grep_stdout)
elif path.exists(filename):
import cPickle
set_buffer_error(grep_stderr)
return WEECHAT_RC_OK
try:
#debug(file)
fd = open(filename, 'rb')
d = cPickle.load(fd)
matched_lines.update(d)
fd.close()
except Exception, e:
error(e)
set_buffer_error()
data = pickle.loads(grep_stdout)
if isinstance(data, Exception):
raise data
matched_lines.update(data)
except Exception as e:
set_buffer_error(repr(e))
return WEECHAT_RC_OK
else:
buffer_update()
global tmpFile
tmpFile = None
finally:
grep_stdout = grep_stderr = ''
hook_file_grep = None
return WEECHAT_RC_OK
def get_grep_file_status():
@ -1265,12 +1284,12 @@ def buffer_input(data, buffer, input_data):
weechat.infolist_free(infolist)
try:
cmd_grep_parsing(input_data)
except Exception, e:
except Exception as e:
error('Argument error, %s' % e, buffer=buffer)
return WEECHAT_RC_OK
try:
show_matching_lines()
except Exception, e:
except Exception as e:
error(e)
except NameError:
error("There isn't any previous search to repeat.", buffer=buffer)
@ -1331,7 +1350,7 @@ def cmd_grep_parsing(args):
pattern = _tmplRe.sub(tmplReplacer, args)
debug('Using regexp: %s', pattern)
if not pattern:
raise Exception, 'No pattern for grep the logs.'
raise Exception('No pattern for grep the logs.')
def positive_number(opt, val):
try:
@ -1344,7 +1363,7 @@ def cmd_grep_parsing(args):
opt = '-' + opt
else:
opt = '--' + opt
raise Exception, "argument for %s must be a positive integer." %opt
raise Exception("argument for %s must be a positive integer." % opt)
for opt, val in opts:
opt = opt.strip('-')
@ -1403,18 +1422,18 @@ def cmd_grep_parsing(args):
tail = n
def cmd_grep_stop(buffer, args):
global hook_file_grep, pattern, matched_lines, tmpFile
global hook_file_grep, pattern, matched_lines
if hook_file_grep:
if args == 'stop':
weechat.unhook(hook_file_grep)
hook_file_grep = None
s = 'Search for \'%s\' stopped.' % pattern
say(s, buffer)
grep_buffer = weechat.buffer_search('python', SCRIPT_NAME)
if grep_buffer:
weechat.buffer_set(grep_buffer, 'title', s)
del matched_lines
tmpFile = None
matched_lines = {}
else:
say(get_grep_file_status(), buffer)
raise Exception
@ -1439,7 +1458,7 @@ def cmd_grep(data, buffer, args):
# parse
try:
cmd_grep_parsing(args)
except Exception, e:
except Exception as e:
error('Argument error, %s' % e)
return WEECHAT_RC_OK
@ -1486,7 +1505,7 @@ def cmd_grep(data, buffer, args):
# grepping
try:
show_matching_lines()
except Exception, e:
except Exception as e:
error(e)
return WEECHAT_RC_OK
@ -1505,7 +1524,7 @@ def cmd_logs(data, buffer, args):
opt = opt.strip('-')
if opt in ('size', 's'):
sort_by_size = True
except Exception, e:
except Exception as e:
error('Argument error, %s' % e)
return WEECHAT_RC_OK
@ -1639,7 +1658,7 @@ if __name__ == '__main__' and import_ok and \
If used with 'log <file>' search in all logs that matches <file>.
-b --buffer: Search only in buffers, not in file logs.
-c --count: Just count the number of matched lines instead of showing them.
-m --matchcase: Don't do case insensible search.
-m --matchcase: Don't do case insensitive search.
-H --hilight: Colour exact matches in output buffer.
-o --only-match: Print only the matching part of the line (unique matches).
-v -i --invert: Print lines that don't match the regular expression.
@ -1688,7 +1707,7 @@ Examples:
'completion_grep_args', '')
# settings
for opt, val in settings.iteritems():
for opt, val in settings.items():
if not weechat.config_is_set_plugin(opt):
weechat.config_set_plugin(opt, val)

File diff suppressed because it is too large Load Diff