Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • weechat/scripts
1 result
Show changes
#
# Copyright (C) 2006-2012 Sebastien Helleu <flashcode@flashtux.org>
# Copyright (C) 2011 Nils Görs <weechatter@arcor.de>
# Copyright (C) 2011 ArZa <arza@arza.us>
#
# 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
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# Beep (terminal bell) and/or run command on highlight/private message or new DCC.
#
# History:
# 2012-06-05, ldvx<ldvx@freenode>:
# version 1.1: Added wildcard support for whitelist_nicks.
# 2012-05-09, ldvx <ldvx@freenode>:
# version 1.0: Added beep_pv_blacklist, beep_highlight_blacklist, blacklist_nicks,
# and wildcard support for blacklist_nicks.
# 2012-05-02, ldvx <ldvx@freenode>:
# version 0.9: fix regex for nick in tags, add options "whitelist_channels"
# and "bell_always"
# 2012-04-19, ldvx <ldvx@freenode>:
# version 0.8: add whitelist, trigger, use hook_process for commands,
# rename option "beep_command" to "beep_command_pv", add help for options
# 2011-04-16, ArZa <arza@arza.us>:
# version 0.7: fix default beep command
# 2011-03-11, nils_2 <weechatter@arcor.de>:
# version 0.6: add additional command options for dcc and highlight
# 2011-03-09, nils_2 <weechatter@arcor.de>:
# version 0.5: add option for beep command and dcc
# 2009-05-02, Sebastien Helleu <flashcode@flashtux.org>:
# version 0.4: sync with last API changes
# 2008-11-05, Sebastien Helleu <flashcode@flashtux.org>:
# version 0.3: conversion to WeeChat 0.3.0+
# 2007-08-10, Sebastien Helleu <flashcode@flashtux.org>:
# version 0.2: upgraded licence to GPL 3
# 2006-09-02, Sebastien Helleu <flashcode@flashtux.org>:
# version 0.1: initial release
use strict;
my $SCRIPT_NAME = "beep";
my $VERSION = "1.1";
# default values in setup file (~/.weechat/plugins.conf)
my %options_default = ('beep_pv' => ['on', 'beep on private message'],
'beep_pv_whitelist' => ['off', 'turn whitelist for private messages on or off'],
'beep_pv_blacklist' => ['off', 'turn blacklist for private messages on or off'],
'beep_highlight' => ['on', 'beep on highlight'],
'beep_highlight_whitelist' => ['off', 'turn whitelist for highlights on or off'],
'beep_highlight_blacklist' => ['off', 'turn blacklist for highlights on or off'],
'beep_dcc' => ['on', 'beep on dcc'],
'beep_trigger_pv' => ['', 'word that will trigger execution of beep_command_pv (it empty, anything will trigger)'],
'beep_trigger_highlight' => ['', 'word that will trigger execution of beep_command_highlight (if empty, anything will trigger)'],
'beep_command_pv' => ['$bell', 'command for beep on private message, special value "$bell" is allowed, as well as "$bell;command"'],
'beep_command_highlight' => ['$bell', 'command for beep on highlight, special value "$bell" is allowed, as well as "$bell;command"'],
'beep_command_dcc' => ['$bell', 'command for beep on dcc, special value "$bell" is allowed, as well as "$bell;command"'],
'beep_command_timeout' => ['30000', 'timeout for command run (in milliseconds, 0 = never kill (not recommended))'],
'whitelist_nicks' => ['', 'comma-separated list of "server.nick": if not empty, only these nicks will trigger execution of commands (example: "freenode.nick1,freenode.nick2")'],
'blacklist_nicks' => ['', 'comma-separated list of "server.nick": if not empty, these nicks will not be able to trigger execution of commands. Cannot be used in conjuction with whitelist (example: "freenode.nick1,freenode.nick2")'],
'whitelist_channels' => ['', 'comma-separated list of "server.#channel": if not empty, only these channels will trigger execution of commands (example: "freenode.#weechat,freenode.#channel2")'],
'bell_always' => ['', 'use $bell on private messages and/or highlights regardless of trigger and whitelist settings (example: "pv,highlight")'],
);
my %options = ();
weechat::register($SCRIPT_NAME, "FlashCode <flashcode\@flashtux.org>", $VERSION,
"GPL3", "Beep (terminal bell) and/or run command on highlight/private message or new DCC", "", "");
init_config();
weechat::hook_config("plugins.var.perl.$SCRIPT_NAME.*", "toggle_config_by_set", "");
weechat::hook_print("", "", "", 1, "pv_and_highlight", "");
weechat::hook_signal("irc_dcc", "dcc", "");
sub pv_and_highlight
{
my ($data, $buffer, $date, $tags, $displayed, $highlight, $prefix, $message) = @_;
# return if message is filtered
return weechat::WEECHAT_RC_OK if ($displayed != 1);
# return if nick in message is own nick
my $nick = "";
$nick = $2 if ($tags =~ m/(^|,)nick_([^,]*)(,|$)/);
return weechat::WEECHAT_RC_OK if (weechat::buffer_get_string($buffer, "localvar_nick") eq $nick);
# highlight
if ($highlight)
{
# Always print visual bel, regardless of whitelist and trigger settings
# beep_command_highlight does not need to contain $bell
if ($options{bell_always} =~ m/(^|,)highlight(,|$)/)
{
print STDERR "\a";
}
# Channels whitelist for highlights
if ($options{beep_highlight} eq "on")
{
if ($options{whitelist_channels} ne "")
{
my $serverandchannel = weechat::buffer_get_string($buffer, "localvar_server"). "." .
weechat::buffer_get_string($buffer, "localvar_channel");
if ($options{beep_trigger_highlight} eq "" or $message =~ m/\b$options{beep_trigger_highlight}\b/)
{
if ($options{whitelist_channels} =~ /(^|,)$serverandchannel(,|$)/)
{
beep_exec_command($options{beep_command_highlight});
}
# What if we are highlighted and we're in a PM? For now, do nothing.
}
}
else
{
# Execute $bell and/or command with trigger and whitelist/blacklist settings
beep_trigger_whitelist_blacklist($buffer, $message, $nick, $options{beep_trigger_highlight},
$options{beep_highlight_whitelist}, $options{beep_highlight_blacklist},
$options{beep_command_highlight});
}
}
}
# private message
elsif (weechat::buffer_get_string($buffer, "localvar_type") eq "private" and $tags =~ m/(^|,)notify_private(,|$)/)
{
# Always print visual bel, regardless of whitelist and trigger settings
# beep_command_pv does not need to contain $bell
if ($options{bell_always} =~ m/(^|,)pv(,|$)/)
{
print STDERR "\a";
}
# Execute $bell and/or command with trigger and whitelist/blacklist settings
if ($options{beep_pv} eq "on")
{
beep_trigger_whitelist_blacklist($buffer, $message, $nick, $options{beep_trigger_pv},
$options{beep_pv_whitelist}, $options{beep_pv_blacklist},
$options{beep_command_pv});
}
}
return weechat::WEECHAT_RC_OK;
}
sub dcc
{
beep_exec_command($options{beep_command_dcc}) if ($options{beep_dcc} eq "on");
return weechat::WEECHAT_RC_OK;
}
sub beep_trigger_whitelist_blacklist
{
my ($buffer, $message, $nick, $trigger, $whitelist, $blacklist, $command) = @_;
if ($trigger eq "" or $message =~ m/\b$trigger\b/)
{
my $serverandnick = weechat::buffer_get_string($buffer, "localvar_server").".".$nick;
if ($whitelist eq "on" and $options{whitelist_nicks} ne "")
{
# What to do if there's a wildcard in the whitelit
if ($options{whitelist_nicks} =~ m/\*/ and
match_in_wild_card($serverandnick, $options{whitelist_nicks}))
{
beep_exec_command($command);
}
# What to do if there's no wildcard in the whitelist
elsif ($options{whitelist_nicks} =~ /(^|,)$serverandnick(,|$)/)
{
beep_exec_command($command);
}
}
elsif ($blacklist eq "on" and $options{blacklist_nicks} ne "")
{
# What to do if there's a wildcard in the blacklist
if ($options{blacklist_nicks} =~ m/\*/ and
!match_in_wild_card($serverandnick, $options{blacklist_nicks}))
{
beep_exec_command($command);
}
# What to do if there's no wildcard in the blacklist
elsif ($options{blacklist_nicks} !~ /(^|,)$serverandnick(,|$)/)
{
beep_exec_command($command);
}
}
# What to do if we are not using whitelist of blacklist feature
elsif ($whitelist eq "off" and $blacklist eq "off")
{
beep_exec_command($command);
}
}
}
sub beep_exec_command
{
my $command = $_[0];
if ($command =~ /^\$bell/)
{
print STDERR "\a";
($command) = $command =~ /^\$bell;(.+)$/;
}
weechat::hook_process($command, $options{beep_command_timeout}, "my_process", "") if ($command);
}
sub match_in_wild_card
{
my ($serverandnick, $white_or_black) = @_;
my $nick_iter;
my @array_of_nicks = split(",", $white_or_black);
foreach $nick_iter (@array_of_nicks)
{
$nick_iter =~ s/\*/[^,]*/g;
if ($serverandnick =~ /$nick_iter/)
{
return 1;
}
}
return 0;
}
sub my_process
{
return weechat::WEECHAT_RC_OK;
}
sub toggle_config_by_set
{
my ($pointer, $name, $value) = @_;
$name = substr($name, length("plugins.var.perl.".$SCRIPT_NAME."."), length($name));
$options{$name} = $value;
return weechat::WEECHAT_RC_OK;
}
sub init_config
{
my $version = weechat::info_get("version_number", "") || 0;
foreach my $option (keys %options_default)
{
if (!weechat::config_is_set_plugin($option))
{
weechat::config_set_plugin($option, $options_default{$option}[0]);
$options{$option} = $options_default{$option}[0];
}
else
{
$options{$option} = weechat::config_get_plugin($option);
}
if ($version >= 0x00030500)
{
weechat::config_set_desc_plugin($option, $options_default{$option}[1]." (default: \"".$options_default{$option}[0]."\")");
}
}
}
# echo.pl by ArZa <arza@arza.us>: Print a line and additionally set activity level
# This program is free software: you can modify/redistribute it under the terms of
# GNU General Public License by Free Software Foundation, either version 3 or later
# which you can get from <http://www.gnu.org/licenses/>.
# This program is distributed in the hope that it will be useful, but without any warranty.
weechat::register("echo", "ArZa <arza\@arza.us>", "0.1", "GPL3", "Print a line and additionally set activity level", "", "");
weechat::hook_command(
"echo",
"Print a line and additionally set activity level. Local variables are expanded when starting with \$ and can be escaped with \\.",
"[ -p/-plugin <plugin> ] [ -b/-buffer <buffer name/number> | -c/-core ] [ -l/-level <level>] [text]",
"-plugin: plugin where printed, default: current plugin
-buffer: buffer where printed, default: current buffer, e.g. #weechat or freenode.#weechat)
-core: print to the core buffer
-level: number of the activity level, default: low:
0=low, 1=message, 2=private, 3=highlight
Examples:
/echo This is a test message
/echo -b freenode.#weechat -level 3 Highlight!
/echo -core This goes to the core buffer
/echo -buffer #weechat -l 1 My variable \\\$name is \$name on \$channel",
"-buffer %(buffer_names) || -core || -level 1|2|3 || -plugin %(plugins_names)", "echo", ""
);
sub echo {
my @args=split(/ /, $_[2]);
my $i=0;
my ($plugin, $buffer, $level) = ("", "", "");
while($i<=$#args){ # go through command options
if($args[$i] eq "-b" || $args[$i] eq "-buffer"){
$i++;
$buffer=$args[$i] if $args[$i];
}elsif($args[$i] eq "-p" || $args[$i] eq "-plugin"){
$i++;
$plugin=$args[$i] if $args[$i];
}elsif($args[$i] eq "-c" || $args[$i] eq "-core"){
$buffer=weechat::buffer_search_main();
}elsif($args[$i] eq "-l" || $args[$i] eq "-level"){
$i++;
$level=$args[$i] if $args[$i];
}else{
last;
}
$i++;
}
if($plugin ne ""){ # use specific plugin if set
$buffer=weechat::buffer_search($plugin, $buffer);
}elsif($buffer ne ""){
if($buffer=~/^\d+$/){ # if got a number
my $infolist = weechat::infolist_get("buffer", "", "");
while(weechat::infolist_next($infolist)){ # find the buffer for the number
if(weechat::infolist_integer($infolist, "number") eq $buffer){
$buffer=weechat::buffer_search( weechat::infolist_string($infolist, "plugin"), weechat::infolist_string($infolist, "name") );
last;
}
}
weechat::infolist_free($infolist);
}elsif( weechat::buffer_search ( weechat::buffer_get_string( weechat::current_buffer(), "plugin" ), $buffer ) ){ # if buffer found in current plugin
$buffer=weechat::buffer_search ( weechat::buffer_get_string( weechat::current_buffer(), "plugin" ), $buffer );
}else{ # search even more to find the correct buffer
my $infolist = weechat::infolist_get("buffer", "", "");
while(weechat::infolist_next($infolist)){ # find the buffer for a short_name
if(lc(weechat::infolist_string($infolist, "short_name")) eq lc($buffer)){
$buffer=weechat::buffer_search( weechat::infolist_string($infolist, "plugin"), weechat::infolist_string($infolist, "name") );
last;
}
}
weechat::infolist_free($infolist);
}
}
$buffer=weechat::current_buffer() if $buffer eq "" || $buffer eq $args[$i-1]; # otherwise use the current buffer
my $j=$i;
$args[$j]=~s/^\\\-/-/ if $args[$j]; # "\-" -> "-" in the beginning
while($j<=$#args){ # go through text
if($args[$j]=~/^\$/){ # replace variables
$args[$j]=weechat::buffer_string_replace_local_var($buffer, $args[$j]);
}elsif($args[$j]=~/^\\[\$\\]/){ # escape variables
$args[$j]=~s/^\\//;
}
$j++;
}
weechat::print($buffer, join(' ', @args[$i..$#args])); # print the text
weechat::buffer_set($buffer, "hotlist", $level); # set hotlist level
}
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011-2013 by F. Besser <fbesser@gmail.com>
#
# 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
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# History:
# 2013-09-01, nils_2@freenode.#weechat:
# version 0.2: add support of servername for "-exclude"
# : make script behave like /allchan and /allserver command
# : add function "-current"
# : case-insensitive search for query/server
#
# 2011-09-05, F. Besser <fbesser@gmail.com>:
# version 0.1: script created
#
# Development is on:
# https://github.com/fbesser/weechat_scripts
#
# (this script requires WeeChat 0.3.0 or newer)
#
SCRIPT_NAME = "allquery"
SCRIPT_AUTHOR = "fbesser"
SCRIPT_VERSION = "0.2"
SCRIPT_LICENSE = "GPL3"
SCRIPT_DESC = "Executes command on all irc query buffer"
SCRIPT_COMMAND = "allquery"
import_ok = True
try:
import weechat
except ImportError:
print('This script must be run under WeeChat.')
print('Get WeeChat now at: http://www.weechat.org/')
import_ok = False
try:
import re
except ImportError, message:
print('Missing package(s) for %s: %s' % (SCRIPT_NAME, message))
import_ok = False
def make_list(argument):
""" Make a list out of argument string of format -argument=value0,value1"""
arglist = argument.lower().split("=", 1)
arguments = arglist[1].split(",")
return arguments
def allquery_command_cb(data, buffer, args):
""" Callback for /allquery command """
args = args.strip()
if args == "":
weechat.command("", "/help %s" % SCRIPT_COMMAND)
return weechat.WEECHAT_RC_OK
argv = args.split(" ")
exclude_nick = None
current_server = None
if '-current' in argv:
current_server = weechat.buffer_get_string(weechat.current_buffer(), "localvar_server")
# remove "-current" + whitespace from argumentlist
args = args.replace("-current", "")
args = args.lstrip()
argv.remove("-current")
# search for "-exclude" in arguments
i = 0
for entry in argv[0:]:
if entry.startswith("-exclude="):
exclude_nick = make_list(argv[i])
command = " ".join(argv[i+1::])
break
i +=1
else:
command = args
# no command found.
if not command:
return weechat.WEECHAT_RC_OK
if not command.startswith("/"):
command = "/%s" % command
infolist = weechat.infolist_get("buffer", "", "")
while weechat.infolist_next(infolist):
if weechat.infolist_string(infolist, "plugin_name") == "irc":
ptr = weechat.infolist_pointer(infolist, "pointer")
server = weechat.buffer_get_string(ptr, "localvar_server")
query = weechat.buffer_get_string(ptr, "localvar_channel")
execute_command = re.sub(r'\$nick', query, command)
if weechat.buffer_get_string(ptr, "localvar_type") == "private":
if current_server is not None:
if server == current_server:
exclude_nick_and_server(ptr,query,server,exclude_nick,execute_command)
else:
exclude_nick_and_server(ptr,query,server,exclude_nick,execute_command)
weechat.infolist_free(infolist)
return weechat.WEECHAT_RC_OK
def exclude_nick_and_server(ptr, query, server, exclude_nick, execute_command):
server = "%s.*" % server # servername + ".*"
if exclude_nick is not None:
if not query.lower() in exclude_nick and not server.lower() in exclude_nick:
weechat.command(ptr, execute_command)
else:
weechat.command(ptr, execute_command)
if __name__ == '__main__' and import_ok:
if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION,
SCRIPT_LICENSE, SCRIPT_DESC, "", ""):
weechat.hook_command(SCRIPT_COMMAND, SCRIPT_DESC,
'[-current] [-exclude=<nick|server>[,<nick2|server>...]] <command> [<arguments>]',
' -current: execute command for query of current server only\n'
' -exclude: exclude some querys and/or server from executed command\n'
' command: command executed in query buffers\n'
' arguments: arguments for command (special variables $nick will be replaced by its value)\n\n'
'Examples:\n'
' close all query buffers:\n'
' /' + SCRIPT_COMMAND + ' buffer close\n'
' close all query buffers, but don\'t close FlashCode:\n'
' /' + SCRIPT_COMMAND + ' -exclude=FlashCode buffer close\n'
' close all query buffers, except for server freenode:\n'
' /' + SCRIPT_COMMAND + ' -exclude=freenode.* buffer close\n'
' msg to all query buffers:\n'
' /' + SCRIPT_COMMAND + ' say Hello\n'
' notice to all query buffers:\n'
' /' + SCRIPT_COMMAND + ' notice $nick Hello',
'%(commands)',
'allquery_command_cb', '')
# -*- coding: utf-8 -*-
# =============================================================================
# shell.py (c) March 2006, 2009 by Kolter <kolter@openics.org>
#
# Licence : GPL v2
# Description : running shell commands in WeeChat
# Syntax : try /help shell to get some help on this script
# Precond : needs weechat >= 0.3.0 to run
#
#
# ### changelog ###
#
# * version 0.8, 2013-07-27, Sebastien Helleu <flashcode@flashtux.org>:
# - don't remove empty lines in output of command
# * version 0.7, 2012-11-26, Sebastien Helleu <flashcode@flashtux.org>:
# - use hashtable for command arguments (for WeeChat >= 0.4.0)
# * version 0.6, 2012-11-21, Sebastien Helleu <flashcode@flashtux.org>:
# - call shell in hook_process (WeeChat >= 0.3.9.2 does not call shell any more)
# * version 0.5, 2011-10-01, Sebastien Helleu <flashcode@flashtux.org>:
# - add shell buffer
# * version 0.4, 2009-05-02, Sebastien Helleu <flashcode@flashtux.org>:
# - sync with last API changes
# * version 0.3, 2009-03-06, Sebastien Helleu <flashcode@flashtux.org>:
# - use of hook_process to run background process
# - add option -t <timeout> to kill process after <timeout> seconds
# - show process running, kill it with -kill
# * version 0.2, 2009-01-31, Sebastien Helleu <flashcode@flashtux.org>:
# - conversion to WeeChat 0.3.0+
# * version 0.1, 2006-03-13, Kolter <kolter@openics.org>:
# - first release
#
# =============================================================================
import weechat, os, datetime
SCRIPT_NAME = 'shell'
SCRIPT_AUTHOR = 'Kolter'
SCRIPT_VERSION = '0.8'
SCRIPT_LICENSE = 'GPL2'
SCRIPT_DESC = 'Run shell commands in WeeChat'
SHELL_CMD = 'shell'
SHELL_PREFIX = '[shell] '
cmd_hook_process = ''
cmd_command = ''
cmd_start_time = None
cmd_buffer = ''
cmd_shell_buffer = ''
cmd_stdout = ''
cmd_stderr = ''
cmd_send_to_buffer = ''
cmd_timeout = 0
if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
SCRIPT_DESC, '', ''):
weechat.hook_command(
SHELL_CMD,
'Running shell commands in WeeChat',
'[-o|-n] [-t seconds] <command> || -show || -kill',
' -o: send output to current buffer (simulate user entry '
'with command output - dangerous, be careful when using this option)\n'
' -n: display output in a new empty buffer\n'
'-t seconds: auto-kill process after timeout (seconds) if process '
'is still running\n'
' command: shell command or builtin like cd, getenv, setenv, unsetenv\n'
' -show: show running process\n'
' -kill: kill running process',
'-o|-n|-t|cd|getenv|setenv|unsetenv|-show||-kill -o|-n|-t|cd|getenv|setenv|unsetenv',
'shell_cmd', '')
def shell_init():
"""Initialize some variables."""
global cmd_hook_process, cmd_command, cmd_start_time, cmd_buffer, cmd_stdout, cmd_stderr
cmd_hook_process = ''
cmd_command = ''
cmd_start_time = None
cmd_buffer = ''
cmd_stdout = ''
cmd_stderr = ''
def shell_set_title():
"""Set title on shell buffer (with working directory)."""
global cmd_shell_buffer
if cmd_shell_buffer:
weechat.buffer_set(cmd_shell_buffer, 'title',
'%s.py %s | "q": close buffer | Working dir: %s' % (SCRIPT_NAME, SCRIPT_VERSION, os.getcwd()))
def shell_process_cb(data, command, rc, stdout, stderr):
"""Callback for hook_process()."""
global cmd_hook_process, cmd_buffer, cmd_stdout, cmd_stderr, cmd_send_to_buffer
cmd_stdout += stdout
cmd_stderr += stderr
if int(rc) >= 0:
if cmd_stdout:
lines = cmd_stdout.rstrip().split('\n')
if cmd_send_to_buffer == 'current':
for line in lines:
weechat.command(cmd_buffer, '%s' % line)
else:
weechat.prnt(cmd_buffer, '')
if cmd_send_to_buffer != 'new':
weechat.prnt(cmd_buffer, '%sCommand "%s" (rc %d), stdout:'
% (SHELL_PREFIX, data, int(rc)))
for line in lines:
weechat.prnt(cmd_buffer, ' \t%s' % line)
if cmd_stderr:
lines = cmd_stderr.rstrip().split('\n')
if cmd_send_to_buffer == 'current':
for line in lines:
weechat.command(cmd_buffer, '%s' % line)
else:
weechat.prnt(cmd_buffer, '')
if cmd_send_to_buffer != 'new':
weechat.prnt(cmd_buffer, '%s%sCommand "%s" (rc %d), stderr:'
% (weechat.prefix('error'), SHELL_PREFIX, data, int(rc)))
for line in lines:
weechat.prnt(cmd_buffer, '%s%s' % (weechat.prefix('error'), line))
cmd_hook_process = ''
shell_set_title()
return weechat.WEECHAT_RC_OK
def shell_show_process(buffer):
"""Show running process."""
global cmd_command, cmd_start_time
if cmd_hook_process:
weechat.prnt(buffer, '%sprocess running: "%s" (started on %s)'
% (SHELL_PREFIX, cmd_command, cmd_start_time.ctime()))
else:
weechat.prnt(buffer, '%sno process running' % SHELL_PREFIX)
def shell_kill_process(buffer):
"""Kill running process."""
global cmd_hook_process, cmd_command
if cmd_hook_process:
weechat.unhook(cmd_hook_process)
weechat.prnt(buffer, '%sprocess killed (command "%s")' % (SHELL_PREFIX, cmd_command))
shell_init()
else:
weechat.prnt(buffer, '%sno process running' % SHELL_PREFIX)
def shell_chdir(buffer, directory):
"""Change working directory."""
if not directory:
if os.environ.has_key('HOME'):
directory = os.environ['HOME']
try:
os.chdir(directory)
except:
weechat.prnt(buffer, '%san error occured while running command "cd %s"' % (SHELL_PREFIX, directory))
else:
weechat.prnt(buffer, '%schdir to "%s" ok, new path: %s' % (SHELL_PREFIX, directory, os.getcwd()))
shell_set_title()
def shell_getenv(buffer, var):
"""Get environment variable."""
global cmd_send_to_buffer
var = var.strip()
if not var:
weechat.prnt(buffer, '%swrong syntax, try "getenv VAR"' % (SHELL_PREFIX))
return
value = os.getenv(var)
if value == None:
weechat.prnt(buffer, '%s$%s is not set' % (SHELL_PREFIX, var))
else:
if cmd_send_to_buffer == 'current':
weechat.command(buffer, '$%s=%s' % (var, os.getenv(var)))
else:
weechat.prnt(buffer, '%s$%s=%s' % (SHELL_PREFIX, var, os.getenv(var)))
def shell_setenv(buffer, expr):
"""Set an environment variable."""
global cmd_send_to_buffer
expr = expr.strip()
lexpr = expr.split('=')
if (len(lexpr) < 2):
weechat.prnt(buffer, '%swrong syntax, try "setenv VAR=VALUE"' % (SHELL_PREFIX))
return
os.environ[lexpr[0].strip()] = '='.join(lexpr[1:])
if cmd_send_to_buffer != 'current':
weechat.prnt(buffer, '%s$%s is now set to "%s"' % (SHELL_PREFIX, lexpr[0], '='.join(lexpr[1:])))
def shell_unsetenv(buffer, var):
"""Remove environment variable."""
var = var.strip()
if not var:
weechat.prnt(buffer, '%swrong syntax, try "unsetenv VAR"' % (SHELL_PREFIX))
return
if os.environ.has_key(var):
del os.environ[var]
weechat.prnt(buffer, '%s$%s is now unset' % (SHELL_PREFIX, var))
else:
weechat.prnt(buffer, '%s$%s is not set' % (SHELL_PREFIX, var))
def shell_exec(buffer, command):
"""Execute a command."""
global cmd_hook_process, cmd_command, cmd_start_time, cmd_buffer
global cmd_stdout, cmd_stderr, cmd_send_to_buffer, cmd_timeout
if cmd_hook_process:
weechat.prnt(buffer,
'%sanother process is running! (use "/%s -kill" to kill it)'
% (SHELL_PREFIX, SHELL_CMD))
return
if cmd_send_to_buffer == 'new':
weechat.prnt(buffer, '-->\t%s%s$ %s%s'
% (weechat.color('chat_buffer'), os.getcwd(), weechat.color('reset'), command))
weechat.prnt(buffer, '')
args = command.split(' ')
if args[0] == 'cd':
shell_chdir(buffer, ' '.join(args[1:]))
elif args[0] == 'getenv':
shell_getenv (buffer, ' '.join(args[1:]))
elif args[0] == 'setenv':
shell_setenv (buffer, ' '.join(args[1:]))
elif args[0] == 'unsetenv':
shell_unsetenv (buffer, ' '.join(args[1:]))
else:
shell_init()
cmd_command = command
cmd_start_time = datetime.datetime.now()
cmd_buffer = buffer
version = weechat.info_get("version_number", "") or 0
if int(version) >= 0x00040000:
cmd_hook_process = weechat.hook_process_hashtable('sh', { 'arg1': '-c', 'arg2': command },
cmd_timeout * 1000, 'shell_process_cb', command)
else:
cmd_hook_process = weechat.hook_process("sh -c '%s'" % command, cmd_timeout * 1000, 'shell_process_cb', command)
def shell_input_buffer(data, buffer, input):
"""Input callback on shell buffer."""
global cmd_send_to_buffer
if input in ('q', 'Q'):
weechat.buffer_close(buffer)
return weechat.WEECHAT_RC_OK
cmd_send_to_buffer = 'new'
weechat.prnt(buffer, '')
command = weechat.string_input_for_buffer(input)
shell_exec(buffer, command)
return weechat.WEECHAT_RC_OK
def shell_close_buffer(data, buffer):
"""Close callback on shell buffer."""
global cmd_shell_buffer
cmd_shell_buffer = ''
return weechat.WEECHAT_RC_OK
def shell_new_buffer():
"""Create shell buffer."""
global cmd_shell_buffer
cmd_shell_buffer = weechat.buffer_search('python', 'shell')
if not cmd_shell_buffer:
cmd_shell_buffer = weechat.buffer_new('shell', 'shell_input_buffer', '', 'shell_close_buffer', '')
if cmd_shell_buffer:
shell_set_title()
weechat.buffer_set(cmd_shell_buffer, 'localvar_set_no_log', '1')
weechat.buffer_set(cmd_shell_buffer, 'time_for_each_line', '0')
weechat.buffer_set(cmd_shell_buffer, 'input_get_unknown_commands', '1')
weechat.buffer_set(cmd_shell_buffer, 'display', '1')
return cmd_shell_buffer
def shell_cmd(data, buffer, args):
"""Callback for /shell command."""
global cmd_send_to_buffer, cmd_timeout
largs = args.split(' ')
# strip spaces
while '' in largs:
largs.remove('')
while ' ' in largs:
largs.remove(' ')
cmdbuf = buffer
if len(largs) == 0:
shell_new_buffer()
else:
if largs[0] == '-show':
shell_show_process(cmdbuf)
elif largs[0] == '-kill':
shell_kill_process(cmdbuf)
else:
cmd_send_to_buffer = ''
cmd_timeout = 0
while largs:
if largs[0] == '-o':
cmd_send_to_buffer = 'current'
largs = largs[1:]
continue
if largs[0] == '-n':
cmd_send_to_buffer = 'new'
cmdbuf = shell_new_buffer()
largs = largs[1:]
continue
if largs[0] == '-t' and len(largs) > 2:
cmd_timeout = int(largs[1])
largs = largs[2:]
continue
break
if len(largs) > 0:
shell_exec(cmdbuf, ' '.join(largs))
return weechat.WEECHAT_RC_OK