commit 39d8e6b732fecc59d6dad8acc974ceabc2343859 Author: aewens Date: Thu Jan 3 19:57:42 2019 +0100 Initial commit diff --git a/.bash_logout b/.bash_logout new file mode 100644 index 0000000..de4f5f7 --- /dev/null +++ b/.bash_logout @@ -0,0 +1,7 @@ +# ~/.bash_logout: executed by bash(1) when login shell exits. + +# when leaving the console clear the screen to increase privacy + +if [ "$SHLVL" = 1 ]; then + [ -x /usr/bin/clear_console ] && /usr/bin/clear_console -q +fi diff --git a/.bashrc b/.bashrc new file mode 100644 index 0000000..d312581 --- /dev/null +++ b/.bashrc @@ -0,0 +1,120 @@ +# ~/.bashrc: executed by bash(1) for non-login shells. +# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) +# for examples + +# If not running interactively, don't do anything +case $- in + *i*) ;; + *) return;; +esac + +# don't put duplicate lines or lines starting with space in the history. +# See bash(1) for more options +HISTCONTROL=ignoreboth + +# append to the history file, don't overwrite it +shopt -s histappend + +# for setting history length see HISTSIZE and HISTFILESIZE in bash(1) +HISTSIZE=HISTFILESIZE + +# check the window size after each command and, if necessary, +# update the values of LINES and COLUMNS. +shopt -s checkwinsize + +# If set, the pattern "**" used in a pathname expansion context will +# match all files and zero or more directories and subdirectories. +#shopt -s globstar + +# make less more friendly for non-text input files, see lesspipe(1) +[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" + +# set variable identifying the chroot you work in (used in the prompt below) +if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then + debian_chroot=$(cat /etc/debian_chroot) +fi + +# set a fancy prompt (non-color, unless we know we "want" color) +case "$TERM" in + xterm-color|*-256color) color_prompt=yes;; +esac + +# uncomment for a colored prompt, if the terminal has the capability; turned +# off by default to not distract the user: the focus in a terminal window +# should be on the output of commands, not on the prompt +#force_color_prompt=yes + +if [ -n "$force_color_prompt" ]; then + if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then + # We have color support; assume it's compliant with Ecma-48 + # (ISO/IEC-6429). (Lack of such support is extremely rare, and such + # a case would tend to support setf rather than setaf.) + color_prompt=yes + else + color_prompt= + fi +fi + +if [ "$color_prompt" = yes ]; then + PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ' +else + PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ' +fi +unset color_prompt force_color_prompt + +# If this is an xterm set the title to user@host:dir +case "$TERM" in +xterm*|rxvt*) + PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1" + ;; +*) + ;; +esac + +# enable color support of ls and also add handy aliases +if [ -x /usr/bin/dircolors ]; then + test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" + alias ls='ls --color=auto' + #alias dir='dir --color=auto' + #alias vdir='vdir --color=auto' + + alias grep='grep --color=auto' + alias fgrep='fgrep --color=auto' + alias egrep='egrep --color=auto' +fi + +# colored GCC warnings and errors +#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01' + +# some more ls aliases +alias ll='ls -alF' +alias la='ls -A' +alias l='ls -CF' + +# Add an "alert" alias for long running commands. Use like so: +# sleep 10; alert +alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' + +# Alias definitions. +# You may want to put all your additions into a separate file like +# ~/.bash_aliases, instead of adding them here directly. +# See /usr/share/doc/bash-doc/examples in the bash-doc package. + +if [ -f ~/.bash_aliases ]; then + . ~/.bash_aliases +fi + +# enable programmable completion features (you don't need to enable +# this, if it's already enabled in /etc/bash.bashrc and /etc/profile +# sources /etc/bash.bashrc). +if ! shopt -oq posix; then + if [ -f /usr/share/bash-completion/bash_completion ]; then + . /usr/share/bash-completion/bash_completion + elif [ -f /etc/bash_completion ]; then + . /etc/bash_completion + fi +fi + +# set EDITOR just in case +export EDITOR=nano + diff --git a/.profile b/.profile new file mode 100644 index 0000000..11bfa8b --- /dev/null +++ b/.profile @@ -0,0 +1,32 @@ +# ~/.profile: executed by the command interpreter for login shells. +# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login +# exists. +# see /usr/share/doc/bash/examples/startup-files for examples. +# the files are located in the bash-doc package. + +# the default umask is set in /etc/profile; for setting the umask +# for ssh logins, install and configure the libpam-umask package. +#umask 022 + +# if running bash +if [ -n "$BASH_VERSION" ]; then + # include .bashrc if it exists + if [ -f "$HOME/.bashrc" ]; then + . "$HOME/.bashrc" + fi +fi + +# set PATH so it includes user's private bin if it exists +if [ -d "$HOME/bin" ] ; then + PATH="$HOME/bin:$PATH" +fi + +# set PATH so it includes user's private bin if it exists +if [ -d "$HOME/.local/bin" ] ; then + PATH="$HOME/.local/bin:$PATH" +fi + +# set PATH so it includes ~center's bin if it exists +if [ -d "/center/bin" ] ; then + PATH="/center/bin:$PATH" +fi diff --git a/.ssh/authorized_keys b/.ssh/authorized_keys new file mode 100644 index 0000000..e69de29 diff --git a/.weechat/alias.conf b/.weechat/alias.conf new file mode 100644 index 0000000..3167757 --- /dev/null +++ b/.weechat/alias.conf @@ -0,0 +1,48 @@ +# +# alias.conf -- weechat v1.0.1 +# + +[cmd] +AAWAY = "allserv /away" +AME = "allchan /me" +AMSG = "allchan /msg *" +ANICK = "allserv /nick" +BEEP = "print -beep" +BS = "quote botserv" +BYE = "quit" +C = "buffer clear" +CHAT = "dcc chat" +CL = "buffer clear" +CLOSE = "buffer close" +CS = "quote chanserv" +EXIT = "quit" +IG = "ignore" +J = "join" +HS = "quote hostserv" +K = "kick" +KB = "kickban" +LEAVE = "part" +M = "msg" +MS = "quote memoserv" +MSGBUF = "command -buffer $1 * /input send $2-" +MUB = "unban *" +N = "names" +NS = "quote nickserv" +Q = "query" +REDRAW = "window refresh" +save_settings = "/autojoin --run;/layout store;/save" +SAY = "msg *" +SIGNOFF = "quit" +T = "topic" +UB = "unban" +UMODE = "mode $nick" +V = "command core version" +W = "who" +WC = "window merge" +WI = "whois" +WII = "whois $1 $1" +WW = "whowas" +setup_aspell = "/set weechat.bar.rootinput.items [input_prompt]+(away),[input_search],[input_paste],input_text,aspell_suggest;/set aspell.check.default_dict en_US;/set aspell.check.suggestions 4;/set aspell.check.enabled on;/unalias setup_aspell;/save" + +[completion] +MSGBUF = "%(buffers_plugins_names)" diff --git a/.weechat/aspell.conf b/.weechat/aspell.conf new file mode 100644 index 0000000..aa0bd00 --- /dev/null +++ b/.weechat/aspell.conf @@ -0,0 +1,20 @@ +# +# aspell.conf -- weechat v1.0.1 +# + +[color] +misspelled = lightred +suggestions = default + +[check] +commands = "ame,amsg,away,command,cycle,kick,kickban,me,msg,notice,part,query,quit,topic" +default_dict = "" +during_search = off +enabled = off +real_time = off +suggestions = -1 +word_min_length = 2 + +[dict] + +[option] diff --git a/.weechat/buflist.conf b/.weechat/buflist.conf new file mode 100644 index 0000000..0b225d5 --- /dev/null +++ b/.weechat/buflist.conf @@ -0,0 +1,37 @@ +# +# weechat -- buflist.conf +# +# WARNING: It is NOT recommended to edit this file by hand, +# especially if WeeChat is running. +# +# Use /set or similar command to change settings in WeeChat. +# +# For more info, see: https://weechat.org/doc/quickstart +# + +[look] +display_conditions = "${buffer.hidden}==0" +enabled = on +mouse_jump_visited_buffer = off +mouse_move_buffer = on +mouse_wheel = on +nick_prefix = off +nick_prefix_empty = on +signals_refresh = "" +sort = "number,-active" + +[format] +buffer = "${format_number}${indent}${format_nick_prefix}${color_hotlist}${name}" +buffer_current = "${color:,233}${format_number}${indent}${format_nick_prefix}${color:lightcyan}${name}" +hotlist = " ${color:green}(${hotlist}${color:green})" +hotlist_highlight = "${color:magenta}" +hotlist_low = "${color:default}" +hotlist_message = "${color:130}" +hotlist_none = "${color:white}" +hotlist_private = "${color:cyan}" +hotlist_separator = "${color:default}," +indent = " " +lag = " ${color:green}[${color:brown}${lag}${color:green}]" +nick_prefix = "${color_nick_prefix}${nick_prefix}" +number = "${color:green}${number}${if:${number_displayed}?.: }" + diff --git a/.weechat/charset.conf b/.weechat/charset.conf new file mode 100644 index 0000000..aadbdae --- /dev/null +++ b/.weechat/charset.conf @@ -0,0 +1,11 @@ +# +# charset.conf -- weechat v1.0.1 +# + +[default] +decode = "iso-8859-1" +encode = "" + +[decode] + +[encode] diff --git a/.weechat/exec.conf b/.weechat/exec.conf new file mode 100644 index 0000000..0f713aa --- /dev/null +++ b/.weechat/exec.conf @@ -0,0 +1,11 @@ +# +# exec.conf -- weechat v1.0.1 +# + +[command] +default_options = "" +purge_delay = 0 + +[color] +flag_finished = lightred +flag_running = lightgreen diff --git a/.weechat/irc.conf b/.weechat/irc.conf new file mode 100644 index 0000000..8e5c781 --- /dev/null +++ b/.weechat/irc.conf @@ -0,0 +1,174 @@ +# +# irc.conf -- weechat v1.0.1 +# + +[look] +buffer_switch_autojoin = on +buffer_switch_join = on +color_nicks_in_names = off +color_nicks_in_nicklist = on +color_nicks_in_server_messages = on +color_pv_nick_like_channel = on +ctcp_time_format = "%a, %d %b %Y %T %z" +display_away = local +display_ctcp_blocked = on +display_ctcp_reply = on +display_ctcp_unknown = on +display_host_join = on +display_host_join_local = on +display_host_quit = on +display_join_message = "329,332,333,366" +display_old_topic = on +display_pv_away_once = on +display_pv_back = on +highlight_channel = "$nick" +highlight_pv = "$nick" +highlight_server = "$nick" +highlight_tags_restrict = "irc_privmsg,irc_notice" +item_away_message = on +item_channel_modes_hide_args = "k" +item_display_server = buffer_plugin +item_nick_modes = on +item_nick_prefix = on +join_auto_add_chantype = off +msgbuffer_fallback = current +new_channel_position = none +new_pv_position = none +nick_color_force = "" +nick_color_hash = sum +nick_color_stop_chars = "_|[" +nick_completion_smart = speakers +nick_mode = prefix +nick_mode_empty = off +nicks_hide_password = "nickserv" +notice_as_pv = auto +notice_welcome_redirect = on +notice_welcome_tags = "" +notify_tags_ison = "notify_message" +notify_tags_whois = "notify_message" +part_closes_buffer = off +pv_buffer = independent +pv_tags = "notify_private" +raw_messages = 256 +server_buffer = merge_with_core +smart_filter = on +smart_filter_delay = 5 +smart_filter_join = on +smart_filter_join_unmask = 30 +smart_filter_mode = "+" +smart_filter_nick = on +smart_filter_quit = on +topic_strip_colors = off + +[color] +input_nick = lightcyan +item_away = 130 +item_channel_modes = lightcyan +item_lag_counting = default +item_lag_finished = 130 +item_nick_modes = lightgreen +message_join = green +message_quit = red +mirc_remap = "1,-1:darkgray" +nick_prefixes = "q:lightred;a:lightcyan;o:lightgreen;h:lightmagenta;v:yellow;*:lightblue" +notice = green +reason_quit = default +topic_new = white +topic_old = default + +[network] +autoreconnect_delay_growing = 2 +autoreconnect_delay_max = 600 +ban_mask_default = "*!$ident@$host" +colors_receive = on +colors_send = on +lag_check = 60 +lag_max = 1800 +lag_min_show = 500 +lag_reconnect = 0 +lag_refresh_interval = 1 +notify_check_ison = 1 +notify_check_whois = 5 +send_unknown_commands = off +whois_double_nick = off + +[msgbuffer] + +[ctcp] + +[ignore] + +[server_default] +addresses = "" +anti_flood_prio_high = 2 +anti_flood_prio_low = 2 +autoconnect = off +autojoin = "" +autoreconnect = on +autoreconnect_delay = 10 +autorejoin = off +autorejoin_delay = 30 +away_check = 0 +away_check_max_nicks = 25 +capabilities = "" +command = "" +command_delay = 0 +connection_timeout = 60 +default_msg_kick = "" +default_msg_part = "WeeChat %v" +default_msg_quit = "WeeChat %v" +ipv6 = on +local_hostname = "" +notify = "" +password = "" +proxy = "" +realname = "" +sasl_mechanism = plain +sasl_password = "" +sasl_timeout = 15 +sasl_username = "" +ssl = off +ssl_cert = "" +ssl_dhkey_size = 2048 +ssl_fingerprint = "" +ssl_priorities = "NORMAL" +ssl_verify = on +username = "${env:USER}" + +[server] +tilde.addresses = "localhost" +tilde.proxy +tilde.ipv6 +tilde.ssl +tilde.ssl_cert +tilde.ssl_priorities +tilde.ssl_dhkey_size +tilde.ssl_fingerprint +tilde.ssl_verify +tilde.password +tilde.capabilities +tilde.sasl_mechanism +tilde.sasl_username +tilde.sasl_password +tilde.sasl_timeout +tilde.autoconnect = on +tilde.autoreconnect +tilde.autoreconnect_delay +tilde.nicks +tilde.nicks_alternate +tilde.realname +tilde.local_hostname +tilde.command +tilde.command_delay +tilde.autojoin = "#meta,#team" +tilde.autorejoin +tilde.autorejoin_delay +tilde.connection_timeout +tilde.anti_flood_prio_high +tilde.anti_flood_prio_low +tilde.away_check +tilde.away_check_max_nicks +tilde.default_msg_kick +tilde.default_msg_part +tilde.default_msg_quit +tilde.notify diff --git a/.weechat/iset.conf b/.weechat/iset.conf new file mode 100644 index 0000000..81785f2 --- /dev/null +++ b/.weechat/iset.conf @@ -0,0 +1,30 @@ +# +# iset.conf -- weechat v1.0.1 +# + +[color] +bg_selected = 235 +help_default_value = green +help_option_name = white +help_text = lightcyan +option = default +option_selected = white +type = brown +type_selected = 130 +value = cyan +value_diff = magenta +value_diff_selected = lightmagenta +value_selected = lightcyan +value_undef = green +value_undef_selected = lightgreen + +[help] +show_help_bar = on +show_help_extra_info = on +show_plugin_description = off + +[look] +scroll_horiz = 10 +show_current_line = on +use_mute = off +value_search_char = "=" diff --git a/.weechat/logger.conf b/.weechat/logger.conf new file mode 100644 index 0000000..2b557ff --- /dev/null +++ b/.weechat/logger.conf @@ -0,0 +1,26 @@ +# +# logger.conf -- weechat v1.0.1 +# + +[look] +backlog = 20 + +[color] +backlog_end = default +backlog_line = default + +[file] +auto_log = off +flush_delay = 120 +info_lines = off +mask = "$plugin.$name.weechatlog" +name_lower_case = on +nick_prefix = "" +nick_suffix = "" +path = "%h/logs/" +replacement_char = "_" +time_format = "%Y-%m-%d %H:%M:%S" + +[level] + +[mask] diff --git a/.weechat/perl/autoload/highmon.pl b/.weechat/perl/autoload/highmon.pl new file mode 120000 index 0000000..2eb5e1e --- /dev/null +++ b/.weechat/perl/autoload/highmon.pl @@ -0,0 +1 @@ +../highmon.pl \ No newline at end of file diff --git a/.weechat/perl/autoload/iset.pl b/.weechat/perl/autoload/iset.pl new file mode 120000 index 0000000..2746e0d --- /dev/null +++ b/.weechat/perl/autoload/iset.pl @@ -0,0 +1 @@ +../iset.pl \ No newline at end of file diff --git a/.weechat/perl/highmon.pl b/.weechat/perl/highmon.pl new file mode 100644 index 0000000..1c07712 --- /dev/null +++ b/.weechat/perl/highmon.pl @@ -0,0 +1,1139 @@ +# +# highmon.pl - Highlight Monitoring for weechat 0.3.0 +# Version 2.5 +# +# Add 'Highlight Monitor' buffer/bar to log all highlights in one spot +# +# Usage: +# /highmon [help] | [monitor [channel [server]]] | [clean default|orphan|all] | clearbar +# Command wrapper for highmon commands +# +# /highmon clean default|orphan|all will clean the config section of default 'on' entries, +# channels you are no longer joined, or both +# +# /highmon clearbar will clear the contents of highmon's bar output +# +# /highmon monitor [channel] [server] is used to toggle a highlight monitoring on and off, this +# can be used in the channel buffer for the channel you wish to toggle, or be given +# with arguments e.g. /highmon monitor #weechat freenode +# +# /set plugins.var.perl.highmon.alignment +# The config setting "alignment" can be changed to; +# "channel", "schannel", "nchannel", "channel,nick", "schannel,nick", "nchannel,nick" +# to change how the monitor appears +# The 'channel' value will show: "#weechat" +# The 'schannel' value will show: "6" +# The 'nchannel' value will show: "6:#weechat" +# +# /set plugins.var.perl.highmon.short_names +# Setting this to 'on' will trim the network name from highmon, ala buffers.pl +# +# /set plugins.var.perl.highmon.merge_private +# Setting this to 'on' will merge private messages to highmon's display +# +# /set plugins.var.perl.highmon.color_buf +# This turns colored buffer names on or off, you can also set a single fixed color by using a weechat color name. +# This *must* be a valid color name, or weechat will likely do unexpected things :) +# +# /set plugins.var.perl.highmon.hotlist_show +# Setting this to 'on' will let the highmon buffer appear in hotlists +# (status bar/buffer.pl) +# +# /set plugins.var.perl.highmon.away_only +# Setting this to 'on' will only put messages in the highmon buffer when +# you set your status to away +# +# /set plugins.var.perl.highmon.logging +# Toggles logging status for highmon buffer (default: off) +# +# /set plugins.var.perl.highmon.output +# Changes where output method of highmon; takes either "bar" or "buffer" (default; buffer) +# /set plugins.var.perl.highmon.bar_lines +# Changes the amount of lines the output bar will hold. +# (Only appears once output has been set to bar, defaults to 10) +# /set plugins.var.perl.highmon.bar_scrolldown +# Toggles the bar scrolling at the bottom when new highlights are received +# (Only appears once output has been set to bar, defaults to off) +# +# /set plugins.var.perl.highmon.nick_prefix +# /set plugins.var.perl.highmon.nick_suffix +# Sets the prefix and suffix chars in the highmon buffer +# (Defaults to <> if nothing set, and blank if there is) +# +# servername.#channel +# servername is the internal name for the server (set when you use /server add) +# #channel is the channel name, (where # is whatever channel type that channel happens to be) +# +# Optional, set up tweaks; Hide the status and input lines on highmon +# +# /set weechat.bar.status.conditions "${window.buffer.full_name} != perl.highmon" +# /set weechat.bar.input.conditions "${window.buffer.full_name} != perl.highmon" +# + +# Bugs and feature requests at: https://github.com/KenjiE20/highmon + +# History: +# 2014-08-16, KenjiE20 : +# 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 +# and update hint for conditions to use eval +# -change: Make all outputs use the date callback for more accurate timestamps (thanks Germainz) +# 2013-12-04, KenjiE20 : +# v2.4: -add: Support for eval style colour codes in time format used for bar output +# 2013-10-22, KenjiE20 : +# v2.3.3.2: -fix: Typo in fix command +# 2013-10-10, KenjiE20 : +# v2.3.3.1: -fix: Typo in closed buffer warning +# 2013-10-07, KenjiE20 : +# v2.3.3: -add: Warning and fixer for accidental buffer closes +# 2013-01-15, KenjiE20 : +# v2.3.2: -fix: Let bar output use the string set in weechat's config option +# -add: github info +# 2012-04-15, KenjiE20 : +# v2.3.1: -fix: Colour tags in bar timestamp string +# 2012-02-28, KenjiE20 : +# v2.3: -feature: Added merge_private option to display private messages (default: off) +# -fix: Channel name colours now show correctly when set to on +# 2011-08-07, Sitaktif : +# v2.2.1: -feature: Add "bar_scrolldown" option to have the bar display the latest hl at anytime +# -fix: Set up bar-specific config at startup if 'output' is already configured as 'bar' +# 2010-12-22, KenjiE20 : +# v2.2: -change: Use API instead of config to find channel colours, ready for 0.3.4 and 256 colours +# 2010-12-13, idl0r & KenjiE20 : +# v2.1.3: -fix: perl errors caused by bar line counter +# -fix: Add command list to inbuilt help +# 2010-09-30, KenjiE20 : +# v2.1.2: -fix: logging config was not correctly toggling back on (thanks to sleo for noticing) +# -version sync w/ chanmon +# 2010-08-27, KenjiE20 : +# v2.1: -feature: Add 'nchannel' option to alignment to display buffer and name +# 2010-04-25, KenjiE20 : +# v2.0: Release as version 2.0 +# 2010-04-24, KenjiE20 : +# v1.9: Rewrite for v2.0 +# Bring feature set in line with chanmon 2.0 +# -code change: Made more subs to shrink the code down in places +# -fix: Stop highmon attempting to double load/hook +# -fix: Add version dependant check for away status +# 2010-01-25, KenjiE20 : +# v1.7: -fixture: Let highmon be aware of nick_prefix/suffix +# and allow custom prefix/suffix for chanmon buffer +# (Defaults to <> if nothing set, and blank if there is) +# (Thanks to m4v for these) +# 2009-09-07, KenjiE20 : +# v1.6: -feature: colored buffer names +# -change: version sync with chanmon +# 2009-09-05, KenjiE20 : +# v1.2: -fix: disable buffer highlight +# 2009-09-02, KenjiE20 : +# v.1.1.1 -change: Stop unsightly text block on '/help' +# 2009-08-10, KenjiE20 : +# v1.1: In-client help added +# 2009-08-02, KenjiE20 : +# v1.0: Initial Public Release + +# Copyright (c) 2009 by KenjiE20 +# +# 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 . +# + +@bar_lines = (); +@bar_lines_time = (); +# Replicate info earlier for in-client help + +$highmonhelp = weechat::color("bold")."/highmon [help] | [monitor [channel [server]]] | [clean default|orphan|all] | clearbar".weechat::color("-bold")." + Command wrapper for highmon commands + +".weechat::color("bold")."/highmon clean default|orphan|all".weechat::color("-bold")." will clean the config section of default 'on' entries, channels you are no longer joined, or both + +".weechat::color("bold")."/highmon clearbar".weechat::color("-bold")." will clear the contents of highmon's bar output + +".weechat::color("bold")."/highmon monitor [channel] [server]".weechat::color("-bold")." is used to toggle a highlight monitoring on and off, this can be used in the channel buffer for the channel you wish to toggle, or be given with arguments e.g. /highmon monitor #weechat freenode + +".weechat::color("bold")."/set plugins.var.perl.highmon.alignment".weechat::color("-bold")." + The config setting \"alignment\" can be changed to; + \"channel\", \"schannel\", \"nchannel\", \"channel,nick\", \"schannel,nick\", \"nchannel,nick\" + to change how the monitor appears + The 'channel' value will show: \"#weechat\" + The 'schannel' value will show: \"6\" + The 'nchannel' value will show: \"6:#weechat\" + +".weechat::color("bold")."/set plugins.var.perl.highmon.short_names".weechat::color("-bold")." + Setting this to 'on' will trim the network name from highmon, ala buffers.pl + +".weechat::color("bold")."/set plugins.var.perl.highmon.merge_private".weechat::color("-bold")." + Setting this to 'on' will merge private messages to highmon's display + +".weechat::color("bold")."/set plugins.var.perl.highmon.color_buf".weechat::color("-bold")." + This turns colored buffer names on or off, you can also set a single fixed color by using a weechat color name. + This ".weechat::color("bold")."must".weechat::color("-bold")." be a valid color name, or weechat will likely do unexpected things :) + +".weechat::color("bold")."/set plugins.var.perl.highmon.hotlist_show".weechat::color("-bold")." +Setting this to 'on' will let the highmon buffer appear in hotlists (status bar/buffer.pl) + +".weechat::color("bold")."/set plugins.var.perl.highmon.away_only".weechat::color("-bold")." +Setting this to 'on' will only put messages in the highmon buffer when you set your status to away + +".weechat::color("bold")."/set plugins.var.perl.highmon.logging".weechat::color("-bold")." + Toggles logging status for highmon buffer (default: off) + +".weechat::color("bold")."/set plugins.var.perl.highmon.output".weechat::color("-bold")." + Changes where output method of highmon; takes either \"bar\" or \"buffer\" (default; buffer) +".weechat::color("bold")."/set plugins.var.perl.highmon.bar_lines".weechat::color("-bold")." + Changes the amount of lines the output bar will hold. + (Only appears once output has been set to bar, defaults to 10) +".weechat::color("bold")."/set plugins.var.perl.highmon.bar_scrolldown".weechat::color("-bold")." + Toggles the bar scrolling at the bottom when new highlights are received + (Only appears once output has been set to bar, defaults to off) + +".weechat::color("bold")."/set plugins.var.perl.highmon.nick_prefix".weechat::color("-bold")." +".weechat::color("bold")."/set plugins.var.perl.highmon.nick_suffix".weechat::color("-bold")." + Sets the prefix and suffix chars in the highmon buffer + (Defaults to <> if nothing set, and blank if there is) + +".weechat::color("bold")."servername.#channel".weechat::color("-bold")." + servername is the internal name for the server (set when you use /server add) + #channel is the channel name, (where # is whatever channel type that channel happens to be) + +".weechat::color("bold")."Optional, set up tweaks;".weechat::color("-bold")." Hide the status and input lines on highmon + +".weechat::color("bold")."/set weechat.bar.status.conditions \"\${window.buffer.full_name} != perl.highmon\"".weechat::color("-bold")." +".weechat::color("bold")."/set weechat.bar.input.conditions \"\${window.buffer.full_name} != perl.highmon\"".weechat::color("-bold"); +# Print verbose help +sub print_help +{ + weechat::print("", "\t".weechat::color("bold")."Highmon Help".weechat::color("-bold")."\n\n"); + weechat::print("", "\t".$highmonhelp); + return weechat::WEECHAT_RC_OK; +} + +# Bar item build +sub highmon_bar_build +{ + # Get max lines + $max_lines = weechat::config_get_plugin("bar_lines"); + $max_lines = $max_lines ? $max_lines : 10; + $str = ''; + $align_num = 0; + $count = 0; + # Keep lines within max + while ($#bar_lines > $max_lines) + { + shift(@bar_lines); + shift(@bar_lines_time); + } + # So long as we have some lines, build a string + if (@bar_lines) + { + # Build loop + $sep = " ".weechat::config_string(weechat::config_get("weechat.look.prefix_suffix"))." "; + foreach(@bar_lines) + { + # Find max align needed + $prefix_num = (index(weechat::string_remove_color($_, ""), $sep)); + $align_num = $prefix_num if ($prefix_num > $align_num); + } + foreach(@bar_lines) + { + # Get align for this line + $prefix_num = (index(weechat::string_remove_color($_, ""), $sep)); + + # Make string + $str = $str.$bar_lines_time[$count]." ".(" " x ($align_num - $prefix_num)).$_."\n"; + # Increment count for sync with time list + $count++; + } + } + return $str; +} + +# Make a new bar +sub highmon_bar_open +{ + # Make the bar item + weechat::bar_item_new("highmon", "highmon_bar_build", ""); + + $highmon_bar = weechat::bar_new ("highmon", "off", 100, "root", "", "bottom", "vertical", "vertical", 0, 0, "default", "cyan", "default", "on", "highmon"); + + return weechat::WEECHAT_RC_OK; +} +# Close bar +sub highmon_bar_close +{ + # Find if bar exists + $highmon_bar = weechat::bar_search("highmon"); + # If is does, close it + if ($highmon_bar ne "") + { + weechat::bar_remove($highmon_bar); + } + + # Find if bar item exists + $highmon_bar_item = weechat::bar_item_search("highmon_bar"); + # If is does, close it + if ($highmon_bar_item ne "") + { + weechat::bar_remove($highmon_bar_item); + } + + @bar_lines = (); + return weechat::WEECHAT_RC_OK; +} + +# Make a new buffer +sub highmon_buffer_open +{ + # Search for pre-existing buffer + $highmon_buffer = weechat::buffer_search("perl", "highmon"); + + # Make a new buffer + if ($highmon_buffer eq "") + { + $highmon_buffer = weechat::buffer_new("highmon", "highmon_buffer_input", "", "highmon_buffer_close", ""); + } + + # Turn off notify, highlights + if ($highmon_buffer ne "") + { + if (weechat::config_get_plugin("hotlist_show" eq "off")) + { + weechat::buffer_set($highmon_buffer, "notify", "0"); + } + weechat::buffer_set($highmon_buffer, "highlight_words", "-"); + weechat::buffer_set($highmon_buffer, "title", "Highlight Monitor"); + # Set no_log + if (weechat::config_get_plugin("logging") eq "off") + { + weechat::buffer_set($highmon_buffer, "localvar_set_no_log", "1"); + } + } + return weechat::WEECHAT_RC_OK; +} +# Buffer input has no action +sub highmon_buffer_input +{ + return weechat::WEECHAT_RC_OK; +} +# Close up +sub highmon_buffer_close +{ + $highmon_buffer = ""; + # If user hasn't changed output style warn user + if (weechat::config_get_plugin("output") eq "buffer") + { + weechat::print("", "\tHighmon buffer has been closed but output is still set to buffer, unusual results may occur. To recreate the buffer use ".weechat::color("bold")."/highmon fix".weechat::color("-bold")); + } + return weechat::WEECHAT_RC_OK; +} + +# Highmon command wrapper +sub highmon_command_cb +{ + $data = $_[0]; + $buffer = $_[1]; + $args = $_[2]; + my $cmd = ''; + my $arg = ''; + + if ($args ne "") + { + # Split argument up + @arg_array = split(/ /,$args); + # Take first as command + $cmd = shift(@arg_array); + # Rebuild string to pass to subs + if (@arg_array) + { + $arg = join(" ", @arg_array); + } + } + + # Help command + if ($cmd eq "" || $cmd eq "help") + { + print_help(); + } + # /monitor command + elsif ($cmd eq "monitor") + { + highmon_toggle($data, $buffer, $arg); + } + # /highclean command + elsif ($cmd eq "clean") + { + highmon_config_clean($data, $buffer, $arg); + } + # clearbar command + elsif ($cmd eq "clearbar") + { + if (weechat::config_get_plugin("output") eq "bar") + { + @bar_lines = (); + weechat::bar_item_update("highmon"); + } + } + # Fix closed buffer + elsif ($cmd eq "fix") + { + if (weechat::config_get_plugin("output") eq "buffer" && $highmon_buffer eq "") + { + highmon_buffer_open(); + } + } + return weechat::WEECHAT_RC_OK; +} + +# Clean up config entries +sub highmon_config_clean +{ + $data = $_[0]; + $buffer = $_[1]; + $args = $_[2]; + + # Don't do anything if bad option given + if ($args ne "default" && $args ne "orphan" && $args ne "all") + { + weechat::print("", "\thighmon.pl: Unknown option"); + return weechat::WEECHAT_RC_OK; + } + + @chans = (); + # Load an infolist of highmon options + $infolist = weechat::infolist_get("option", "", "*highmon*"); + while (weechat::infolist_next($infolist)) + { + $name = weechat::infolist_string($infolist, "option_name"); + $name =~ s/perl\.highmon\.(\w*)\.([#&\+!])(.*)/$1.$2$3/; + if ($name =~ /^(.*)\.([#&\+!])(.*)$/) + { + $action = 0; + # Clean up all 'on's + if ($args eq "default" || $args eq "all") + { + # If value in config is "on" + if (weechat::config_get_plugin($name) eq "on") + { + # Unset and if successful flag as changed + $rc = weechat::config_unset_plugin($name); + if ($rc eq weechat::WEECHAT_CONFIG_OPTION_UNSET_OK_REMOVED) + { + $action = 1; + } + } + } + # Clean non joined + if ($args eq "orphan" || $args eq "all") + { + # If we can't find the buffer for this entry + if (weechat::buffer_search("irc", $name) eq "") + { + # Unset and if successful flag as changed + $rc = weechat::config_unset_plugin($name); + if ($rc eq weechat::WEECHAT_CONFIG_OPTION_UNSET_OK_REMOVED) + { + $action = 1; + } + } + } + # Add changed entry names to list + push (@chans, $name) if ($action); + } + } + weechat::infolist_free($infolist); + # If channels were cleaned from config + if (@chans) + { + # If only one entry + if (@chans == 1) + { + $str = "\thighmon.pl: Cleaned ".@chans." entry from the config:"; + } + else + { + $str = "\thighmon.pl: Cleaned ".@chans." entries from the config:"; + } + # Build a list of channels + foreach(@chans) + { + $str = $str." ".$_; + } + # Print what happened + weechat::print("",$str); + } + # Config seemed to be clean + else + { + weechat::print("", "\thighmon.pl: No entries removed"); + } + return weechat::WEECHAT_RC_OK; +} + +# Check config elements +sub highmon_config_init +{ + # First run default + if (!(weechat::config_is_set_plugin ("first_run"))) + { + if (weechat::config_get_plugin("first_run") ne "true") + { + weechat::print("", "\tThis appears to be the first time highmon has been run. For help and common set up hints see /highmon help"); + weechat::config_set_plugin("first_run", "true"); + } + } + # Alignment default + if (!(weechat::config_is_set_plugin ("alignment"))) + { + weechat::config_set_plugin("alignment", "channel"); + } + if (weechat::config_get_plugin("alignment") eq "") + { + weechat::config_set_plugin("alignment", "none"); + } + + # Short name default + if (!(weechat::config_is_set_plugin ("short_names"))) + { + weechat::config_set_plugin("short_names", "off"); + } + + # Coloured names default + if (!(weechat::config_is_set_plugin ("color_buf"))) + { + weechat::config_set_plugin("color_buf", "on"); + } + + # Hotlist show default + if (!(weechat::config_is_set_plugin ("hotlist_show"))) + { + weechat::config_set_plugin("hotlist_show", "off"); + } + + # Away only default + if (!(weechat::config_is_set_plugin ("away_only"))) + { + weechat::config_set_plugin("away_only", "off"); + } + + # highmon log default + if (!(weechat::config_is_set_plugin ("logging"))) + { + weechat::config_set_plugin("logging", "off"); + } + + # Output default + if (!(weechat::config_is_set_plugin ("output"))) + { + weechat::config_set_plugin("output", "buffer"); + } + + # Private message merging + if (!(weechat::config_is_set_plugin ("merge_private"))) + { + weechat::config_set_plugin("merge_private", "off"); + } + + # Set bar config in case output was set to "bar" before even changing the setting + if (weechat::config_get_plugin("output") eq "bar") + { + # Output bar lines default + if (!(weechat::config_is_set_plugin ("bar_lines"))) + { + weechat::config_set_plugin("bar_lines", "10"); + } + if (!(weechat::config_is_set_plugin ("bar_scrolldown"))) + { + weechat::config_set_plugin("bar_scrolldown", "off"); + } + } + + # Check for exisiting prefix/suffix chars, and setup accordingly + $prefix = weechat::config_get("irc.look.nick_prefix"); + $prefix = weechat::config_string($prefix); + $suffix = weechat::config_get("irc.look.nick_suffix"); + $suffix = weechat::config_string($suffix); + + if (!(weechat::config_is_set_plugin("nick_prefix"))) + { + if ($prefix eq "" && $suffix eq "") + { + weechat::config_set_plugin("nick_prefix", "<"); + } + else + { + weechat::config_set_plugin("nick_prefix", ""); + } + } + + if (!(weechat::config_is_set_plugin("nick_suffix"))) + { + if ($prefix eq "" && $suffix eq "") + { + weechat::config_set_plugin("nick_suffix", ">"); + } + else + { + weechat::config_set_plugin("nick_suffix", ""); + } + } +} + +# Get config updates +sub highmon_config_cb +{ + $point = $_[0]; + $name = $_[1]; + $value = $_[2]; + + $name =~ s/^plugins\.var\.perl\.highmon\.//; + + # Set logging on buffer + if ($name eq "logging") + { + # Search for pre-existing buffer + $highmon_buffer = weechat::buffer_search("perl", "highmon"); + if ($value eq "off") + { + weechat::buffer_set($highmon_buffer, "localvar_set_no_log", "1"); + } + else + { + weechat::buffer_set($highmon_buffer, "localvar_del_no_log", ""); + } + } + # Output changer + elsif ($name eq "output") + { + if ($value eq "bar") + { + # Search for pre-existing buffer + $highmon_buffer = weechat::buffer_search("perl", "highmon"); + # Close if it exists + if ($highmon_buffer ne "") + { + weechat::buffer_close($highmon_buffer) + } + + # Output bar lines default + if (!(weechat::config_is_set_plugin ("bar_lines"))) + { + weechat::config_set_plugin("bar_lines", "10"); + } + if (!(weechat::config_is_set_plugin ("bar_scrolldown"))) + { + weechat::config_set_plugin("bar_scrolldown", "off"); + } + # Make a bar if doesn't exist + highmon_bar_open(); + } + elsif ($value eq "buffer") + { + # If a bar exists, close it + highmon_bar_close(); + # Open buffer + highmon_buffer_open(); + } + + } + # Change if hotlist config changes + elsif ($name eq "hotlist_show") + { + # Search for pre-existing buffer + $highmon_buffer = weechat::buffer_search("perl", "highmon"); + if ($value eq "off" && $highmon_buffer) + { + weechat::buffer_set($highmon_buffer, "notify", "0"); + } + elsif ($value ne "off" && $highmon_buffer) + { + weechat::buffer_set($highmon_buffer, "notify", "3"); + } + } + elsif ($name eq "weechat.look.prefix_suffix") + { + if (weechat::config_get_plugin("output") eq "bar") + { + @bar_lines = (); + weechat::print("", "\thighmon: weechat.look.prefix_suffix changed, clearing highmon bar"); + weechat::bar_item_update("highmon"); + } + } + return weechat::WEECHAT_RC_OK; +} + +# Set up weechat hooks / commands +sub highmon_hook +{ + weechat::hook_print("", "", "", 0, "highmon_new_message", ""); + weechat::hook_command("highclean", "Highmon config clean up", "default|orphan|all", " default: Cleans all config entries with the default \"on\" value\n orphan: Cleans all config entries for channels you aren't currently joined\n all: Does both defaults and orphan", "default|orphan|all", "highmon_config_clean", ""); + + weechat::hook_command("highmon", "Highmon help", "[help] | [monitor [channel [server]]] | [clean default|orphan|all] | clearbar", " help: Print help on config options for highmon\n monitor: Toggles monitoring for a channel\n clean: Highmon config clean up (/highclean)\nclearbar: Clear Highmon bar", "help || monitor %(irc_channels) %(irc_servers) || clean default|orphan|all || clearbar", "highmon_command_cb", ""); + + weechat::hook_config("plugins.var.perl.highmon.*", "highmon_config_cb", ""); + weechat::hook_config("weechat.look.prefix_suffix", "highmon_config_cb", ""); +} + +# Main body, Callback for hook_print +sub highmon_new_message +{ + my $net = ""; + my $chan = ""; + my $nick = ""; + my $outstr = ""; + my $window_displayed = ""; + my $dyncheck = "0"; + +# DEBUG point +# $string = "\t"."0: ".$_[0]." 1: ".$_[1]." 2: ".$_[2]." 3: ".$_[3]." 4: ".$_[4]." 5: ".$_[5]." 6: ".$_[6]." 7: ".$_[7]; +# weechat::print("", "\t".$string); + + $cb_datap = $_[0]; + $cb_bufferp = $_[1]; + $cb_date = $_[2]; + $cb_tags = $_[3]; + $cb_disp = $_[4]; + $cb_high = $_[5]; + $cb_prefix = $_[6]; + $cb_msg = $_[7]; + + # Only work on highlighted messages or private message when enabled + if ($cb_high == "1" || (weechat::config_get_plugin("merge_private") eq "on" && $cb_tags =~ /notify_private/)) + { + # Pre bug #29618 (0.3.3) away detect + if (weechat::info_get("version_number", "") <= 197120) + { + $away = ''; + # Get infolist for this server + $infolist = weechat::infolist_get("irc_server", "", weechat::buffer_get_string($cb_bufferp, "localvar_server")); + while (weechat::infolist_next($infolist)) + { + # Get away message is is_away is on + $away = weechat::infolist_string($infolist, "away_message") if (weechat::infolist_integer($infolist, "is_away")); + } + weechat::infolist_free($infolist); + } + # Post bug #29618 fix + else + { + $away = weechat::buffer_get_string($cb_bufferp, "localvar_away"); + } + if (weechat::config_get_plugin("away_only") ne "on" || ($away ne "")) + { + # Check buffer name is an IRC channel + $bufname = weechat::buffer_get_string($cb_bufferp, 'name'); + if ($bufname =~ /(.*)\.([#&\+!])(.*)/) + { + # Are we running on this channel + if (weechat::config_get_plugin($bufname) ne "off" && $cb_disp eq "1") + { + # Format nick + # Line isn't action or topic notify + if (!($cb_tags =~ /irc_action/) && !($cb_tags =~ /irc_topic/)) + { + # Strip nick colour + $uncolnick = weechat::string_remove_color($cb_prefix, ""); + # Format nick + $nick = " ".weechat::config_get_plugin("nick_prefix").weechat::color("chat_highlight").$uncolnick.weechat::color("reset").weechat::config_get_plugin("nick_suffix"); + } + # Topic line + elsif ($cb_tags =~ /irc_topic/) + { + $nick = " ".$cb_prefix.weechat::color("reset"); + } + # Action line + else + { + $uncolnick = weechat::string_remove_color($cb_prefix, ""); + $nick = weechat::color("chat_highlight").$uncolnick.weechat::color("reset"); + } + # Send to output + highmon_print ($cb_msg, $cb_bufferp, $nick, $cb_date, $cb_tags); + } + } + # Or is private message + elsif (weechat::config_get_plugin("merge_private") eq "on" && $cb_tags =~ /notify_private/) + { + # Strip nick colour + $uncolnick = weechat::buffer_get_string($cb_bufferp, 'short_name'); + # Format nick + $nick = " ".weechat::config_get_plugin("nick_prefix").weechat::color("chat_highlight").$uncolnick.weechat::color("reset").weechat::config_get_plugin("nick_suffix"); + #Send to output + highmon_print ($cb_msg, $cb_bufferp, $nick, $cb_date, $cb_tags); + } + } + } + return weechat::WEECHAT_RC_OK; +} + +# Output formatter and printer takes (msg bufpointer nick) +sub highmon_print +{ + $cb_msg = $_[0]; + my $cb_bufferp = $_[1] if ($_[1]); + my $nick = $_[2] if ($_[2]); + my $cb_date = $_[3] if ($_[3]); + my $cb_tags = $_[4] if ($_[4]); + + #Normal channel message + if ($cb_bufferp && $nick) + { + # Format buffer name + $bufname = format_buffer_name($cb_bufferp); + + # If alignment is #channel | nick msg + if (weechat::config_get_plugin("alignment") eq "channel") + { + $nick =~ s/\s(.*)/$1/; + # Build string + $outstr = $bufname."\t".$nick." ".$cb_msg; + } + # or if it is channel number | nick msg + elsif (weechat::config_get_plugin("alignment") eq "schannel") + { + $nick =~ s/\s(.*)/$1/; + # Use channel number instead + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').weechat::color("reset"); + # Build string + $outstr = $bufname."\t".$nick." ".$cb_msg; + } + # or if it is number:#channel | nick msg + elsif (weechat::config_get_plugin("alignment") eq "nchannel") + { + $nick =~ s/\s(.*)/$1/; + # Place channel number in front of formatted name + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').":".weechat::color("reset").$bufname; + # Build string + $outstr = $bufname."\t".$nick." ".$cb_msg; + } + # or if it is #channel nick | msg + elsif (weechat::config_get_plugin("alignment") eq "channel,nick") + { + # Build string + $outstr = $bufname.":".$nick."\t".$cb_msg; + } + # or if it is channel number nick | msg + elsif (weechat::config_get_plugin("alignment") eq "schannel,nick") + { + # Use channel number instead + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').weechat::color("reset"); + # Build string + $outstr = $bufname.":".$nick."\t".$cb_msg; + } + # or if it is number:#channel nick | msg + elsif (weechat::config_get_plugin("alignment") eq "nchannel,nick") + { + # Place channel number in front of formatted name + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').":".weechat::color("reset").$bufname; + # Build string + $outstr = $bufname.":".$nick."\t".$cb_msg; + } + # or finally | #channel nick msg + else + { + # Build string + $outstr = "\t".$bufname.":".$nick." ".$cb_msg; + } + } + # highmon channel toggle message + elsif ($cb_bufferp && !$nick) + { + # Format buffer name + $bufname = format_buffer_name($cb_bufferp); + + # If alignment is #channel * | * + if (weechat::config_get_plugin("alignment") =~ /channel/) + { + # If it's actually channel number * | * + if (weechat::config_get_plugin("alignment") =~ /schannel/) + { + # Use channel number instead + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').weechat::color("reset"); + } + # Or if it's actually number:#channel * | * + if (weechat::config_get_plugin("alignment") =~ /nchannel/) + { + # Place channel number in front of formatted name + $bufname = weechat::color("chat_prefix_buffer").weechat::buffer_get_integer($cb_bufferp, 'number').":".weechat::color("reset").$bufname; + } + $outstr = $bufname."\t".$cb_msg; + } + # or if alignment is | * + else + { + $outstr = $bufname.": ".$cb_msg; + } + } + # highmon dynmon + elsif (!$cb_bufferp && !$nick) + { + $outstr = "\t".$cb_msg; + } + + # Send string to buffer + if (weechat::config_get_plugin("output") eq "buffer") + { + # Search for and confirm buffer + $highmon_buffer = weechat::buffer_search("perl", "highmon"); + # Print + if ($cb_date) + { + weechat::print_date_tags($highmon_buffer, $cb_date, $cb_tags, $outstr); + } + else + { + weechat::print($highmon_buffer, $outstr); + } + } + elsif (weechat::config_get_plugin("output") eq "bar") + { + # Add time string + use POSIX qw(strftime); + if ($cb_date) + { + $time = strftime(weechat::config_string(weechat::config_get("weechat.look.buffer_time_format")), localtime($cb_date)); + } + else + { + $time = strftime(weechat::config_string(weechat::config_get("weechat.look.buffer_time_format")), localtime); + } + # Colourise + if ($time =~ /\$\{(?:color:)?[\w,]+\}/) # Coloured string + { + while ($time =~ /\$\{(?:color:)?([\w,]+)\}/) + { + $color = weechat::color($1); + $time =~ s/\$\{(?:color:)?[\w,]+\}/$color/; + } + $time .= weechat::color("reset"); + } + else # Default string + { + $colour = weechat::color(weechat::config_string(weechat::config_get("weechat.color.chat_time_delimiters"))); + $reset = weechat::color("reset"); + $time =~ s/(\d*)(.)(\d*)/$1$colour$2$reset$3/g; + } + # Push updates to bar lists + push (@bar_lines_time, $time); + + # Change tab char + $delim = " ".weechat::color(weechat::config_string(weechat::config_get("weechat.color.chat_delimiters"))).weechat::config_string(weechat::config_get("weechat.look.prefix_suffix")).weechat::color("reset")." "; + $outstr =~ s/\t/$delim/; + + push (@bar_lines, $outstr); + # Trigger update + weechat::bar_item_update("highmon"); + + if (weechat::config_get_plugin("bar_scrolldown") eq "on") + { + weechat::command("", "/bar scroll highmon * ye") + } + } +} + +# Start the output display +sub highmon_start +{ + if (weechat::config_get_plugin("output") eq "buffer") + { + highmon_buffer_open(); + } + elsif (weechat::config_get_plugin("output") eq "bar") + { + highmon_bar_open(); + } +} + +# Takes two optional args (channel server), toggles monitoring on/off +sub highmon_toggle +{ + $data = $_[0]; + $buffer = $_[1]; + $args = $_[2]; + + # Check if we've been told what channel to act on + if ($args ne "") + { + # Split argument up + @arg_array = split(/ /,$args); + # Check if a server was given + if ($arg_array[1]) + { + # Find matching + $bufp = weechat::buffer_search("irc", $arg_array[1].".".$arg_array[0]); + } + else + { + $found_chans = 0; + # Loop through defined servers + $infolist = weechat::infolist_get("buffer", "", ""); + while (weechat::infolist_next($infolist)) + { + # Only interesting in IRC buffers + if (weechat::infolist_string($infolist, "plugin_name") eq "irc") + { + # Find buffers that maych + $sname = weechat::infolist_string($infolist, "short_name"); + if ($sname eq $arg_array[0]) + { + $found_chans++; + $bufp = weechat::infolist_pointer($infolist, "pointer"); + } + } + } + weechat::infolist_free($infolist); + # If the infolist found more than one channel, halt as we need to know which one + if ($found_chans > 1) + { + weechat::print("", "Channel name is not unique, please define server"); + return weechat::WEECHAT_RC_OK; + } + } + # Something didn't return right + if ($bufp eq "") + { + weechat::print("", "Could not find buffer"); + return weechat::WEECHAT_RC_OK; + } + } + else + { + # Get pointer from where we are + $bufp = weechat::current_buffer(); + } + # Get buffer name + $bufname = weechat::buffer_get_string($bufp, 'name'); + # Test if buffer is an IRC channel + if ($bufname =~ /(.*)\.([#&\+!])(.*)/) + { + if (weechat::config_get_plugin($bufname) eq "off") + { + # If currently off, set on + weechat::config_set_plugin($bufname, "on"); + + # Send to output formatter + highmon_print("Highlight Monitoring Enabled", $bufp); + return weechat::WEECHAT_RC_OK; + } + elsif (weechat::config_get_plugin($bufname) eq "on" || weechat::config_get_plugin($bufname) eq "") + { + # If currently on, set off + weechat::config_set_plugin($bufname, "off"); + + # Send to output formatter + highmon_print("Highlight Monitoring Disabled", $bufp); + return weechat::WEECHAT_RC_OK; + } + } +} + +# Takes a buffer pointer and returns a formatted name +sub format_buffer_name +{ + $cb_bufferp = $_[0]; + $bufname = weechat::buffer_get_string($cb_bufferp, 'name'); + + # Set colour from buffer name + if (weechat::config_get_plugin("color_buf") eq "on") + { + # Determine what colour to use + $color = weechat::info_get("irc_nick_color", $bufname); + if (!$color) + { + $color = 0; + @char_array = split(//,$bufname); + foreach $char (@char_array) + { + $color += ord($char); + } + $color %= 10; + $color = sprintf "weechat.color.chat_nick_color%02d", $color+1; + $color = weechat::config_get($color); + $color = weechat::config_string($color); + $color = weechat::color($color); + } + + # Private message just show network + if (weechat::config_get_plugin("merge_private") eq "on" && weechat::buffer_get_string($cb_bufferp, "localvar_type") eq "private") + { + $bufname = weechat::buffer_get_string($cb_bufferp, "localvar_server"); + } + # Format name to short or 'nicename' + elsif (weechat::config_get_plugin("short_names") eq "on") + { + $bufname = weechat::buffer_get_string($cb_bufferp, 'short_name'); + } + else + { + $bufname =~ s/(.*)\.([#&\+!])(.*)/$1$2$3/; + } + + # Build a coloured string + $bufname = $color.$bufname.weechat::color("reset"); + } + # User set colour name + elsif (weechat::config_get_plugin("color_buf") ne "off") + { + # Private message just show network + if (weechat::config_get_plugin("merge_private") eq "on" && weechat::buffer_get_string($cb_bufferp, "localvar_type") eq "private") + { + $bufname = weechat::buffer_get_string($cb_bufferp, "localvar_server"); + } + # Format name to short or 'nicename' + elsif (weechat::config_get_plugin("short_names") eq "on") + { + $bufname = weechat::buffer_get_string($cb_bufferp, 'short_name'); + } + else + { + $bufname =~ s/(.*)\.([#&\+!])(.*)/$1$2$3/; + } + + $color = weechat::config_get_plugin("color_buf"); + $bufname = weechat::color($color).$bufname.weechat::color("reset"); + } + # Stick with default colour + else + { + # Private message just show network + if (weechat::config_get_plugin("merge_private") eq "on" && weechat::buffer_get_string($cb_bufferp, "localvar_type") eq "private") + { + $bufname = weechat::buffer_get_string($cb_bufferp, "localvar_server"); + } + # Format name to short or 'nicename' + elsif (weechat::config_get_plugin("short_names") eq "on") + { + $bufname = weechat::buffer_get_string($cb_bufferp, 'short_name'); + } + else + { + $bufname =~ s/(.*)\.([#&\+!])(.*)/$1$2$3/; + } + } + + return $bufname; +} + +# Check result of register, and attempt to behave in a sane manner +if (!weechat::register("highmon", "KenjiE20", "2.5", "GPL3", "Highlight Monitor", "", "")) +{ + # Double load + weechat::print ("", "\tHighmon is already loaded"); + return weechat::WEECHAT_RC_OK; +} +else +{ + # Start everything + highmon_hook(); + highmon_config_init(); + highmon_start(); +} diff --git a/.weechat/perl/iset.pl b/.weechat/perl/iset.pl new file mode 100644 index 0000000..f179022 --- /dev/null +++ b/.weechat/perl/iset.pl @@ -0,0 +1,1462 @@ +# +# Copyright (C) 2008-2014 Sebastien Helleu +# Copyright (C) 2010-2014 Nils Görs +# +# 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 . +# +# Set WeeChat and plugins options interactively. +# +# History: +# +# 2014-09-30, arza : +# version 3.6: fix current line counter when options aren't found +# 2014-06-03, nils_2 : +# version 3.5: add new option "use_mute" +# 2014-01-30, stfn : +# version 3.4: add new options "color_value_diff" and "color_value_diff_selected" +# 2014-01-16, luz : +# version 3.3: fix bug with column alignment in iset buffer when option +# name contains unicode characters +# 2013-08-03, Sebastien Helleu : +# version 3.2: allow "q" as input in iset buffer to close it +# 2013-07-14, Sebastien Helleu : +# version 3.1: remove unneeded calls to iset_refresh() in mouse callback +# (faster mouse actions when lot of options are displayed), +# fix bug when clicking on a line after the last option displayed +# 2013-04-30, arza : +# version 3.0: simpler title, fix refresh on unset +# 2012-12-16, nils_2 : +# version 2.9: fix focus window with iset buffer on mouse click +# 2012-08-25, nils_2 : +# version 2.8: most important key and mouse bindings for iset buffer added to title-bar (idea The-Compiler) +# 2012-07-31, nils_2 : +# version 2.7: add combined option and value search (see /help iset) +# : add exact value search (see /help iset) +# : fix problem with metacharacter in value search +# : fix use of uninitialized value for unset option and reset value of option +# 2012-07-25, nils_2 : +# version 2.6: switch to iset buffer (if existing) when command /iset is called with arguments +# 2012-03-17, Sebastien Helleu : +# version 2.5: fix check of sections when creating config file +# 2012-03-09, Sebastien Helleu : +# version 2.4: fix reload of config file +# 2012-02-02, nils_2 : +# version 2.3: fixed: refresh problem with new search results and cursor was outside window. +# : add: new option "current_line" in title bar +# version 2.2: fixed: refresh error when toggling plugins description +# 2011-11-05, nils_2 : +# version 2.1: use own config file (iset.conf), fix own help color (used immediately) +# 2011-10-16, nils_2 : +# version 2.0: add support for left-mouse-button and more sensitive mouse gesture (for integer/color options) +# add help text for mouse support +# 2011-09-20, Sebastien Helleu : +# version 1.9: add mouse support, fix iset buffer, fix errors on first load under FreeBSD +# 2011-07-21, nils_2 : +# version 1.8: added: option "show_plugin_description" (alt+p) +# fixed: typos in /help iset (lower case for alt+'x' keys) +# 2011-05-29, nils_2 : +# version 1.7: added: version check for future needs +# added: new option (scroll_horiz) and usage of scroll_horiz function (weechat >= 0.3.6 required) +# fixed: help_bar did not pop up immediately using key-shortcut +# 2011-02-19, nils_2 : +# version 1.6: added: display of all possible values in help bar (show_help_extra_info) +# fixed: external user options never loaded when starting iset first time +# 2011-02-13, Sebastien Helleu : +# version 1.5: use new help format for command arguments +# 2011-02-03, nils_2 : +# version 1.4: fixed: restore value filter after /upgrade using buffer local variable. +# 2011-01-14, nils_2 : +# version 1.3: added function to search for values (option value_search_char). +# code optimization. +# 2010-12-26, Sebastien Helleu : +# version 1.2: improve speed of /upgrade when iset buffer is open, +# restore filter used after /upgrade using buffer local variable, +# use /iset filter argument if buffer is open. +# 2010-11-21, drubin : +# version 1.1.1: fix bugs with cursor position +# 2010-11-20, nils_2 : +# version 1.1: cursor position set to value +# 2010-08-03, Sebastien Helleu : +# version 1.0: move misplaced call to infolist_free() +# 2010-02-02, rettub : +# version 0.9: turn all the help stuff off if option 'show_help_bar' is 'off', +# new key binding - to toggle help_bar and help stuff on/off +# 2010-01-30, nils_2 : +# version 0.8: fix error when option does not exist +# 2010-01-24, Sebastien Helleu : +# version 0.7: display iset bar only on iset buffer +# 2010-01-22, nils_2 and drubin: +# version 0.6: add description in a bar, fix singular/plural bug in title bar, +# fix selected line when switching buffer +# 2009-06-21, Sebastien Helleu : +# version 0.5: fix bug with iset buffer after /upgrade +# 2009-05-02, Sebastien Helleu : +# version 0.4: sync with last API changes +# 2009-01-04, Sebastien Helleu : +# version 0.3: open iset buffer when /iset command is executed +# 2009-01-04, Sebastien Helleu : +# version 0.2: use null values for options, add colors, fix refresh bugs, +# use new keys to reset/unset options, sort options by name, +# display number of options in buffer's title +# 2008-11-05, Sebastien Helleu : +# version 0.1: first official version +# 2008-04-19, Sebastien Helleu : +# script creation + +use strict; + +my $PRGNAME = "iset"; +my $VERSION = "3.6"; +my $DESCR = "Interactive Set for configuration options"; +my $AUTHOR = "Sebastien Helleu "; +my $LICENSE = "GPL3"; +my $LANG = "perl"; +my $ISET_CONFIG_FILE_NAME = "iset"; + +my $iset_config_file; +my $iset_buffer = ""; +my $wee_version_number = 0; +my @iset_focus = (); +my @options_names = (); +my @options_types = (); +my @options_values = (); +my @options_default_values = (); +my @options_is_null = (); +my $option_max_length = 0; +my $current_line = 0; +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 +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"; +my $help_text_mouse = "Mouse: left: select, right: toggle/set, right + drag left/right: increase/decrease"; +my %options_iset; + +my %mouse_keys = ("\@chat(perl.$PRGNAME):button1" => "hsignal:iset_mouse", + "\@chat(perl.$PRGNAME):button2*" => "hsignal:iset_mouse", + "\@chat(perl.$PRGNAME):wheelup" => "/repeat 5 /iset **up", + "\@chat(perl.$PRGNAME):wheeldown" => "/repeat 5 /iset **down"); + + +sub iset_title +{ + if ($iset_buffer ne "") + { + my $current_line_counter = ""; + if (weechat::config_boolean($options_iset{"show_current_line"}) == 1) + { + if (@options_names eq 0) + { + $current_line_counter = "0/"; + } + else + { + $current_line_counter = ($current_line + 1) . "/"; + } + } + my $show_filter = ""; + if ($search_mode eq 0) + { + $iset_filter_title = "(value) "; + $show_filter = $search_value; + if ( substr($show_filter,0,1) eq weechat::config_string($options_iset{"value_search_char"}) ) + { + $show_filter = substr($show_filter,1,length($show_filter)); + } + } + elsif ($search_mode eq 1) + { + $iset_filter_title = "(value) "; + $show_filter = "*".$search_value."*"; + } + elsif ($search_mode eq 2) + { + $iset_filter_title = ""; + $filter = "*" if ($filter eq ""); + $show_filter = $filter; + } + elsif ($search_mode eq 3) + { + $iset_filter_title = "(option) "; + $show_filter = $filter + .weechat::color("default") + ." / (value) " + .weechat::color("yellow") + ."*".$search_value."*"; + } + weechat::buffer_set($iset_buffer, "title", + $iset_filter_title + .weechat::color("yellow") + .$show_filter + .weechat::color("default")." | " + .$current_line_counter + .@options_names + ." | " + .$help_text_keys + ." | " + .$help_text_mouse); + } +} + +sub iset_create_filter +{ + $filter = $_[0]; + if ( $search_mode == 3 ) + { + my @cmd_array = split(/ /,$filter); + my $array_count = @cmd_array; + $filter = $cmd_array[0]; + $filter = $cmd_array[0] . " " . $cmd_array[1] if ( $array_count >2 ); + } + $filter = "$1.*" if ($filter =~ /f (.*)/); # search file + $filter = "*.$1.*" if ($filter =~ /s (.*)/); # search section + if ((substr($filter, 0, 1) ne "*") && (substr($filter, -1, 1) ne "*")) + { + $filter = "*".$filter."*"; + } + if ($iset_buffer ne "") + { + weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $filter); + } +} + +sub iset_buffer_input +{ + my ($data, $buffer, $string) = ($_[0], $_[1], $_[2]); + if ($string eq "q") + { + weechat::buffer_close($buffer); + return weechat::WEECHAT_RC_OK; + } + $search_value = ""; + my @cmd_array = split(/ /,$string); + my $array_count = @cmd_array; + my $string2 = substr($string, 0, 1); + if ($string2 eq weechat::config_string($options_iset{"value_search_char"}) + or (defined $cmd_array[0] and $cmd_array[0] eq weechat::config_string($options_iset{"value_search_char"}).weechat::config_string($options_iset{"value_search_char"})) ) + { + $search_mode = 1; + $search_value = substr($string, 1); + iset_get_values($search_value); + if ($iset_buffer ne "") + { + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); + } + } + else + { + $search_mode = 2; + 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_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 + } + } + if ( $search_mode == 3) + { + iset_create_filter($string); + iset_get_options($search_value); + }else + { + iset_create_filter($string); + iset_get_options(""); + } + } + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); + weechat::buffer_clear($buffer); + $current_line = 0; + iset_refresh(); + return weechat::WEECHAT_RC_OK; +} + +sub iset_buffer_close +{ + $iset_buffer = ""; + + return weechat::WEECHAT_RC_OK; +} + +sub iset_init +{ + $current_line = 0; + $iset_buffer = weechat::buffer_search($LANG, $PRGNAME); + if ($iset_buffer eq "") + { + $iset_buffer = weechat::buffer_new($PRGNAME, "iset_buffer_input", "", "iset_buffer_close", ""); + } + else + { + my $new_filter = weechat::buffer_get_string($iset_buffer, "localvar_iset_filter"); + $search_mode = weechat::buffer_get_string($iset_buffer, "localvar_iset_search_mode"); + $search_value = weechat::buffer_get_string($iset_buffer, "localvar_iset_search_value"); + $filter = $new_filter if ($new_filter ne ""); + } + if ($iset_buffer ne "") + { + weechat::buffer_set($iset_buffer, "type", "free"); + iset_title(); + weechat::buffer_set($iset_buffer, "key_bind_ctrl-L", "/iset **refresh"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-A", "/iset **up"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-B", "/iset **down"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-23~", "/iset **left"); + weechat::buffer_set($iset_buffer, "key_bind_meta2-24~" , "/iset **right"); + weechat::buffer_set($iset_buffer, "key_bind_meta- ", "/iset **toggle"); + weechat::buffer_set($iset_buffer, "key_bind_meta-+", "/iset **incr"); + weechat::buffer_set($iset_buffer, "key_bind_meta--", "/iset **decr"); + weechat::buffer_set($iset_buffer, "key_bind_meta-imeta-r", "/iset **reset"); + weechat::buffer_set($iset_buffer, "key_bind_meta-imeta-u", "/iset **unset"); + weechat::buffer_set($iset_buffer, "key_bind_meta-ctrl-J", "/iset **set"); + weechat::buffer_set($iset_buffer, "key_bind_meta-ctrl-M", "/iset **set"); + weechat::buffer_set($iset_buffer, "key_bind_meta-meta2-1~", "/iset **scroll_top"); + weechat::buffer_set($iset_buffer, "key_bind_meta-meta2-4~", "/iset **scroll_bottom"); + weechat::buffer_set($iset_buffer, "key_bind_meta-v", "/iset **toggle_help"); + weechat::buffer_set($iset_buffer, "key_bind_meta-p", "/iset **toggle_show_plugin_desc"); + weechat::buffer_set($iset_buffer, "localvar_set_iset_filter", $filter); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); + } +} + +sub iset_get_options +{ + my $var_value = $_[0]; + $var_value = "" if (not defined $var_value); + $var_value = lc($var_value); + $search_value = $var_value; + @iset_focus = (); + @options_names = (); + @options_types = (); + @options_values = (); + @options_default_values = (); + @options_is_null = (); + $option_max_length = 0; + my %options_internal = (); + my $i = 0; + my $key; + my $iset_struct; + my %iset_struct; + + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $var_value) if ($search_mode == 3); + + my $infolist = weechat::infolist_get("option", "", $filter); + while (weechat::infolist_next($infolist)) + { + $key = sprintf("%08d", $i); + my $name = weechat::infolist_string($infolist, "full_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 $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}{"type"} = $type; + $options_internal{$name}{"value"} = $value; + $options_internal{$name}{"default_value"} = $default_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}); + } + } + else + { + $options_internal{$name}{"type"} = $type; + $options_internal{$name}{"value"} = $value; + $options_internal{$name}{"default_value"} = $default_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}); + } + $i++; + } + weechat::infolist_free($infolist); + + foreach my $name (sort keys %options_internal) + { + push(@options_names, $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_is_null, $options_internal{$name}{"is_null"}); + } +} + +sub iset_get_values +{ + my $var_value = $_[0]; + $var_value = lc($var_value); + if (substr($var_value,0,1) eq weechat::config_string($options_iset{"value_search_char"}) and $var_value ne weechat::config_string($options_iset{"value_search_char"})) + { + $var_value = substr($var_value,1,length($var_value)); + $search_mode = 0; + } + iset_search_values($var_value,$search_mode); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $var_value); + $search_value = $var_value; +} +sub iset_search_values +{ + my ($var_value,$search_mode) = ($_[0],$_[1]); + @options_names = (); + @options_types = (); + @options_values = (); + @options_default_values = (); + @options_is_null = (); + $option_max_length = 0; + my %options_internal = (); + my $i = 0; + my $infolist = weechat::infolist_get("option", "", "*"); + while (weechat::infolist_next($infolist)) + { + my $name = weechat::infolist_string($infolist, "full_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"); + if ($search_mode) + { + if ( grep /\Q$var_value/,lc($value) ) + { + $options_internal{$name}{"type"} = $type; + $options_internal{$name}{"value"} = $value; + $options_internal{$name}{"default_value"} = $default_value; + $options_internal{$name}{"is_null"} = $is_null; + $option_max_length = length($name) if (length($name) > $option_max_length); + } + } + else + { +# if ($value =~ /\Q$var_value/si) + if (lc($value) eq $var_value) + { + $options_internal{$name}{"type"} = $type; + $options_internal{$name}{"value"} = $value; + $options_internal{$name}{"default_value"} = $default_value; + $options_internal{$name}{"is_null"} = $is_null; + $option_max_length = length($name) if (length($name) > $option_max_length); + } + } + $i++; + } + weechat::infolist_free($infolist); + foreach my $name (sort keys %options_internal) + { + push(@options_names, $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_is_null, $options_internal{$name}{"is_null"}); + } +} + +sub iset_refresh_line +{ + if ($iset_buffer ne "") + { + my $y = $_[0]; + if ($y <= $#options_names) + { + return if (! defined($options_types[$y])); + my $format = sprintf("%%s%%s%%s %%s %%-7s %%s %%s%%s%%s"); + my $padding; + if ($wee_version_number >= 0x00040200) + { + $padding = " " x ($option_max_length - weechat::strlen_screen($options_names[$y])); + } + else + { + $padding = " " x ($option_max_length - length($options_names[$y])); + } + my $around = ""; + $around = "\"" if ((!$options_is_null[$y]) && ($options_types[$y] eq "string")); + + my $color1 = weechat::color(weechat::config_color($options_iset{"color_option"})); + my $color2 = weechat::color(weechat::config_color($options_iset{"color_type"})); + my $color3 = ""; + if ($options_is_null[$y]) + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value_undef"})); + } + elsif ($options_values[$y] ne $options_default_values[$y]) + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value_diff"})); + } + else + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value"})); + } + if ($y == $current_line) + { + $color1 = weechat::color(weechat::config_color($options_iset{"color_option_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + $color2 = weechat::color(weechat::config_color($options_iset{"color_type_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + 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"})); + } + elsif ($options_values[$y] ne $options_default_values[$y]) + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value_diff_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + } + else + { + $color3 = weechat::color(weechat::config_color($options_iset{"color_value_selected"}).",".weechat::config_color($options_iset{"color_bg_selected"})); + } + } + my $value = $options_values[$y]; + $value = "(undef)" if ($options_is_null[$y]); + my $strline = sprintf($format, + $color1, $options_names[$y], $padding, + $color2, $options_types[$y], + $color3, $around, $value, $around); + weechat::print_y($iset_buffer, $y, $strline); + } + } +} + +sub iset_refresh +{ + iset_title(); + if (($iset_buffer ne "") && ($#options_names >= 0)) + { + foreach my $y (0 .. $#options_names) + { + iset_refresh_line($y); + } + } + + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); +} + +sub iset_full_refresh +{ + $iset_buffer = weechat::buffer_search($LANG, $PRGNAME); + if ($iset_buffer ne "") + { + weechat::buffer_clear($iset_buffer) unless defined $_[0]; # iset_full_refresh(1) does a full refresh without clearing buffer + # search for "*" in $filter. + if ($filter =~ m/\*/ and $search_mode == 2) + { + iset_get_options(""); + } + else + { + if ($search_mode == 0) + { + $search_value = "=" . $search_value; + iset_get_values($search_value); + } + elsif ($search_mode == 1) + { + iset_get_values($search_value); + } + elsif ($search_mode == 3) + { + iset_create_filter($filter); + iset_get_options($search_value); + } + } + if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 1) + { + iset_set_current_line($current_line); + }else + { + $current_line = $#options_names if ($current_line > $#options_names); + } + iset_refresh(); + weechat::command($iset_buffer, "/window refresh"); + } +} + +sub iset_set_current_line +{ + my $new_current_line = $_[0]; + if ($new_current_line >= 0) + { + my $old_current_line = $current_line; + $current_line = $new_current_line; + $current_line = $#options_names if ($current_line > $#options_names); + if ($old_current_line != $current_line) + { + iset_refresh_line($old_current_line); + iset_refresh_line($current_line); + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); + } + } +} + +sub iset_signal_window_scrolled_cb +{ + my ($data, $signal, $signal_data) = ($_[0], $_[1], $_[2]); + if ($iset_buffer ne "") + { + my $infolist = weechat::infolist_get("window", $signal_data, ""); + if (weechat::infolist_next($infolist)) + { + if (weechat::infolist_pointer($infolist, "buffer") eq $iset_buffer) + { + my $old_current_line = $current_line; + my $new_current_line = $current_line; + my $start_line_y = weechat::infolist_integer($infolist, "start_line_y"); + my $chat_height = weechat::infolist_integer($infolist, "chat_height"); + $new_current_line += $chat_height if ($new_current_line < $start_line_y); + $new_current_line -= $chat_height if ($new_current_line >= $start_line_y + $chat_height); + $new_current_line = $start_line_y if ($new_current_line < $start_line_y); + $new_current_line = $start_line_y + $chat_height - 1 if ($new_current_line >= $start_line_y + $chat_height); + iset_set_current_line($new_current_line); + } + } + weechat::infolist_free($infolist); + } + + return weechat::WEECHAT_RC_OK; +} + +sub iset_get_window_number +{ + if ($iset_buffer ne "") + { + my $window = weechat::window_search_with_buffer($iset_buffer); + return "-window ".weechat::window_get_integer ($window, "number")." " if ($window ne ""); + } + return ""; +} + +sub iset_check_line_outside_window +{ + if ($iset_buffer ne "") + { + undef my $infolist; + if ($wee_version_number >= 0x00030500) + { + my $window = weechat::window_search_with_buffer($iset_buffer); + $infolist = weechat::infolist_get("window", $window, "") if $window; + } + else + { + $infolist = weechat::infolist_get("window", "", "current"); + } + if ($infolist) + { + if (weechat::infolist_next($infolist)) + { + my $start_line_y = weechat::infolist_integer($infolist, "start_line_y"); + my $chat_height = weechat::infolist_integer($infolist, "chat_height"); + my $window_number = ""; + if ($wee_version_number >= 0x00030500) + { + $window_number = "-window ".weechat::infolist_integer($infolist, "number")." "; + } + if ($start_line_y > $current_line) + { + weechat::command($iset_buffer, "/window scroll ".$window_number."-".($start_line_y - $current_line)); + } + else + { + if ($start_line_y <= $current_line - $chat_height) + { + weechat::command($iset_buffer, "/window scroll ".$window_number."+".($current_line - $start_line_y - $chat_height + 1)); + + } + } + } + weechat::infolist_free($infolist); + } + } +} + +sub iset_get_option_name_index +{ + my $option_name = $_[0]; + my $index = 0; + while ($index <= $#options_names) + { + return -1 if ($options_names[$index] gt $option_name); + return $index if ($options_names[$index] eq $option_name); + $index++; + } + return -1; +} + +sub iset_config_cb +{ + my ($data, $option_name, $value) = ($_[0], $_[1], $_[2]); + + if ($iset_buffer ne "") + { + return weechat::WEECHAT_RC_OK if (weechat::info_get("weechat_upgrading", "") eq "1"); + + my $index = iset_get_option_name_index($option_name); + if ($index >= 0) + { + # refresh info about changed option + my $infolist = weechat::infolist_get("option", "", $option_name); + if ($infolist) + { + weechat::infolist_next($infolist); + if (weechat::infolist_fields($infolist)) + { + $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"); + } + 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 + { + iset_full_refresh() if ($option_name ne "weechat.bar.isetbar.hidden"); + } + } + + return weechat::WEECHAT_RC_OK; +} + +sub iset_set_option +{ + my ($option, $value) = ($_[0],$_[1]); + if (defined $option and defined $value) + { + $option = weechat::config_get($option); + weechat::config_option_set($option, $value, 1) if ($option ne ""); + } +} + +sub iset_reset_option +{ + my $option = $_[0]; + if (defined $option) + { + $option = weechat::config_get($option); + weechat::config_option_reset($option, 1) if ($option ne ""); + } +} + +sub iset_unset_option +{ + my $option = $_[0]; + if (defined $option) + { + $option = weechat::config_get($option); + weechat::config_option_unset($option) if ($option ne ""); + } +} + + +sub iset_cmd_cb +{ + my ($data, $buffer, $args) = ($_[0], $_[1], $_[2]); + my $filter_set = 0; +# $search_value = ""; + if (($args ne "") && (substr($args, 0, 2) ne "**")) + { + my @cmd_array = split(/ /,$args); + my $array_count = @cmd_array; + if (substr($args, 0, 1) eq weechat::config_string($options_iset{"value_search_char"}) + or (defined $cmd_array[0] and $cmd_array[0] eq weechat::config_string($options_iset{"value_search_char"}).weechat::config_string($options_iset{"value_search_char"})) ) + { + $search_mode = 1; + my $search_value = substr($args, 1); # cut value_search_char + if ($iset_buffer ne "") + { + weechat::buffer_clear($iset_buffer); + weechat::command($iset_buffer, "/window refresh"); + } + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); + iset_init(); + iset_get_values($search_value); + iset_refresh(); + weechat::buffer_set($iset_buffer, "display", "1"); +# $filter = $var_value; + return weechat::WEECHAT_RC_OK; + } + else + { + # f/s option =value + # option =value + $search_mode = 2; + 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_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 + } + } + iset_create_filter($args); + $filter_set = 1; + my $ptrbuf = weechat::buffer_search($LANG, $PRGNAME); + if ($ptrbuf eq "") + { + iset_init(); + iset_get_options($search_value); + iset_full_refresh(); + weechat::buffer_set(weechat::buffer_search($LANG, $PRGNAME), "display", "1"); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); + return weechat::WEECHAT_RC_OK; + } + else + { + iset_get_options($search_value); + iset_full_refresh(); + weechat::buffer_set($ptrbuf, "display", "1"); + } + } + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_mode", $search_mode); + weechat::buffer_set($iset_buffer, "localvar_set_iset_search_value", $search_value); + } + if ($iset_buffer eq "") + { + iset_init(); + iset_get_options(""); + iset_refresh(); + } + else + { +# iset_get_options($search_value); + iset_full_refresh() if ($filter_set); + } + + if ($args eq "") + { + weechat::buffer_set($iset_buffer, "display", "1"); + } + else + { + if ($args eq "**refresh") + { + iset_full_refresh(); + } + if ($args eq "**up") + { + if ($current_line > 0) + { + $current_line--; + iset_refresh_line($current_line + 1); + iset_refresh_line($current_line); + iset_check_line_outside_window(); + } + } + if ($args eq "**down") + { + if ($current_line < $#options_names) + { + $current_line++; + iset_refresh_line($current_line - 1); + iset_refresh_line($current_line); + iset_check_line_outside_window(); + } + } + if ($args eq "**left" && $wee_version_number >= 0x00030600) + { + weechat::command($iset_buffer, "/window scroll_horiz ".iset_get_window_number()."-".weechat::config_integer($options_iset{"scroll_horiz"})."%"); + } + if ($args eq "**right" && $wee_version_number >= 0x00030600) + { + weechat::command($iset_buffer, "/window scroll_horiz ".iset_get_window_number().weechat::config_integer($options_iset{"scroll_horiz"})."%"); + } + if ($args eq "**scroll_top") + { + my $old_current_line = $current_line; + $current_line = 0; + iset_refresh_line ($old_current_line); + iset_refresh_line ($current_line); + iset_title(); + weechat::command($iset_buffer, "/window scroll_top ".iset_get_window_number()); + } + if ($args eq "**scroll_bottom") + { + my $old_current_line = $current_line; + $current_line = $#options_names; + iset_refresh_line ($old_current_line); + iset_refresh_line ($current_line); + iset_title(); + weechat::command($iset_buffer, "/window scroll_bottom ".iset_get_window_number()); + } + if ($args eq "**toggle") + { + if ($options_types[$current_line] eq "boolean") + { + iset_set_option($options_names[$current_line], "toggle"); + } + } + if ($args eq "**incr") + { + if (($options_types[$current_line] eq "integer") + || ($options_types[$current_line] eq "color")) + { + iset_set_option($options_names[$current_line], "++1"); + } + } + if ($args eq "**decr") + { + if (($options_types[$current_line] eq "integer") + || ($options_types[$current_line] eq "color")) + { + iset_set_option($options_names[$current_line], "--1"); + } + } + if ($args eq "**reset") + { + iset_reset_option($options_names[$current_line]); + } + if ($args eq "**unset") + { + iset_unset_option($options_names[$current_line]); + } + if ($args eq "**toggle_help") + { + if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1) + { + weechat::config_option_set($options_iset{"show_help_bar"},0,1); + iset_show_bar(0); + } + else + { + weechat::config_option_set($options_iset{"show_help_bar"},1,1); + iset_show_bar(1); + } + } + if ($args eq "**toggle_show_plugin_desc") + { + if (weechat::config_boolean($options_iset{"show_plugin_description"}) == 1) + { + weechat::config_option_set($options_iset{"show_plugin_description"},0,1); + iset_full_refresh(); + iset_check_line_outside_window(); + iset_title(); + } + else + { + weechat::config_option_set($options_iset{"show_plugin_description"},1,1); + iset_full_refresh(); + iset_check_line_outside_window(); + iset_title(); + } + } + if ($args eq "**set") + { + my $quote = ""; + my $value = $options_values[$current_line]; + if ($options_is_null[$current_line]) + { + $value = "null"; + } + 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); + + 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 ""); + } + } + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); + return weechat::WEECHAT_RC_OK; +} + +sub iset_get_help +{ + my ($redraw) = ($_[0]); + + return '' if (weechat::config_boolean($options_iset{"show_help_bar"}) == 0); + + if (not defined $options_names[$current_line]) + { + return "No option selected. Set a new filter using command line (use '*' to see all options)"; + } + if ($options_name_copy eq $options_names[$current_line] and not defined $redraw) + { + return $description; + } + $options_name_copy = $options_names[$current_line]; + my $optionlist =""; + $optionlist = weechat::infolist_get("option", "", $options_names[$current_line]); + weechat::infolist_next($optionlist); + my $full_name = weechat::infolist_string($optionlist,"full_name"); + my $option_desc = ""; + my $option_default_value = ""; + my $option_range = ""; + my $possible_values = ""; + my $re = qq(\Q$full_name); + if (grep (/^$re$/,$options_names[$current_line])) + { + $option_desc = weechat::infolist_string($optionlist, "description_nls"); + $option_desc = weechat::infolist_string($optionlist, "description") if ($option_desc eq ""); + $option_desc = "No help found" if ($option_desc eq ""); + $option_default_value = weechat::infolist_string($optionlist, "default_value"); + $possible_values = weechat::infolist_string($optionlist, "string_values") if (weechat::infolist_string($optionlist, "string_values") ne ""); + if ((weechat::infolist_string($optionlist, "type") eq "integer") && ($possible_values eq "")) + { + $option_range = weechat::infolist_integer($optionlist, "min") + ." .. ".weechat::infolist_integer($optionlist, "max"); + } + } + weechat::infolist_free($optionlist); + iset_title(); + + $description = weechat::color(weechat::config_color($options_iset{"color_help_option_name"})).$options_names[$current_line] + .weechat::color("bar_fg").": " + .weechat::color(weechat::config_color($options_iset{"color_help_text"})).$option_desc; + + # show additional infos like default value and possible values + + if (weechat::config_boolean($options_iset{"show_help_extra_info"}) == 1) + { + $description .= + weechat::color("bar_delim")." [" + .weechat::color("bar_fg")."default: " + .weechat::color("bar_delim")."\"" + .weechat::color(weechat::config_color($options_iset{"color_help_default_value"})).$option_default_value + .weechat::color("bar_delim")."\""; + if ($option_range ne "") + { + $description .= weechat::color("bar_fg").", values: ".$option_range; + } + if ($possible_values ne "") + { + $possible_values =~ s/\|/", "/g; # replace '|' to '", "' + $description .= weechat::color("bar_fg").", values: ". "\"" . $possible_values . "\""; + + } + $description .= weechat::color("bar_delim")."]"; + } + return $description; +} + +sub iset_check_condition_isetbar_cb +{ + my ($data, $modifier, $modifier_data, $string) = ($_[0], $_[1], $_[2], $_[3]); + my $buffer = weechat::window_get_pointer($modifier_data, "buffer"); + if ($buffer ne "") + { + if ((weechat::buffer_get_string($buffer, "plugin") eq $LANG) + && (weechat::buffer_get_string($buffer, "name") eq $PRGNAME)) + { + return "1"; + } + } + return "0"; +} + +sub iset_show_bar +{ + my $show = $_[0]; + my $barhidden = weechat::config_get("weechat.bar.isetbar.hidden"); + if ($barhidden) + { + if ($show) + { + if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1) + { + if (weechat::config_boolean($barhidden)) + { + weechat::config_option_set($barhidden, 0, 1); + } + } + } + else + { + if (!weechat::config_boolean($barhidden)) + { + weechat::config_option_set($barhidden, 1, 1); + } + } + } +} + +sub iset_signal_buffer_switch_cb +{ + my $buffer_pointer = $_[2]; + my $show_bar = 0; + $show_bar = 1 if (weechat::buffer_get_integer($iset_buffer, "num_displayed") > 0); + iset_show_bar($show_bar); + iset_check_line_outside_window() if ($buffer_pointer eq $iset_buffer); + return weechat::WEECHAT_RC_OK; +} + +sub iset_item_cb +{ + return iset_get_help(); +} + +sub iset_upgrade_ended +{ + iset_full_refresh(); +} + +sub iset_end +{ + # when script is unloaded, we hide bar + iset_show_bar(0); +} + +# -------------------------------[ mouse support ]------------------------------------- + +sub hook_focus_iset_cb +{ + my %info = %{$_[1]}; + my $bar_item_line = int($info{"_bar_item_line"}); + undef my $hash; + if (($info{"_buffer_name"} eq $PRGNAME) && $info{"_buffer_plugin"} eq $LANG && ($bar_item_line >= 0) && ($bar_item_line <= $#iset_focus)) + { + $hash = $iset_focus[$bar_item_line]; + } + else + { + $hash = {}; + my $hash_focus = $iset_focus[0]; + foreach my $key (keys %$hash_focus) + { + $hash->{$key} = "?"; + } + } + return $hash; +} + +# _chat_line_y contains selected line +sub iset_hsignal_mouse_cb +{ + my ($data, $signal, %hash) = ($_[0], $_[1], %{$_[2]}); + + if ($hash{"_buffer_name"} eq $PRGNAME && ($hash{"_buffer_plugin"} eq $LANG)) + { + if ($hash{"_key"} eq "button1") + { + iset_set_current_line($hash{"_chat_line_y"}); + } + elsif ($hash{"_key"} eq "button2") + { + if ($options_types[$hash{"_chat_line_y"}] eq "boolean") + { + iset_set_option($options_names[$hash{"_chat_line_y"}], "toggle"); + iset_set_current_line($hash{"_chat_line_y"}); + } + elsif ($options_types[$hash{"_chat_line_y"}] eq "string") + { + iset_set_current_line($hash{"_chat_line_y"}); + weechat::command("", "/$PRGNAME **set"); + } + } + elsif ($hash{"_key"} eq "button2-gesture-left" or $hash{"_key"} eq "button2-gesture-left-long") + { + if ($options_types[$hash{"_chat_line_y"}] eq "integer" or ($options_types[$hash{"_chat_line_y"}] eq "color")) + { + iset_set_current_line($hash{"_chat_line_y"}); + my $distance = distance($hash{"_chat_line_x"},$hash{"_chat_line_x2"}); + weechat::command("", "/repeat $distance /$PRGNAME **decr"); + } + } + elsif ($hash{"_key"} eq "button2-gesture-right" or $hash{"_key"} eq "button2-gesture-right-long") + { + if ($options_types[$hash{"_chat_line_y"}] eq "integer" or ($options_types[$hash{"_chat_line_y"}] eq "color")) + { + iset_set_current_line($hash{"_chat_line_y"}); + my $distance = distance($hash{"_chat_line_x"},$hash{"_chat_line_x2"}); + weechat::command("", "/repeat $distance /$PRGNAME **incr"); + } + } + } + window_switch(); +} + +sub window_switch +{ + my $current_window = weechat::current_window(); + my $dest_window = weechat::window_search_with_buffer(weechat::buffer_search("perl","iset")); + return 0 if ($dest_window eq "" or $current_window eq $dest_window); + + my $infolist = weechat::infolist_get("window", $dest_window, ""); + weechat::infolist_next($infolist); + my $number = weechat::infolist_integer($infolist, "number"); + weechat::infolist_free($infolist); + weechat::command("","/window " . $number); +} + +sub distance +{ + my ($x1,$x2) = ($_[0], $_[1]); + my $distance; + $distance = $x1 - $x2; + $distance = abs($distance); + if ($distance > 0) + { + use integer; + $distance = $distance / 3; + $distance = 1 if ($distance == 0); + } + elsif ($distance == 0) + { + $distance = 1; + } + return $distance; +} + +# -----------------------------------[ config ]--------------------------------------- + +sub iset_config_init +{ + $iset_config_file = weechat::config_new($ISET_CONFIG_FILE_NAME,"iset_config_reload_cb",""); + return if ($iset_config_file eq ""); + + # section "color" + my $section_color = weechat::config_new_section($iset_config_file,"color", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_color eq "") + { + weechat::config_free($iset_config_file); + return; + } + $options_iset{"color_option"} = weechat::config_new_option( + $iset_config_file, $section_color, + "option", "color", "Color for option name in iset buffer", "", 0, 0, + "default", "default", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_option_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "option_selected", "color", "Color for selected option name in iset buffer", "", 0, 0, + "white", "white", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_type"} = weechat::config_new_option( + $iset_config_file, $section_color, + "type", "color", "Color for option type (integer, boolean, string)", "", 0, 0, + "brown", "brown", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_type_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "type_selected", "color", "Color for selected option type (integer, boolean, string)", "", 0, 0, + "yellow", "yellow", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value", "color", "Color for option value", "", 0, 0, + "cyan", "cyan", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_selected", "color", "Color for selected option value", "", 0, 0, + "lightcyan", "lightcyan", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_diff"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_diff", "color", "Color for option value different from default", "", 0, 0, + "magenta", "magenta", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_diff_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_diff_selected", "color", "Color for selected option value different from default", "", 0, 0, + "lightmagenta", "lightmagenta", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_undef"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_undef", "color", "Color for option value undef", "", 0, 0, + "green", "green", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_value_undef_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "value_undef_selected", "color", "Color for selected option value undef", "", 0, 0, + "lightgreen", "lightgreen", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_bg_selected"} = weechat::config_new_option( + $iset_config_file, $section_color, + "bg_selected", "color", "Background color for current selected option", "", 0, 0, + "red", "red", 0, "", "", "full_refresh_cb", "", "", ""); + $options_iset{"color_help_option_name"} = weechat::config_new_option( + $iset_config_file, $section_color, + "help_option_name", "color", "Color for option name in help-bar", "", 0, 0, + "white", "white", 0, "", "", "bar_refresh", "", "", ""); + $options_iset{"color_help_text"} = weechat::config_new_option( + $iset_config_file, $section_color, + "help_text", "color", "Color for option description in help-bar", "", 0, 0, + "default", "default", 0, "", "", "bar_refresh", "", "", ""); + $options_iset{"color_help_default_value"} = weechat::config_new_option( + $iset_config_file, $section_color, + "help_default_value", "color", "Color for default option value in help-bar", "", 0, 0, + "green", "green", 0, "", "", "bar_refresh", "", "", ""); + + # section "help" + my $section_help = weechat::config_new_section($iset_config_file,"help", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_help eq "") + { + weechat::config_free($iset_config_file); + return; + } + $options_iset{"show_help_bar"} = weechat::config_new_option( + $iset_config_file, $section_help, + "show_help_bar", "boolean", "Show help bar", "", 0, 0, + "on", "on", 0, "", "", "toggle_help_cb", "", "", ""); + $options_iset{"show_help_extra_info"} = weechat::config_new_option( + $iset_config_file, $section_help, + "show_help_extra_info", "boolean", "Show additional information in help bar (default value, max./min. value) ", "", 0, 0, + "on", "on", 0, "", "", "", "", "", ""); + $options_iset{"show_plugin_description"} = weechat::config_new_option( + $iset_config_file, $section_help, + "show_plugin_description", "boolean", "Show plugin description in iset buffer", "", 0, 0, + "off", "off", 0, "", "", "full_refresh_cb", "", "", ""); + + # section "look" + my $section_look = weechat::config_new_section($iset_config_file, "look", 0, 0, "", "", "", "", "", "", "", "", "", ""); + if ($section_look eq "") + { + weechat::config_free($iset_config_file); + return; + } + $options_iset{"value_search_char"} = weechat::config_new_option( + $iset_config_file, $section_look, + "value_search_char", "string", "Trigger char to tell iset to search for value instead of option (for example: =red)", "", 0, 0, + "=", "=", 0, "", "", "", "", "", ""); + $options_iset{"scroll_horiz"} = weechat::config_new_option( + $iset_config_file, $section_look, + "scroll_horiz", "integer", "scroll content of iset buffer n%", "", 1, 100, + "10", "10", 0, "", "", "", "", "", ""); + $options_iset{"show_current_line"} = weechat::config_new_option( + $iset_config_file, $section_look, + "show_current_line", "boolean", "show current line in title bar.", "", 0, 0, + "on", "on", 0, "", "", "", "", "", ""); + $options_iset{"use_mute"} = weechat::config_new_option( + $iset_config_file, $section_look, + "use_mute", "boolean", "/mute command will be used in input bar", "", 0, 0, + "off", "off", 0, "", "", "", "", "", ""); +} + +sub iset_config_reload_cb +{ + my ($data,$config_file) = ($_[0], $_[1]); + return weechat::config_reload($config_file) +} + +sub iset_config_read +{ + return weechat::config_read($iset_config_file) if ($iset_config_file ne ""); +} + +sub iset_config_write +{ + return weechat::config_write($iset_config_file) if ($iset_config_file ne ""); +} + +sub full_refresh_cb +{ + iset_full_refresh(); + return weechat::WEECHAT_RC_OK; +} + +sub bar_refresh +{ + iset_get_help(1); + weechat::bar_item_update("isetbar_help") if (weechat::config_boolean($options_iset{"show_help_bar"}) == 1); + return weechat::WEECHAT_RC_OK; +} + +sub toggle_help_cb +{ + my $value = weechat::config_boolean($options_iset{"show_help_bar"}); + iset_show_bar($value); + return weechat::WEECHAT_RC_OK; +} + +# -----------------------------------[ main ]----------------------------------------- + +weechat::register($PRGNAME, $AUTHOR, $VERSION, $LICENSE, + $DESCR, "iset_end", ""); + +$wee_version_number = weechat::info_get("version_number", "") || 0; + +iset_config_init(); +iset_config_read(); + +weechat::hook_command($PRGNAME, "Interactive set", "f || s
|| [=][=]", + "f file : show options for a file\n". + "s section: show options for a section\n". + "text : show options with 'text' in name\n". + weechat::config_string($options_iset{"value_search_char"})."text : show options with 'text' in value\n". + weechat::config_string($options_iset{"value_search_char"}).weechat::config_string($options_iset{"value_search_char"})."text : show options with exact 'text' in value\n\n". + "Keys for iset buffer:\n". + "f11,f12 : move iset content left/right\n". + "up,down : move one option up/down\n". + "pgup,pdwn : move one page up/down\n". + "home,end : move to first/last option\n". + "ctrl+'L' : refresh options and screen\n". + "alt+space : toggle boolean on/off\n". + "alt+'+' : increase value (for integer or color)\n". + "alt+'-' : decrease value (for integer or color)\n". + "alt+'i',alt+'r': reset value of option\n". + "alt+'i',alt+'u': unset option\n". + "alt+enter : set new value for option (edit it with command line)\n". + "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". + "\n". + "Mouse actions:\n". + "wheel up/down : move cursor up/down\n". + "left button : select an option from list\n". + "right button : toggle boolean (on/off) or set a new value for option (edit it with command line)\n". + "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 options for file 'irc'\n". + " /iset f irc\n". + " show options for section 'look'\n". + " /iset s look\n". + " show all options with text 'nicklist' in name\n". + " /iset nicklist\n". + " show all values which contain 'red'. ('" . weechat::config_string($options_iset{"value_search_char"}) . "' is a trigger char).\n". + " /iset ". weechat::config_string($options_iset{"value_search_char"}) ."red\n". + " show all values which hit 'off'. ('" . weechat::config_string($options_iset{"value_search_char"}) . weechat::config_string($options_iset{"value_search_char"}) . "' is a trigger char).\n". + " /iset ". weechat::config_string($options_iset{"value_search_char"}) . weechat::config_string($options_iset{"value_search_char"}) ."off\n". + " show options for file 'weechat' which contains value 'off'\n". + " /iset f weechat ".weechat::config_string($options_iset{"value_search_char"})."off\n". + "", + "", "iset_cmd_cb", ""); +weechat::hook_signal("upgrade_ended", "iset_upgrade_ended", ""); +weechat::hook_signal("window_scrolled", "iset_signal_window_scrolled_cb", ""); +weechat::hook_signal("buffer_switch", "iset_signal_buffer_switch_cb",""); +weechat::bar_item_new("isetbar_help", "iset_item_cb", ""); +weechat::bar_new("isetbar", "on", "0", "window", "", "top", "horizontal", + "vertical", "3", "3", "default", "cyan", "default", "1", + "isetbar_help"); +weechat::hook_modifier("bar_condition_isetbar", "iset_check_condition_isetbar_cb", ""); +weechat::hook_config("*", "iset_config_cb", ""); +$iset_buffer = weechat::buffer_search($LANG, $PRGNAME); +iset_init() if ($iset_buffer ne ""); + +if ($wee_version_number >= 0x00030600) +{ + weechat::hook_focus("chat", "hook_focus_iset_cb", ""); + weechat::hook_hsignal($PRGNAME."_mouse", "iset_hsignal_mouse_cb", ""); + weechat::key_bind("mouse", \%mouse_keys); +} diff --git a/.weechat/plugins.conf b/.weechat/plugins.conf new file mode 100644 index 0000000..3131fb5 --- /dev/null +++ b/.weechat/plugins.conf @@ -0,0 +1,61 @@ +# +# plugins.conf -- weechat v1.0.1 +# + +[var] +fifo.fifo = "on" +guile.check_license = "off" +lua.check_license = "off" +perl.check_license = "off" +perl.highmon.alignment = "channel" +perl.highmon.away_only = "off" +perl.highmon.color_buf = "on" +perl.highmon.first_run = "true" +perl.highmon.hotlist_show = "off" +perl.highmon.logging = "off" +perl.highmon.merge_private = "off" +perl.highmon.nick_prefix = "<" +perl.highmon.nick_suffix = ">" +perl.highmon.output = "buffer" +perl.highmon.short_names = "off" +python.apply_corrections.check_every = "5" +python.apply_corrections.data_timeout = "60" +python.apply_corrections.message_limit = "2" +python.apply_corrections.print_format = "[nick]: [corrected]" +python.apply_corrections.print_limit = "1" +python.autojoin.autosave = "off" +python.check_license = "off" +python.grep.clear_buffer = "off" +python.grep.default_tail_head = "10" +python.grep.go_to_buffer = "on" +python.grep.log_filter = "" +python.grep.max_lines = "4000" +python.grep.show_summary = "on" +python.grep.size_limit = "2048" +python.screen_away.away_suffix = "" +python.screen_away.command_on_attach = "" +python.screen_away.command_on_detach = "" +python.screen_away.ignore = "" +python.screen_away.ignore_relays = "off" +python.screen_away.interval = "5" +python.screen_away.message = "Detached from screen" +python.screen_away.set_away = "on" +python.screen_away.time_format = "since %Y-%m-%d %H:%M:%S%z" +ruby.check_license = "off" +tcl.check_license = "off" + +[desc] +python.apply_corrections.check_every = "Interval between each check for expired messages." +python.apply_corrections.data_timeout = "Time before a message is expired." +python.apply_corrections.message_limit = "Number of messages to store per nick." +python.apply_corrections.print_format = "Format string for the printed corrections." +python.apply_corrections.print_limit = "Maximum number of lines to correct." +python.screen_away.away_suffix = "What to append to your nick when you're away." +python.screen_away.command_on_attach = "Commands to execute on attach, separated by semicolon" +python.screen_away.command_on_detach = "Commands to execute on detach, separated by semicolon" +python.screen_away.ignore = "Comma-separated list of servers to ignore." +python.screen_away.ignore_relays = "Only check screen status and ignore relay interfaces" +python.screen_away.interval = "How often in seconds to check screen status" +python.screen_away.message = "Away message" +python.screen_away.set_away = "Set user as away." +python.screen_away.time_format = "time format append to away message" diff --git a/.weechat/python/apply_corrections.py b/.weechat/python/apply_corrections.py new file mode 100644 index 0000000..2fd8b5c --- /dev/null +++ b/.weechat/python/apply_corrections.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2012 Chris Johnson +# +# 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 . +# + +# apply_corrections +# +# A weechat plugin to re-print a user's messages with corrections applied when +# they send a correction string (ex: s/typo/replacement). +# +# The following options are availalble: +# +# check_every: Interval, in seconds, between each check for expired messages. +# If set to 0 no check will be performed and all messages will be +# saved indefinitely. +# +# data_timeout: Time, in seconds, before a message is expired. If set to 0 +# messages will never expire. +# +# message_limit: Number of messages to store per nick. If set to 0 all messages +# will be saved until they expire. +# +# print_format: Format string for the printed corrections. +# Default: "[nick]: [corrected]" +# +# Variables allowed: +# +# [nick]: The nick of the person who sent the messages. +# [corrected]: The corrected text of the previous message(s). +# [correction]: The correction (format: s/typo/replacement). +# [original]: The original message before correction. +# [pattern]: The "typo" portion of the correction. +# [replacement]: The "replacement" portion of the correction. +# [timestamp]: The timestamp of the original message. +# +# print_limit: Maximum number of lines to correct and print to the buffer. If +# set to 0 all lines that match the pattern will be printed. +# +# Note: Setting check_every, data_timeout, message_limit, or some combination +# thereof to 0's will eat a lot of memory very quickly as it will drastically +# increase the size of the dictionary holding previous messages. Likewise, +# setting print_limit to 0 with a large number of saved messages will quickly +# fill your screen with a bunch of stuff should someone submit a generic +# enough correction string. + +# History: +# +# 2014-05-10, Sébastien Helleu +# version 1.2: change hook_print callback argument type of +# displayed/highlight (WeeChat >= 1.0) +# 2012-10-09, Chris Johnson : +# version 1.1: change some more variable names for clarity/consistency +# 2012-10-08, Chris Johnson : +# version 1.0: fix get_corrected_messages so that the most recent messages +# are corrected and returned +# 2012-10-08, Chris Johnson : +# version 0.9: use defaultdict to handle missing keys, flatten dict by +# using (buffer, nick) tuple as key, simplify message logging +# logic, rename some stuff for clarity. +# 2012-10-08, Chris Johnson : +# version 0.8: remove empty buffers and nicks during clean-up +# 2012-09-05, Chris Johnson : +# version 0.7: fix bug when restoring defaults for options that require +# integer values +# 2012-09-05, Chris Johnson : +# version 0.6: copy info from README into script and shorten the variable +# descriptions +# 2012-09-01, Chris Johnson : +# version 0.5: don't log the reprinted messages +# 2012-08-31, Chris Johnson : +# version 0.4: use same timestamp as buffer when reprinting, instead +# of epoch +# 2012-08-31, Chris Johnson : +# version 0.3: switch to [var] style variables for print format +# 2012-08-30, Chris Johnson : +# version 0.2: fixed search for typos so if regex fails it falls back +# to string.find +# 2012-08-30, Chris Johnson : +# version 0.1: initial release + +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 + import time + from operator import itemgetter + from collections import defaultdict +except ImportError as message: + print('Missing package(s) for %s: %s' % (SCRIPT_NAME, message)) + import_ok = False + +SCRIPT_NAME = 'apply_corrections' +SCRIPT_AUTHOR = 'Chris Johnson ' +SCRIPT_VERSION = '1.2' +SCRIPT_LICENSE = 'GPL3' +SCRIPT_DESC = "When a correction (ex: s/typo/replacement) is sent, print the "\ + "user's previous message(s) with the corrected text instead." + +# Default settings for the plugin. +settings = {'check_every': '5', + 'data_timeout': '60', + 'message_limit': '2', + 'print_format': '[nick]: [corrected]', + 'print_limit': '1'} + +# Initialize the dictionary to store most recent messages per buffer per nick. +LASTWORDS = defaultdict(list) + + +def apply_correction(message, pattern, replacement): + """ + Replaces all occurences of pattern in message with replacment. It tries to + treat the pattern and replacement as regular expressions, but falls back to + string replace if that fails. + """ + + try: + message = re.compile(pattern).sub(replacement, message) + except: + message = message.replace(pattern, replacement) + + return message + + +def get_corrected_messages(nick, log, correction): + """ + Return list of messages that match the pattern, with corrections applied. + Limited to print_limit items, sorted by timestamp ascending. + """ + + print_limit = get_option_int('print_limit') + corrected_messages = [] + pattern, replacement = correction.split('/')[1:3] + + for message in log: + if print_limit and len(corrected_messages) >= print_limit: + break + original = message.get('message', '') + if original: + try: + match = re.match(re.compile('.*%s.*' % pattern), original) + except: + match = original.find(pattern) != -1 + finally: + if match: + corrected = apply_correction(original, + pattern, + replacement) + timeformat = weechat.config_string( + weechat.config_get('weechat.look.buffer_time_format')) + timestamp = time.strftime( + timeformat, + time.localtime(float(message['timestamp']))) + corrected_messages.append({'nick': nick, + 'corrected': corrected, + 'correction': correction, + 'original': original, + 'pattern': pattern, + 'replacement': replacement, + 'timestamp': timestamp}) + + return sorted(corrected_messages, key=itemgetter('timestamp')) + + +def get_option_int(option): + """ + Checks to see if a configuration option is an integer and sets it back to + the default if it isn't. Returns the value when done. + """ + + try: + value = int(weechat.config_get_plugin(option)) + except ValueError: + weechat.config_set_plugin(option, settings[option]) + value = int(weechat.config_get_plugin(option)) + + return value + + +def get_valid_messages(log, expiry): + """ + Return only the messages that haven't expired. + """ + + valid = [] + for message in log: + try: + timestamp = int(message.get('timestamp', 0)) + if timestamp > expiry: + valid.append(message) + except ValueError: + continue + + return valid + + +def clear_messages_cb(data, remaining_calls): + """ + Callback that clears old messages from the LASTWORDS dictionary. The time + limit is the number of seconds specified in plugin's data_timeout setting. + If data_timeout is set to 0 then no messages are cleared. + """ + + data_timeout = get_option_int('data_timeout') + if data_timeout: + expiry = time.time() - data_timeout + for buff, nick in LASTWORDS.keys(): + valid_messages = get_valid_messages(LASTWORDS[(buff,nick)], expiry) + if valid_messages: + LASTWORDS[(buff, nick)] = valid_messages + else: + del LASTWORDS[(buff,nick)] + + return weechat.WEECHAT_RC_OK + + +def handle_message_cb(data, buffer, date, tags, disp, hl, nick, message): + """ + Callback that handles new messages. If the message is in the format of a + regex find/replace (ex. 's/typo/replacement/', 'nick: s/typo/replacement') + then the last print_limit messages for that nick are re-printed to the + current buffer in their oringal order with the change applied. Otherwise + the message is stored in LASTWORDS dictionary for this buffer > nick. + """ + + # Don't do anything if the message isn't suppose to be displayed. + if int(disp): + buffer_name = weechat.buffer_get_string(buffer, 'name') + log = LASTWORDS[(buffer_name, nick)] + + # Matches on both 's/typo/replacement' and 'nick: s/typo/replacement', + # mainly because of bitlbee since it puts your nick in front of + # incoming messages. + # + # Nick regex nicked from colorize_nicks available here: + # http://www.weechat.org/scripts/source/stable/colorize_nicks.py.html/ + valid_nick = r'([@~&!%+])?([-a-zA-Z0-9\[\]\\`_^\{|\}]+)' + valid_correction = r's/[^/]*/[^/]*' + correction_message_pattern = re.compile( + r'(%s:\s*)?(%s)(/)?$' % (valid_nick, valid_correction)) + match = re.match(correction_message_pattern, message) + + if match: + # If message is a correction and we have previous messages from + # this nick, print up to print_limit of the nick's previous + # messages with corrections applied, in their original order. + correction = match.group(4) + if log and correction: + print_format = weechat.config_get_plugin('print_format') + for cm in get_corrected_messages(nick, log, correction): + corrected_msg = print_format + for k, v in cm.iteritems(): + corrected_msg = corrected_msg.replace('[%s]' % k, v) + weechat.prnt_date_tags(buffer, 0, 'no_log', corrected_msg) + else: + # If it's not a correction, store the message in LASTWORDS. + log.insert(0, {'message': message, 'timestamp': date}) + # If there's a per-nick limit, shorten the list to match. + message_limit = get_option_int('message_limit') + while message_limit and len(log) > message_limit: + log.pop() + + return weechat.WEECHAT_RC_OK + + +def load_config(data=None, option=None, value=None): + """ + Load configuration options and (re)register hook_timer to clear old + messages based on the current value of check_every. If check_every is 0 + then messages are never cleared. + """ + + # On initial load set any unset options to the defaults. + if not option: + for option, default in settings.iteritems(): + if not weechat.config_is_set_plugin(option): + weechat.config_set_plugin(option, default) + + if not option or option.endswith('check_every'): + # If hook_timer for clearing old messages is set already, clear it. + old_hook = globals().get('CLEAR_HOOK', None) + if old_hook is not None: + weechat.unhook(old_hook) + + # Register hook_timer to clear old messages. + check_every = get_option_int('check_every') * 1000 + if check_every: + globals()['CLEAR_HOOK'] = weechat.hook_timer( + check_every, 0, 0, 'clear_messages_cb', '') + + return weechat.WEECHAT_RC_OK + + +def desc_options(): + """ + Load descriptions for all the options. + """ + + weechat.config_set_desc_plugin( + 'check_every', 'Interval between each check for expired messages.') + + weechat.config_set_desc_plugin( + 'data_timeout', 'Time before a message is expired.') + + weechat.config_set_desc_plugin( + 'message_limit', 'Number of messages to store per nick.') + + weechat.config_set_desc_plugin( + 'print_format', 'Format string for the printed corrections.') + + weechat.config_set_desc_plugin( + 'print_limit', 'Maximum number of lines to correct.') + + return weechat.WEECHAT_RC_OK + + +if __name__ == '__main__' and import_ok: + if weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, + SCRIPT_LICENSE, SCRIPT_DESC, '', ''): + # Load the configuration options. + load_config() + + # Set up the descriptions for each option. + desc_options() + + # Register hook to run load_config when options are changed. + weechat.hook_config('plugins.var.python.%s.*' % SCRIPT_NAME, + 'load_config', '') + + # Register hook_print to process each new message as it comes in. + weechat.hook_print('', '', '', 1, 'handle_message_cb', '') diff --git a/.weechat/python/autojoin.py b/.weechat/python/autojoin.py new file mode 100644 index 0000000..3fe4b6b --- /dev/null +++ b/.weechat/python/autojoin.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2009 by xt +# +# 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 . +# + +# (this script requires WeeChat 0.3.0 or newer) +# +# History: +# 2009-06-18, xt +# version 0.1: initial release +# +# 2009-10-18, LBo +# version 0.2: added autosaving of join channels +# /set plugins.var.python.autojoin.autosave 'on' +# +# 2009-10-19, LBo +# version 0.2.1: now only responds to part messages from self +# find_channels() only returns join'ed channels, not all the buffers +# updated description and docs +# +# 2009-10-20, LBo +# version 0.2.2: fixed quit callback +# removed the callbacks on part & join messages +# +# 2012-04-14, Filip H.F. "FiXato" Slagter +# version 0.2.3: fixed bug with buffers of which short names were changed. +# Now using 'name' from irc_channel infolist. +# version 0.2.4: Added support for key-protected channels +# +# 2014-05-22, Nathaniel Wesley Filardo +# version 0.2.5: Fix keyed channel support +# +# @TODO: add options to ignore certain buffers +# @TODO: maybe add an option to enable autosaving on part/join messages + +import weechat as w +import re + +SCRIPT_NAME = "autojoin" +SCRIPT_AUTHOR = "xt " +SCRIPT_VERSION = "0.2.5" +SCRIPT_LICENSE = "GPL3" +SCRIPT_DESC = "Configure autojoin for all servers according to currently joined channels" +SCRIPT_COMMAND = "autojoin" + +# script options +settings = { + "autosave": "off", +} + +if w.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, SCRIPT_DESC, "", ""): + + w.hook_command(SCRIPT_COMMAND, + SCRIPT_DESC, + "[--run]", + " --run: actually run the commands instead of displaying\n", + "--run", + "autojoin_cb", + "") + + #w.hook_signal('*,irc_in2_join', 'autosave_channels_on_activity', '') + #w.hook_signal('*,irc_in2_part', 'autosave_channels_on_activity', '') + w.hook_signal('quit', 'autosave_channels_on_quit', '') + +# Init everything +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": + return w.WEECHAT_RC_OK + + 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) + + return w.WEECHAT_RC_OK + + +def autosave_channels_on_activity(signal, callback, callback_data): + ''' Autojoin current channels ''' + if w.config_get_plugin(option) != "on": + return w.WEECHAT_RC_OK + + items = find_channels() + + # print/execute commands + for server, channels in items.iteritems(): + 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) + 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""" + items = find_channels() + + # print/execute commands + for server, channels in items.iteritems(): + channels = channels.rstrip(',') + if not channels: # empty channel list + continue + command = '/set irc.server.%s.autojoin %s' % (server, channels) + if args == '--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." + items = {} + infolist = w.infolist_get('irc_server', '', '') + # populate servers + while w.infolist_next(infolist): + items[w.infolist_string(infolist, 'name')] = '' + + w.infolist_free(infolist) + + # populate channels per server + for server in items.keys(): + keys = [] + keyed_channels = [] + unkeyed_channels = [] + items[server] = '' #init if connected but no channels + infolist = w.infolist_get('irc_channel', '', server) + while w.infolist_next(infolist): + if w.infolist_integer(infolist, 'nicks_count') == 0: + #parted but still open in a buffer: bit hackish + continue + if w.infolist_integer(infolist, 'type') == 0: + key = w.infolist_string(infolist, "key") + if len(key) > 0: + keys.append(key) + keyed_channels.append(w.infolist_string(infolist, "name")) + else : + unkeyed_channels.append(w.infolist_string(infolist, "name")) + items[server] = ','.join(keyed_channels + unkeyed_channels) + if len(keys) > 0: + items[server] += ' %s' % ','.join(keys) + w.infolist_free(infolist) + + return items + diff --git a/.weechat/python/autoload/apply_corrections.py b/.weechat/python/autoload/apply_corrections.py new file mode 120000 index 0000000..9c1ae70 --- /dev/null +++ b/.weechat/python/autoload/apply_corrections.py @@ -0,0 +1 @@ +../apply_corrections.py \ No newline at end of file diff --git a/.weechat/python/autoload/autojoin.py b/.weechat/python/autoload/autojoin.py new file mode 120000 index 0000000..6fceded --- /dev/null +++ b/.weechat/python/autoload/autojoin.py @@ -0,0 +1 @@ +../autojoin.py \ No newline at end of file diff --git a/.weechat/python/autoload/grep.py b/.weechat/python/autoload/grep.py new file mode 120000 index 0000000..87d4ca7 --- /dev/null +++ b/.weechat/python/autoload/grep.py @@ -0,0 +1 @@ +../grep.py \ No newline at end of file diff --git a/.weechat/python/autoload/otr.py b/.weechat/python/autoload/otr.py new file mode 120000 index 0000000..61d1b18 --- /dev/null +++ b/.weechat/python/autoload/otr.py @@ -0,0 +1 @@ +../otr.py \ No newline at end of file diff --git a/.weechat/python/autoload/screen_away.py b/.weechat/python/autoload/screen_away.py new file mode 120000 index 0000000..e485b70 --- /dev/null +++ b/.weechat/python/autoload/screen_away.py @@ -0,0 +1 @@ +../screen_away.py \ No newline at end of file diff --git a/.weechat/python/autoload/urlview.py b/.weechat/python/autoload/urlview.py new file mode 120000 index 0000000..cf5bf9e --- /dev/null +++ b/.weechat/python/autoload/urlview.py @@ -0,0 +1 @@ +../urlview.py \ No newline at end of file diff --git a/.weechat/python/grep.py b/.weechat/python/grep.py new file mode 100644 index 0000000..4fd5c64 --- /dev/null +++ b/.weechat/python/grep.py @@ -0,0 +1,1731 @@ +# -*- coding: utf-8 -*- +### +# Copyright (c) 2009-2011 by Elián Hanisch +# +# 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 . +### + +### +# Search in Weechat buffers and logs (for Weechat 0.3.*) +# +# Inspired by xt's grep.py +# Originally I just wanted to add some fixes in grep.py, but then +# I got carried away and rewrote everything, so new script. +# +# Commands: +# * /grep +# Search in logs or buffers, see /help grep +# * /logs: +# Lists logs in ~/.weechat/logs, see /help logs +# +# Settings: +# * plugins.var.python.grep.clear_buffer: +# Clear the results buffer before each search. Valid values: on, off +# +# * plugins.var.python.grep.go_to_buffer: +# Automatically go to grep buffer when search is over. Valid values: on, off +# +# * plugins.var.python.grep.log_filter: +# Coma separated list of patterns that grep will use for exclude logs, e.g. +# if you use '*server/*' any log in the 'server' folder will be excluded +# when using the command '/grep log' +# +# * plugins.var.python.grep.show_summary: +# Shows summary for each log. Valid values: on, off +# +# * plugins.var.python.grep.max_lines: +# Grep will only print the last matched lines that don't surpass the value defined here. +# +# * plugins.var.python.grep.size_limit: +# Size limit in KiB, is used for decide whenever grepping should run in background or not. If +# the logs to grep have a total size bigger than this value then grep run as a new process. +# 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.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. +# +# +# TODO: +# * try to figure out why hook_process chokes in long outputs (using a tempfile as a +# workaround now) +# * possibly add option for defining time intervals +# +# +# History: +# +# 2015-01-31, Nicd- +# version 0.7.5: +# '~' is now expaned to the home directory in the log file path so +# paths like '~/logs/' should work. +# +# 2015-01-14, nils_2 +# version 0.7.4: make q work to quit grep buffer (requested by: gb) +# +# 2014-03-29, Felix Eckhofer +# version 0.7.3: fix typo +# +# 2011-01-09 +# version 0.7.2: bug fixes +# +# 2010-11-15 +# version 0.7.1: +# * use TempFile so temporal files are guaranteed to be deleted. +# * enable Archlinux workaround. +# +# 2010-10-26 +# version 0.7: +# * added templates. +# * using --only-match shows only unique strings. +# * fixed bug that inverted -B -A switches when used with -t +# +# 2010-10-14 +# version 0.6.8: by xt +# * supress highlights when printing in grep buffer +# +# 2010-10-06 +# version 0.6.7: by xt +# * better temporary file: +# use tempfile.mkstemp. to create a temp file in log dir, +# makes it safer with regards to write permission and multi user +# +# 2010-04-08 +# version 0.6.6: bug fixes +# * use WEECHAT_LIST_POS_END in log file completion, makes completion faster +# * disable bytecode if using python 2.6 +# * use single quotes in command string +# * fix bug that could change buffer's title when using /grep stop +# +# 2010-01-24 +# version 0.6.5: disable bytecode is a 2.6 feature, instead, resort to delete the bytecode manually +# +# 2010-01-19 +# version 0.6.4: bug fix +# version 0.6.3: added options --invert --only-match (replaces --exact, which is still available +# but removed from help) +# * use new 'irc_nick_color' info +# * don't generate bytecode when spawning a new process +# * show active options in buffer title +# +# 2010-01-17 +# version 0.6.2: removed 2.6-ish code +# version 0.6.1: fixed bug when grepping in grep's buffer +# +# 2010-01-14 +# version 0.6.0: implemented grep in background +# * improved context lines presentation. +# * grepping for big (or many) log files runs in a weechat_process. +# * added /grep stop. +# * added 'size_limit' option +# * fixed a infolist leak when grepping buffers +# * added 'default_tail_head' option +# * results are sort by line count +# * don't die if log is corrupted (has NULL chars in it) +# * changed presentation of /logs +# * log path completion doesn't suck anymore +# * removed all tabs, because I learned how to configure Vim so that spaces aren't annoying +# anymore. This was the script's original policy. +# +# 2010-01-05 +# version 0.5.5: rename script to 'grep.py' (FlashCode ). +# +# 2010-01-04 +# version 0.5.4.1: fix index error when using --after/before-context options. +# +# 2010-01-03 +# version 0.5.4: new features +# * added --after-context and --before-context options. +# * added --context as a shortcut for using both -A -B options. +# +# 2009-11-06 +# version 0.5.3: improvements for long grep output +# * grep buffer input accepts the same flags as /grep for repeat a search with different +# options. +# * tweaks in grep's output. +# * max_lines option added for limit grep's output. +# * code in update_buffer() optimized. +# * time stats in buffer title. +# * added go_to_buffer config option. +# * added --buffer for search only in buffers. +# * refactoring. +# +# 2009-10-12, omero +# version 0.5.2: made it python-2.4.x compliant +# +# 2009-08-17 +# version 0.5.1: some refactoring, show_summary option added. +# +# 2009-08-13 +# version 0.5: rewritten from xt's grep.py +# * fixed searching in non weechat logs, for cases like, if you're +# switching from irssi and rename and copy your irssi logs to %h/logs +# * fixed "timestamp rainbow" when you /grep in grep's buffer +# * allow to search in other buffers other than current or in logs +# of currently closed buffers with cmd 'buffer' +# * allow to search in any log file in %h/logs with cmd 'log' +# * added --count for return the number of matched lines +# * added --matchcase for case sensible search +# * added --hilight for color matches +# * added --head and --tail options, and --number +# * added command /logs for list files in %h/logs +# * added config option for clear the buffer before a search +# * added config option for filter logs we don't want to grep +# * added the posibility to repeat last search with another regexp by writing +# it in grep's buffer +# * changed spaces for tabs in the code, which is my preference +# +### + +from os import path +import sys, getopt, time, os, re, tempfile + +try: + import weechat + from weechat import WEECHAT_RC_OK, prnt, prnt_date_tags + import_ok = True +except ImportError: + import_ok = False + +SCRIPT_NAME = "grep" +SCRIPT_AUTHOR = "Elián Hanisch " +SCRIPT_VERSION = "0.7.5" +SCRIPT_LICENSE = "GPL3" +SCRIPT_DESC = "Search in buffers and logs" +SCRIPT_COMMAND = "grep" + +### Default Settings ### +settings = { +'clear_buffer' : 'off', +'log_filter' : '', +'go_to_buffer' : 'on', +'max_lines' : '4000', +'show_summary' : 'on', +'size_limit' : '2048', +'default_tail_head' : '10', +} + +### Class definitions ### +class linesDict(dict): + """ + Class for handling matched lines in more than one buffer. + linesDict[buffer_name] = matched_lines_list + """ + def __setitem__(self, key, value): + assert isinstance(value, list) + if key not in self: + dict.__setitem__(self, key, value) + else: + dict.__getitem__(self, key).extend(value) + + 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())) + else: + return 0 + + def __len__(self): + """Return the sum of total lines stored.""" + if dict.__len__(self): + return sum(map(len, self.itervalues())) + else: + return 0 + + def __str__(self): + """Returns buffer count or buffer name if there's just one stored.""" + n = len(self.keys()) + if n == 1: + return self.keys()[0] + elif n > 1: + return '%s logs' %n + else: + return '' + + def items(self): + """Returns a list of items sorted by line count.""" + items = 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.sort(key=lambda i: i[1].matches_count) + return items + + def strip_separator(self): + for L in self.itervalues(): + L.strip_separator() + + def get_last_lines(self, n): + total_lines = len(self) + #debug('total: %s n: %s' %(total_lines, n)) + if n >= total_lines: + # nothing to do + return + for k, v in reversed(self.items()): + l = len(v) + if n > 0: + if l > n: + del v[:l-n] + v.stripped_lines = l-n + n -= l + else: + del v[:] + v.stripped_lines = l + +class linesList(list): + """Class for list of matches, since sometimes I need to add lines that aren't matches, I need an + independent counter.""" + _sep = '...' + def __init__(self, *args): + list.__init__(self, *args) + self.matches_count = 0 + self.stripped_lines = 0 + + def append(self, item): + """Append lines, can be a string or a list with strings.""" + if isinstance(item, str): + list.append(self, item) + else: + self.extend(item) + + def append_separator(self): + """adds a separator into the list, makes sure it doen't add two together.""" + s = self._sep + if (self and self[-1] != s) or not self: + self.append(s) + + def onlyUniq(self): + s = set(self) + del self[:] + self.extend(s) + + def count_match(self, item=None): + if item is None or isinstance(item, str): + self.matches_count += 1 + else: + self.matches_count += len(item) + + def strip_separator(self): + """removes separators if there are first or/and last in the list.""" + if self: + s = self._sep + if self[0] == s: + del self[0] + if self[-1] == s: + del self[-1] + +### Misc functions ### +now = time.time +def get_size(f): + try: + return os.stat(f).st_size + except OSError: + return 0 + +sizeDict = {0:'b', 1:'KiB', 2:'MiB', 3:'GiB', 4:'TiB'} +def human_readable_size(size): + power = 0 + while size > 1024: + power += 1 + size /= 1024.0 + return '%.2f %s' %(size, sizeDict.get(power, '')) + +def color_nick(nick): + """Returns coloured nick, with coloured mode if any.""" + if not nick: return '' + wcolor = weechat.color + config_string = lambda s : weechat.config_string(weechat.config_get(s)) + config_int = lambda s : weechat.config_integer(weechat.config_get(s)) + # prefix and suffix + prefix = config_string('irc.look.nick_prefix') + suffix = config_string('irc.look.nick_suffix') + prefix_c = suffix_c = wcolor(config_string('weechat.color.chat_delimiters')) + if nick[0] == prefix: + nick = nick[1:] + else: + prefix = prefix_c = '' + if nick[-1] == suffix: + nick = nick[:-1] + suffix = wcolor(color_delimiter) + suffix + else: + suffix = suffix_c = '' + # nick mode + modes = '@!+%' + if nick[0] in modes: + mode, nick = nick[0], nick[1:] + mode_color = wcolor(config_string('weechat.color.nicklist_prefix%d' \ + %(modes.find(mode) + 1))) + else: + mode = mode_color = '' + # nick color + nick_color = weechat.info_get('irc_nick_color', nick) + if not nick_color: + # probably we're in WeeChat 0.3.0 + #debug('no irc_nick_color') + color_nicks_number = config_int('weechat.look.color_nicks_number') + idx = (sum(map(ord, nick))%color_nicks_number) + 1 + nick_color = wcolor(config_string('weechat.color.chat_nick_color%02d' %idx)) + return ''.join((prefix_c, prefix, mode_color, mode, nick_color, nick, suffix_c, suffix)) + +### Config and value validation ### +boolDict = {'on':True, 'off':False} +def get_config_boolean(config): + value = weechat.config_get_plugin(config) + try: + return boolDict[value] + except KeyError: + default = settings[config] + error("Error while fetching config '%s'. Using default value '%s'." %(config, default)) + error("'%s' is invalid, allowed: 'on', 'off'" %value) + return boolDict[default] + +def get_config_int(config, allow_empty_string=False): + value = weechat.config_get_plugin(config) + try: + return int(value) + except ValueError: + if value == '' and allow_empty_string: + return value + default = settings[config] + error("Error while fetching config '%s'. Using default value '%s'." %(config, default)) + error("'%s' is not a number." %value) + return int(default) + +def get_config_log_filter(): + filter = weechat.config_get_plugin('log_filter') + if filter: + return filter.split(',') + else: + return [] + +def get_home(): + home = weechat.config_string(weechat.config_get('logger.file.path')) + home = path.abspath(path.expanduser(home)) + return home.replace('%h', weechat.info_get('weechat_dir', '')) + +def strip_home(s, dir=''): + """Strips home dir from the begging of the log path, this makes them sorter.""" + if not dir: + global home_dir + dir = home_dir + l = len(dir) + if s[:l] == dir: + return s[l:] + return s + +### Messages ### +script_nick = SCRIPT_NAME +def error(s, buffer=''): + """Error msg""" + prnt(buffer, '%s%s %s' %(weechat.prefix('error'), script_nick, s)) + if weechat.config_get_plugin('debug'): + import traceback + if traceback.sys.exc_type: + trace = traceback.format_exc() + prnt('', trace) + +def say(s, buffer=''): + """normal msg""" + prnt_date_tags(buffer, 0, 'no_highlight', '%s\t%s' %(script_nick, s)) + + + +### Log files and buffers ### +cache_dir = {} # note: don't remove, needed for completion if the script was loaded recently +def dir_list(dir, filter_list=(), filter_excludes=True, include_dir=False): + """Returns a list of files in 'dir' and its subdirs.""" + global cache_dir + from os import walk + from fnmatch import fnmatch + #debug('dir_list: listing in %s' %dir) + key = (dir, include_dir) + try: + return cache_dir[key] + except KeyError: + pass + + filter_list = filter_list or get_config_log_filter() + dir_len = len(dir) + if filter_list: + def filter(file): + file = file[dir_len:] # pattern shouldn't match home dir + for pattern in filter_list: + if fnmatch(file, pattern): + return filter_excludes + return not filter_excludes + else: + filter = lambda f : not filter_excludes + + file_list = [] + extend = file_list.extend + join = path.join + def walk_path(): + for basedir, subdirs, files in walk(dir): + #if include_dir: + # subdirs = map(lambda s : join(s, ''), subdirs) + # files.extend(subdirs) + files_path = map(lambda f : join(basedir, f), files) + files_path = [ file for file in files_path if not filter(file) ] + extend(files_path) + + walk_path() + cache_dir[key] = file_list + #debug('dir_list: got %s' %str(file_list)) + return file_list + +def get_file_by_pattern(pattern, all=False): + """Returns the first log whose path matches 'pattern', + if all is True returns all logs that matches.""" + if not pattern: return [] + #debug('get_file_by_filename: searching for %s.' %pattern) + # do envvar expandsion and check file + file = path.expanduser(pattern) + file = path.expandvars(file) + if path.isfile(file): + return [file] + # lets see if there's a matching log + global home_dir + file = path.join(home_dir, pattern) + if path.isfile(file): + return [file] + else: + from fnmatch import fnmatch + file = [] + file_list = dir_list(home_dir) + n = len(home_dir) + for log in file_list: + basename = log[n:] + if fnmatch(basename, pattern): + file.append(log) + #debug('get_file_by_filename: got %s.' %file) + if not all and file: + file.sort() + return [ file[-1] ] + return file + +def get_file_by_buffer(buffer): + """Given buffer pointer, finds log's path or returns None.""" + #debug('get_file_by_buffer: searching for %s' %buffer) + infolist = weechat.infolist_get('logger_buffer', '', '') + if not infolist: return + try: + while weechat.infolist_next(infolist): + pointer = weechat.infolist_pointer(infolist, 'buffer') + if pointer == buffer: + file = weechat.infolist_string(infolist, 'log_filename') + if weechat.infolist_integer(infolist, 'log_enabled'): + #debug('get_file_by_buffer: got %s' %file) + return file + #else: + # debug('get_file_by_buffer: got %s but log not enabled' %file) + finally: + #debug('infolist gets freed') + weechat.infolist_free(infolist) + +def get_file_by_name(buffer_name): + """Given a buffer name, returns its log path or None. buffer_name should be in 'server.#channel' + or '#channel' format.""" + #debug('get_file_by_name: searching for %s' %buffer_name) + # common mask options + config_masks = ('logger.mask.irc', 'logger.file.mask') + # since there's no buffer pointer, we try to replace some local vars in mask, like $channel and + # $server, then replace the local vars left with '*', and use it as a mask for get the path with + # get_file_by_pattern + for config in config_masks: + mask = weechat.config_string(weechat.config_get(config)) + #debug('get_file_by_name: mask: %s' %mask) + if '$name' in mask: + mask = mask.replace('$name', buffer_name) + elif '$channel' in mask or '$server' in mask: + if '.' in buffer_name and \ + '#' not in buffer_name[:buffer_name.find('.')]: # the dot isn't part of the channel name + # ^ I'm asuming channel starts with #, i'm lazy. + server, channel = buffer_name.split('.', 1) + else: + server, channel = '*', buffer_name + if '$channel' in mask: + mask = mask.replace('$channel', channel) + if '$server' in mask: + mask = mask.replace('$server', server) + # change the unreplaced vars by '*' + from string import letters + if '%' in mask: + # vars for time formatting + mask = mask.replace('%', '$') + if '$' in mask: + masks = mask.split('$') + masks = map(lambda s: s.lstrip(letters), masks) + mask = '*'.join(masks) + if mask[0] != '*': + mask = '*' + mask + #debug('get_file_by_name: using mask %s' %mask) + file = get_file_by_pattern(mask) + #debug('get_file_by_name: got file %s' %file) + if file: + return file + return None + +def get_buffer_by_name(buffer_name): + """Given a buffer name returns its buffer pointer or None.""" + #debug('get_buffer_by_name: searching for %s' %buffer_name) + pointer = weechat.buffer_search('', buffer_name) + if not pointer: + try: + infolist = weechat.infolist_get('buffer', '', '') + while weechat.infolist_next(infolist): + short_name = weechat.infolist_string(infolist, 'short_name') + name = weechat.infolist_string(infolist, 'name') + if buffer_name in (short_name, name): + #debug('get_buffer_by_name: found %s' %name) + pointer = weechat.buffer_search('', name) + return pointer + finally: + weechat.infolist_free(infolist) + #debug('get_buffer_by_name: got %s' %pointer) + return pointer + +def get_all_buffers(): + """Returns list with pointers of all open buffers.""" + buffers = [] + infolist = weechat.infolist_get('buffer', '', '') + while weechat.infolist_next(infolist): + buffers.append(weechat.infolist_pointer(infolist, 'pointer')) + weechat.infolist_free(infolist) + grep_buffer = weechat.buffer_search('python', SCRIPT_NAME) + if grep_buffer and grep_buffer in buffers: + # remove it from list + del buffers[buffers.index(grep_buffer)] + return buffers + +### Grep ### +def make_regexp(pattern, matchcase=False): + """Returns a compiled regexp.""" + if pattern in ('.', '.*', '.?', '.+'): + # because I don't need to use a regexp if we're going to match all lines + return None + # matching takes a lot more time if pattern starts or ends with .* and it isn't needed. + if pattern[:2] == '.*': + pattern = pattern[2:] + if pattern[-2:] == '.*': + pattern = pattern[:-2] + try: + if not matchcase: + regexp = re.compile(pattern, re.IGNORECASE) + else: + regexp = re.compile(pattern) + except Exception, e: + raise Exception, 'Bad pattern, %s' %e + return regexp + +def check_string(s, regexp, hilight='', exact=False): + """Checks 's' with a regexp and returns it if is a match.""" + if not regexp: + return s + + elif exact: + matchlist = regexp.findall(s) + if matchlist: + if isinstance(matchlist[0], tuple): + # join tuples (when there's more than one match group in regexp) + return [ ' '.join(t) for t in matchlist ] + return matchlist + + elif hilight: + matchlist = regexp.findall(s) + if matchlist: + if isinstance(matchlist[0], tuple): + # flatten matchlist + matchlist = [ item for L in matchlist for item in L if item ] + matchlist = list(set(matchlist)) # remove duplicates if any + # apply hilight + color_hilight, color_reset = hilight.split(',', 1) + for m in matchlist: + s = s.replace(m, '%s%s%s' % (color_hilight, m, color_reset)) + return s + + # no need for findall() here + elif regexp.search(s): + return s + +def grep_file(file, head, tail, after_context, before_context, count, regexp, hilight, exact, invert): + """Return a list of lines that match 'regexp' in 'file', if no regexp returns all lines.""" + if count: + tail = head = after_context = before_context = False + hilight = '' + elif exact: + before_context = after_context = False + hilight = '' + elif invert: + hilight = '' + #debug(' '.join(map(str, (file, head, tail, after_context, before_context)))) + + lines = linesList() + # define these locally as it makes the loop run slightly faster + append = lines.append + count_match = lines.count_match + separator = lines.append_separator + if invert: + def check(s): + if check_string(s, regexp, hilight, exact): + return None + else: + return s + else: + check = lambda s: check_string(s, regexp, hilight, exact) + + try: + file_object = open(file, 'r') + except IOError: + # file doesn't exist + return lines + if tail or before_context: + # for these options, I need to seek in the file, but is slower and uses a good deal of + # memory if the log is too big, so we do this *only* for these options. + file_lines = file_object.readlines() + + if tail: + # instead of searching in the whole file and later pick the last few lines, we + # reverse the log, search until count reached and reverse it again, that way is a lot + # faster + file_lines.reverse() + # don't invert context switches + before_context, after_context = after_context, before_context + + if before_context: + before_context_range = range(1, before_context + 1) + before_context_range.reverse() + + limit = tail or head + + line_idx = 0 + while line_idx < len(file_lines): + line = file_lines[line_idx] + line = check(line) + if line: + if before_context: + separator() + trimmed = False + for id in before_context_range: + try: + context_line = file_lines[line_idx - id] + if check(context_line): + # match in before context, that means we appended these same lines in a + # previous match, so we delete them merging both paragraphs + if not trimmed: + del lines[id - before_context - 1:] + trimmed = True + else: + append(context_line) + except IndexError: + pass + append(line) + count_match(line) + if after_context: + id, offset = 0, 0 + while id < after_context + offset: + id += 1 + try: + context_line = file_lines[line_idx + id] + _context_line = check(context_line) + if _context_line: + offset = id + context_line = _context_line # so match is hilighted with --hilight + count_match() + append(context_line) + except IndexError: + pass + separator() + line_idx += id + if limit and lines.matches_count >= limit: + break + line_idx += 1 + + if tail: + lines.reverse() + else: + # do a normal grep + limit = head + + for line in file_object: + line = check(line) + if line: + count or append(line) + count_match(line) + if after_context: + id, offset = 0, 0 + while id < after_context + offset: + id += 1 + try: + context_line = file_object.next() + _context_line = check(context_line) + if _context_line: + offset = id + context_line = _context_line + count_match() + count or append(context_line) + except StopIteration: + pass + separator() + if limit and lines.matches_count >= limit: + break + + file_object.close() + return lines + +def grep_buffer(buffer, head, tail, after_context, before_context, count, regexp, hilight, exact, + invert): + """Return a list of lines that match 'regexp' in 'buffer', if no regexp returns all lines.""" + lines = linesList() + if count: + tail = head = after_context = before_context = False + hilight = '' + elif exact: + before_context = after_context = False + #debug(' '.join(map(str, (tail, head, after_context, before_context, count, exact, hilight)))) + + # Using /grep in grep's buffer can lead to some funny effects + # We should take measures if that's the case + def make_get_line_funcion(): + """Returns a function for get lines from the infolist, depending if the buffer is grep's or + not.""" + string_remove_color = weechat.string_remove_color + infolist_string = weechat.infolist_string + grep_buffer = weechat.buffer_search('python', SCRIPT_NAME) + if grep_buffer and buffer == grep_buffer: + def function(infolist): + prefix = infolist_string(infolist, 'prefix') + message = infolist_string(infolist, 'message') + if prefix: # only our messages have prefix, ignore it + return None + return message + else: + infolist_time = weechat.infolist_time + def function(infolist): + prefix = string_remove_color(infolist_string(infolist, 'prefix'), '') + message = string_remove_color(infolist_string(infolist, 'message'), '') + date = infolist_time(infolist, 'date') + return '%s\t%s\t%s' %(date, prefix, message) + return function + get_line = make_get_line_funcion() + + infolist = weechat.infolist_get('buffer_lines', buffer, '') + if tail: + # like with grep_file() if we need the last few matching lines, we move the cursor to + # the end and search backwards + infolist_next = weechat.infolist_prev + infolist_prev = weechat.infolist_next + else: + infolist_next = weechat.infolist_next + infolist_prev = weechat.infolist_prev + limit = head or tail + + # define these locally as it makes the loop run slightly faster + append = lines.append + count_match = lines.count_match + separator = lines.append_separator + if invert: + def check(s): + if check_string(s, regexp, hilight, exact): + return None + else: + return s + else: + check = lambda s: check_string(s, regexp, hilight, exact) + + if before_context: + before_context_range = range(1, before_context + 1) + before_context_range.reverse() + + while infolist_next(infolist): + line = get_line(infolist) + if line is None: continue + line = check(line) + if line: + if before_context: + separator() + trimmed = False + for id in before_context_range: + if not infolist_prev(infolist): + trimmed = True + for id in before_context_range: + context_line = get_line(infolist) + if check(context_line): + if not trimmed: + del lines[id - before_context - 1:] + trimmed = True + else: + append(context_line) + infolist_next(infolist) + count or append(line) + count_match(line) + if after_context: + id, offset = 0, 0 + while id < after_context + offset: + id += 1 + if infolist_next(infolist): + context_line = get_line(infolist) + _context_line = check(context_line) + if _context_line: + context_line = _context_line + offset = id + count_match() + append(context_line) + else: + # in the main loop infolist_next will start again an cause an infinite loop + # this will avoid it + infolist_next = lambda x: 0 + separator() + if limit and lines.matches_count >= limit: + break + weechat.infolist_free(infolist) + + if tail: + lines.reverse() + return lines + +### this is our main grep function +hook_file_grep = None +def show_matching_lines(): + """ + Greps buffers in search_in_buffers or files in search_in_files and updates grep buffer with the + result. + """ + global pattern, matchcase, number, count, exact, hilight, invert + global tail, head, after_context, before_context + global search_in_files, search_in_buffers, matched_lines, home_dir + global time_start + matched_lines = linesDict() + #debug('buffers:%s \nlogs:%s' %(search_in_buffers, search_in_files)) + time_start = now() + + # buffers + if search_in_buffers: + regexp = make_regexp(pattern, matchcase) + for buffer in search_in_buffers: + buffer_name = weechat.buffer_get_string(buffer, 'name') + matched_lines[buffer_name] = grep_buffer(buffer, head, tail, after_context, + before_context, count, regexp, hilight, exact, invert) + + # logs + if search_in_files: + size_limit = get_config_int('size_limit', allow_empty_string=True) + background = False + if size_limit or size_limit == 0: + size = sum(map(get_size, search_in_files)) + if size > size_limit * 1024: + background = True + elif size_limit == '': + background = False + + 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) + 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 + if hook_file_grep: + 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, ) +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' +""" + +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(): + 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 grep_stderr: + error(grep_stderr) + set_buffer_error() + #elif grep_stdout: + #debug(grep_stdout) + elif path.exists(filename): + import cPickle + 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() + 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(): + global search_in_files, matched_lines, time_start + elapsed = now() - time_start + if len(search_in_files) == 1: + log = '%s (%s)' %(strip_home(search_in_files[0]), + human_readable_size(get_size(search_in_files[0]))) + else: + size = sum(map(get_size, search_in_files)) + log = '%s log files (%s)' %(len(search_in_files), human_readable_size(size)) + return 'Searching in %s, running for %.4f seconds. Interrupt it with "/grep stop" or "stop"' \ + ' in grep buffer.' %(log, elapsed) + +### Grep buffer ### +def buffer_update(): + """Updates our buffer with new lines.""" + global pattern_tmpl, matched_lines, pattern, count, hilight, invert, exact + time_grep = now() + + buffer = buffer_create() + if get_config_boolean('clear_buffer'): + weechat.buffer_clear(buffer) + matched_lines.strip_separator() # remove first and last separators of each list + len_total_lines = len(matched_lines) + max_lines = get_config_int('max_lines') + if not count and len_total_lines > max_lines: + weechat.buffer_clear(buffer) + + def _make_summary(log, lines, note): + return '%s matches "%s%s%s"%s in %s%s%s%s' \ + %(lines.matches_count, color_summary, pattern_tmpl, color_info, + invert and ' (inverted)' or '', + color_summary, log, color_reset, note) + + if count: + make_summary = lambda log, lines : _make_summary(log, lines, ' (not shown)') + else: + def make_summary(log, lines): + if lines.stripped_lines: + if lines: + note = ' (last %s lines shown)' %len(lines) + else: + note = ' (not shown)' + else: + note = '' + return _make_summary(log, lines, note) + + global weechat_format + if hilight: + # we don't want colors if there's match highlighting + format_line = lambda s : '%s %s %s' %split_line(s) + else: + def format_line(s): + global nick_dict, weechat_format + date, nick, msg = split_line(s) + if weechat_format: + try: + nick = nick_dict[nick] + except KeyError: + # cache nick + nick_c = color_nick(nick) + nick_dict[nick] = nick_c + nick = nick_c + return '%s%s %s%s %s' %(color_date, date, nick, color_reset, msg) + else: + #no formatting + return msg + + prnt(buffer, '\n') + print_line('Search for "%s%s%s"%s in %s%s%s.' %(color_summary, pattern_tmpl, color_info, + invert and ' (inverted)' or '', color_summary, matched_lines, color_reset), + buffer) + # print last lines + if matched_lines.get_matches_count(): + if count: + # with count we sort by matches lines instead of just lines. + matched_lines_items = matched_lines.items_count() + else: + matched_lines_items = matched_lines.items() + + matched_lines.get_last_lines(max_lines) + for log, lines in matched_lines_items: + if lines.matches_count: + # matched lines + if not count: + # print lines + weechat_format = True + if exact: + lines.onlyUniq() + for line in lines: + #debug(repr(line)) + if line == linesList._sep: + # separator + prnt(buffer, context_sep) + else: + if '\x00' in line: + # log was corrupted + error("Found garbage in log '%s', maybe it's corrupted" %log) + line = line.replace('\x00', '') + prnt_date_tags(buffer, 0, 'no_highlight', format_line(line)) + + # summary + if count or get_config_boolean('show_summary'): + summary = make_summary(log, lines) + print_line(summary, buffer) + + # separator + if not count and lines: + prnt(buffer, '\n') + else: + print_line('No matches found.', buffer) + + # set title + global time_start + time_end = now() + # total time + time_total = time_end - time_start + # percent of the total time used for grepping + time_grep_pct = (time_grep - time_start)/time_total*100 + #debug('time: %.4f seconds (%.2f%%)' %(time_total, time_grep_pct)) + if not count and len_total_lines > max_lines: + note = ' (last %s lines shown)' %len(matched_lines) + else: + note = '' + title = "'q': close buffer | Search in %s%s%s %s matches%s | pattern \"%s%s%s\"%s %s | %.4f seconds (%.2f%%)" \ + %(color_title, matched_lines, color_reset, matched_lines.get_matches_count(), note, + color_title, pattern_tmpl, color_reset, invert and ' (inverted)' or '', format_options(), + time_total, time_grep_pct) + weechat.buffer_set(buffer, 'title', title) + + if get_config_boolean('go_to_buffer'): + weechat.buffer_set(buffer, 'display', '1') + + # free matched_lines so it can be removed from memory + del matched_lines + +def split_line(s): + """Splits log's line 's' in 3 parts, date, nick and msg.""" + global weechat_format + if weechat_format and s.count('\t') >= 2: + date, nick, msg = s.split('\t', 2) # date, nick, message + else: + # looks like log isn't in weechat's format + weechat_format = False # incoming lines won't be formatted + date, nick, msg = '', '', s + # remove tabs + if '\t' in msg: + msg = msg.replace('\t', ' ') + return date, nick, msg + +def print_line(s, buffer=None, display=False): + """Prints 's' in script's buffer as 'script_nick'. For displaying search summaries.""" + if buffer is None: + buffer = buffer_create() + say('%s%s' %(color_info, s), buffer) + if display and get_config_boolean('go_to_buffer'): + weechat.buffer_set(buffer, 'display', '1') + +def format_options(): + global matchcase, number, count, exact, hilight, invert + global tail, head, after_context, before_context + options = [] + append = options.append + insert = options.insert + chars = 'cHmov' + for i, flag in enumerate((count, hilight, matchcase, exact, invert)): + if flag: + append(chars[i]) + + if head or tail: + n = get_config_int('default_tail_head') + if head: + append('h') + if head != n: + insert(-1, ' -') + append('n') + append(head) + elif tail: + append('t') + if tail != n: + insert(-1, ' -') + append('n') + append(tail) + + if before_context and after_context and (before_context == after_context): + append(' -C') + append(before_context) + else: + if before_context: + append(' -B') + append(before_context) + if after_context: + append(' -A') + append(after_context) + + s = ''.join(map(str, options)).strip() + if s and s[0] != '-': + s = '-' + s + return s + +def buffer_create(title=None): + """Returns our buffer pointer, creates and cleans the buffer if needed.""" + buffer = weechat.buffer_search('python', SCRIPT_NAME) + if not buffer: + buffer = weechat.buffer_new(SCRIPT_NAME, 'buffer_input', '', '', '') + weechat.buffer_set(buffer, 'time_for_each_line', '0') + weechat.buffer_set(buffer, 'nicklist', '0') + weechat.buffer_set(buffer, 'title', title or 'grep output buffer') + weechat.buffer_set(buffer, 'localvar_set_no_log', '1') + elif title: + weechat.buffer_set(buffer, 'title', title) + return buffer + +def buffer_input(data, buffer, input_data): + """Repeats last search with 'input_data' as regexp.""" + try: + cmd_grep_stop(buffer, input_data) + except: + return WEECHAT_RC_OK + if input_data in ('q', 'Q'): + weechat.buffer_close(buffer) + return weechat.WEECHAT_RC_OK + + global search_in_buffers, search_in_files + global pattern + try: + if pattern and (search_in_files or search_in_buffers): + # check if the buffer pointers are still valid + for pointer in search_in_buffers: + infolist = weechat.infolist_get('buffer', pointer, '') + if not infolist: + del search_in_buffers[search_in_buffers.index(pointer)] + weechat.infolist_free(infolist) + try: + cmd_grep_parsing(input_data) + except Exception, e: + error('Argument error, %s' %e, buffer=buffer) + return WEECHAT_RC_OK + try: + show_matching_lines() + except Exception, e: + error(e) + except NameError: + error("There isn't any previous search to repeat.", buffer=buffer) + return WEECHAT_RC_OK + +### Commands ### +def cmd_init(): + """Resets global vars.""" + global home_dir, cache_dir, nick_dict + global pattern_tmpl, pattern, matchcase, number, count, exact, hilight, invert + global tail, head, after_context, before_context + hilight = '' + head = tail = after_context = before_context = invert = False + matchcase = count = exact = False + pattern_tmpl = pattern = number = None + home_dir = get_home() + cache_dir = {} # for avoid walking the dir tree more than once per command + nick_dict = {} # nick cache for don't calculate nick color every time + +def cmd_grep_parsing(args): + """Parses args for /grep and grep input buffer.""" + global pattern_tmpl, pattern, matchcase, number, count, exact, hilight, invert + global tail, head, after_context, before_context + global log_name, buffer_name, only_buffers, all + opts, args = getopt.gnu_getopt(args.split(), 'cmHeahtivn:bA:B:C:o', ['count', 'matchcase', 'hilight', + 'exact', 'all', 'head', 'tail', 'number=', 'buffer', 'after-context=', 'before-context=', + 'context=', 'invert', 'only-match']) + #debug(opts, 'opts: '); debug(args, 'args: ') + if len(args) >= 2: + if args[0] == 'log': + del args[0] + log_name = args.pop(0) + elif args[0] == 'buffer': + del args[0] + buffer_name = args.pop(0) + + def tmplReplacer(match): + """This function will replace templates with regexps""" + s = match.groups()[0] + tmpl_args = s.split() + tmpl_key, _, tmpl_args = s.partition(' ') + try: + template = templates[tmpl_key] + if callable(template): + r = template(tmpl_args) + if not r: + error("Template %s returned empty string "\ + "(WeeChat doesn't have enough data)." %t) + return r + else: + return template + except: + return t + + args = ' '.join(args) # join pattern for keep spaces + if args: + pattern_tmpl = args + pattern = _tmplRe.sub(tmplReplacer, args) + debug('Using regexp: %s', pattern) + if not pattern: + raise Exception, 'No pattern for grep the logs.' + + def positive_number(opt, val): + try: + number = int(val) + if number < 0: + raise ValueError + return number + except ValueError: + if len(opt) == 1: + opt = '-' + opt + else: + opt = '--' + opt + raise Exception, "argument for %s must be a positive integer." %opt + + for opt, val in opts: + opt = opt.strip('-') + if opt in ('c', 'count'): + count = not count + elif opt in ('m', 'matchcase'): + matchcase = not matchcase + elif opt in ('H', 'hilight'): + # hilight must be always a string! + if hilight: + hilight = '' + else: + hilight = '%s,%s' %(color_hilight, color_reset) + # we pass the colors in the variable itself because check_string() must not use + # weechat's module when applying the colors (this is for grep in a hooked process) + elif opt in ('e', 'exact', 'o', 'only-match'): + exact = not exact + invert = False + elif opt in ('a', 'all'): + all = not all + elif opt in ('h', 'head'): + head = not head + tail = False + elif opt in ('t', 'tail'): + tail = not tail + head = False + elif opt in ('b', 'buffer'): + only_buffers = True + elif opt in ('n', 'number'): + number = positive_number(opt, val) + elif opt in ('C', 'context'): + n = positive_number(opt, val) + after_context = n + before_context = n + elif opt in ('A', 'after-context'): + after_context = positive_number(opt, val) + elif opt in ('B', 'before-context'): + before_context = positive_number(opt, val) + elif opt in ('i', 'v', 'invert'): + invert = not invert + exact = False + # number check + if number is not None: + if number == 0: + head = tail = False + number = None + elif head: + head = number + elif tail: + tail = number + else: + n = get_config_int('default_tail_head') + if head: + head = n + elif tail: + tail = n + +def cmd_grep_stop(buffer, args): + global hook_file_grep, pattern, matched_lines, tmpFile + 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 + else: + say(get_grep_file_status(), buffer) + raise Exception + +def cmd_grep(data, buffer, args): + """Search in buffers and logs.""" + global pattern, matchcase, head, tail, number, count, exact, hilight + try: + cmd_grep_stop(buffer, args) + except: + return WEECHAT_RC_OK + + if not args: + weechat.command('', '/help %s' %SCRIPT_COMMAND) + return WEECHAT_RC_OK + + cmd_init() + global log_name, buffer_name, only_buffers, all + log_name = buffer_name = '' + only_buffers = all = False + + # parse + try: + cmd_grep_parsing(args) + except Exception, e: + error('Argument error, %s' %e) + return WEECHAT_RC_OK + + # find logs + log_file = search_buffer = None + if log_name: + log_file = get_file_by_pattern(log_name, all) + if not log_file: + error("Couldn't find any log for %s. Try /logs" %log_name) + return WEECHAT_RC_OK + elif all: + search_buffer = get_all_buffers() + elif buffer_name: + search_buffer = get_buffer_by_name(buffer_name) + if not search_buffer: + # there's no buffer, try in the logs + log_file = get_file_by_name(buffer_name) + if not log_file: + error("Logs or buffer for '%s' not found." %buffer_name) + return WEECHAT_RC_OK + else: + search_buffer = [search_buffer] + else: + search_buffer = [buffer] + + # make the log list + global search_in_files, search_in_buffers + search_in_files = [] + search_in_buffers = [] + if log_file: + search_in_files = log_file + elif not only_buffers: + #debug(search_buffer) + for pointer in search_buffer: + log = get_file_by_buffer(pointer) + #debug('buffer %s log %s' %(pointer, log)) + if log: + search_in_files.append(log) + else: + search_in_buffers.append(pointer) + else: + search_in_buffers = search_buffer + + # grepping + try: + show_matching_lines() + except Exception, e: + error(e) + return WEECHAT_RC_OK + +def cmd_logs(data, buffer, args): + """List files in Weechat's log dir.""" + cmd_init() + global home_dir + sort_by_size = False + filter = [] + + try: + opts, args = getopt.gnu_getopt(args.split(), 's', ['size']) + if args: + filter = args + for opt, var in opts: + opt = opt.strip('-') + if opt in ('size', 's'): + sort_by_size = True + except Exception, e: + error('Argument error, %s' %e) + return WEECHAT_RC_OK + + # is there's a filter, filter_excludes should be False + file_list = dir_list(home_dir, filter, filter_excludes=not filter) + if sort_by_size: + file_list.sort(key=get_size) + else: + file_list.sort() + + file_sizes = map(lambda x: human_readable_size(get_size(x)), file_list) + # calculate column lenght + if file_list: + L = file_list[:] + L.sort(key=len) + bigest = L[-1] + column_len = len(bigest) + 3 + else: + column_len = '' + + buffer = buffer_create() + if get_config_boolean('clear_buffer'): + weechat.buffer_clear(buffer) + file_list = zip(file_list, file_sizes) + msg = 'Found %s logs.' %len(file_list) + + print_line(msg, buffer, display=True) + for file, size in file_list: + separator = column_len and '.'*(column_len - len(file)) + prnt(buffer, '%s %s %s' %(strip_home(file), separator, size)) + if file_list: + print_line(msg, buffer) + return WEECHAT_RC_OK + + +### Completion ### +def completion_log_files(data, completion_item, buffer, completion): + #debug('completion: %s' %', '.join((data, completion_item, buffer, completion))) + global home_dir + l = len(home_dir) + completion_list_add = weechat.hook_completion_list_add + WEECHAT_LIST_POS_END = weechat.WEECHAT_LIST_POS_END + for log in dir_list(home_dir): + completion_list_add(completion, log[l:], 0, WEECHAT_LIST_POS_END) + return WEECHAT_RC_OK + +def completion_grep_args(data, completion_item, buffer, completion): + for arg in ('count', 'all', 'matchcase', 'hilight', 'exact', 'head', 'tail', 'number', 'buffer', + 'after-context', 'before-context', 'context', 'invert', 'only-match'): + weechat.hook_completion_list_add(completion, '--' + arg, 0, weechat.WEECHAT_LIST_POS_SORT) + for tmpl in templates: + weechat.hook_completion_list_add(completion, '%{' + tmpl, 0, weechat.WEECHAT_LIST_POS_SORT) + return WEECHAT_RC_OK + + +### Templates ### +# template placeholder +_tmplRe = re.compile(r'%\{(\w+.*?)(?:\}|$)') +# will match 999.999.999.999 but I don't care +ipAddress = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' +domain = r'[\w-]{2,}(?:\.[\w-]{2,})*\.[a-z]{2,}' +url = r'\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?' % (domain, ipAddress) + +def make_url_regexp(args): + #debug('make url: %s', args) + if args: + words = r'(?:%s)' %'|'.join(map(re.escape, args.split())) + return r'(?:\w+://|www\.)[^\s]*%s[^\s]*(?:/[^\])>\s]*)?' %words + else: + return url + +def make_simple_regexp(pattern): + s = '' + for c in pattern: + if c == '*': + s += '.*' + elif c == '?': + s += '.' + else: + s += re.escape(c) + return s + +templates = { + 'ip': ipAddress, + 'url': make_url_regexp, + 'escape': lambda s: re.escape(s), + 'simple': make_simple_regexp, + 'domain': domain, + } + +### Main ### +def delete_bytecode(): + global script_path + bytecode = path.join(script_path, SCRIPT_NAME + '.pyc') + if path.isfile(bytecode): + os.remove(bytecode) + return WEECHAT_RC_OK + +if __name__ == '__main__' and import_ok and \ + weechat.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, \ + SCRIPT_DESC, 'delete_bytecode', ''): + home_dir = get_home() + + # for import ourselves + global script_path + script_path = path.dirname(__file__) + sys.path.append(script_path) + delete_bytecode() + + # check python version + import sys + global bytecode + if sys.version_info > (2, 6): + bytecode = 'B' + else: + bytecode = '' + + + weechat.hook_command(SCRIPT_COMMAND, cmd_grep.__doc__, + "[log | buffer | stop] [-a|--all] [-b|--buffer] [-c|--count] [-m|--matchcase] " + "[-H|--hilight] [-o|--only-match] [-i|-v|--invert] [(-h|--head)|(-t|--tail) [-n|--number ]] " + "[-A|--after-context ] [-B|--before-context ] [-C|--context ] ", +# help +""" + log : Search in one log that matches in the logger path. + Use '*' and '?' as wildcards. + buffer : Search in buffer , if there's no buffer with it will + try to search for a log file. + stop: Stops a currently running search. + -a --all: Search in all open buffers. + If used with 'log ' search in all logs that matches . + -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. + -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. + -t --tail: Print the last 10 matching lines. + -h --head: Print the first 10 matching lines. +-n --number : Overrides default number of lines for --tail or --head. +-A --after-context : Shows lines of trailing context after matching lines. +-B --before-context : Shows lines of leading context before matching lines. +-C --context : Same as using both --after-context and --before-context simultaneously. + : Expression to search. + +Grep buffer: + Input line accepts most arguments of /grep, it'll repeat last search using the new + arguments provided. You can't search in different logs from the buffer's input. + Boolean arguments like --count, --tail, --head, --hilight, ... are toggleable + +Python regular expression syntax: + See http://docs.python.org/lib/re-syntax.html + +Grep Templates: + %{url [text]}: Matches anything like an url, or an url with text. + %{ip}: Matches anything that looks like an ip. + %{domain}: Matches anything like a domain. + %{escape text}: Escapes text in pattern. + %{simple pattern}: Converts a pattern with '*' and '?' wildcards into a regexp. + +Examples: + Search for urls with the word 'weechat' said by 'nick' + /grep nick\\t.*%{url weechat} + Search for '*.*' string + /grep %{escape *.*} +""", + # completion template + "buffer %(buffers_names) %(grep_arguments)|%*" + "||log %(grep_log_files) %(grep_arguments)|%*" + "||stop" + "||%(grep_arguments)|%*", + 'cmd_grep' ,'') + weechat.hook_command('logs', cmd_logs.__doc__, "[-s|--size] []", + "-s --size: Sort logs by size.\n" + " : Only show logs that match . Use '*' and '?' as wildcards.", '--size', 'cmd_logs', '') + + weechat.hook_completion('grep_log_files', "list of log files", + 'completion_log_files', '') + weechat.hook_completion('grep_arguments', "list of arguments", + 'completion_grep_args', '') + + # settings + for opt, val in settings.iteritems(): + if not weechat.config_is_set_plugin(opt): + weechat.config_set_plugin(opt, val) + + # colors + color_date = weechat.color('brown') + color_info = weechat.color('cyan') + color_hilight = weechat.color('lightred') + color_reset = weechat.color('reset') + color_title = weechat.color('yellow') + color_summary = weechat.color('lightcyan') + color_delimiter = weechat.color('chat_delimiters') + color_script_nick = weechat.color('chat_nick') + + # pretty [grep] + script_nick = '%s[%s%s%s]%s' %(color_delimiter, color_script_nick, SCRIPT_NAME, color_delimiter, + color_reset) + script_nick_nocolor = '[%s]' %SCRIPT_NAME + # paragraph separator when using context options + context_sep = '%s\t%s--' %(script_nick, color_info) + + # ------------------------------------------------------------------------- + # Debug + + if weechat.config_get_plugin('debug'): + try: + # custom debug module I use, allows me to inspect script's objects. + import pybuffer + debug = pybuffer.debugBuffer(globals(), '%s_debug' % SCRIPT_NAME) + except: + def debug(s, *args): + if not isinstance(s, basestring): + s = str(s) + if args: + s = s %args + prnt('', '%s\t%s' %(script_nick, s)) + else: + def debug(*args): + pass + +# vim:set shiftwidth=4 tabstop=4 softtabstop=4 expandtab textwidth=100: diff --git a/.weechat/python/otr.py b/.weechat/python/otr.py new file mode 100644 index 0000000..404e96a --- /dev/null +++ b/.weechat/python/otr.py @@ -0,0 +1,2062 @@ +# -*- coding: utf-8 -*- +# otr - WeeChat script for Off-the-Record IRC messaging +# +# DISCLAIMER: To the best of my knowledge this script securely provides OTR +# messaging in WeeChat, but I offer no guarantee. Please report any security +# holes you find. +# +# Copyright (c) 2012-2015 Matthew M. Boedicker +# Nils Görs +# Daniel "koolfy" Faucon +# Felix Eckhofer +# +# Report issues at https://github.com/mmb/weechat-otr +# +# 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 . + +from __future__ import unicode_literals + +import collections +import glob +import io +import os +import platform +import re +import traceback +import shlex +import shutil +import sys + +class PythonVersion2(object): + """Python 2 version of code that must differ between Python 2 and 3.""" + + def __init__(self): + import cgi + self.cgi = cgi + + import HTMLParser + self.html_parser = HTMLParser + self.html_parser_init_kwargs = {} + + import htmlentitydefs + self.html_entities = htmlentitydefs + + def html_escape(self, strng): + """Escape HTML characters in a string.""" + return self.cgi.escape(strng) + + def unicode(self, *args, **kwargs): + """Return the Unicode version of a string.""" + return unicode(*args, **kwargs) + + def unichr(self, *args, **kwargs): + """Return the one character string of a Unicode character number.""" + return unichr(*args, **kwargs) + + def to_unicode(self, strng): + """Convert a utf-8 encoded string to a Unicode.""" + if isinstance(strng, unicode): + return strng + else: + return strng.decode('utf-8', 'replace') + + def to_str(self, strng): + """Convert a Unicode to a utf-8 encoded string.""" + return strng.encode('utf-8', 'replace') + +class PythonVersion3(object): + """Python 3 version of code that must differ between Python 2 and 3.""" + + def __init__(self, minor): + self.minor = minor + + import html + self.html = html + + import html.parser + self.html_parser = html.parser + if self.minor >= 4: + self.html_parser_init_kwargs = { 'convert_charrefs' : True } + else: + self.html_parser_init_kwargs = {} + + import html.entities + self.html_entities = html.entities + + def html_escape(self, strng): + """Escape HTML characters in a string.""" + return self.html.escape(strng, quote=False) + + def unicode(self, *args, **kwargs): + """Return the Unicode version of a string.""" + return str(*args, **kwargs) + + def unichr(self, *args, **kwargs): + """Return the one character string of a Unicode character number.""" + return chr(*args, **kwargs) + + def to_unicode(self, strng): + """Convert a utf-8 encoded string to unicode.""" + if isinstance(strng, bytes): + return strng.decode('utf-8', 'replace') + else: + return strng + + def to_str(self, strng): + """Convert a Unicode to a utf-8 encoded string.""" + return strng + +if sys.version_info.major >= 3: + PYVER = PythonVersion3(sys.version_info.minor) +else: + PYVER = PythonVersion2() + +import weechat + +import potr + +SCRIPT_NAME = 'otr' +SCRIPT_DESC = 'Off-the-Record messaging for IRC' +SCRIPT_HELP = """{description} + +Quick start: + +Add an OTR item to the status bar by adding '[otr]' to the config setting +weechat.bar.status.items. This will show you whether your current conversation +is encrypted, authenticated and logged. /set otr.* for OTR status bar +customization options. + +Start a private conversation with a friend who has OTR: /query yourpeer hi + +In the private chat buffer: /otr start + +If you have not authenticated your peer yet, follow the instructions for +authentication. + +You can, at any time, see the current OTR session status and fingerprints with: +/otr status + +View OTR policies for your peer: /otr policy + +View default OTR policies: /otr policy default + +Start/Stop log recording for the current OTR session: /otr log [start|stop] +This will be reverted back to the previous log setting at the end of the session. + +To refresh the OTR session: /otr refresh + +To end your private conversation: /otr finish + +This script supports only OTR protocol version 2. +""".format(description=SCRIPT_DESC) + +SCRIPT_AUTHOR = 'Matthew M. Boedicker' +SCRIPT_LICENCE = 'GPL3' +SCRIPT_VERSION = '1.8.0' + +OTR_DIR_NAME = 'otr' + +OTR_QUERY_RE = re.compile(r'\?OTR(\?|\??v[a-z\d]*\?)') + +POLICIES = { + 'allow_v2' : 'allow OTR protocol version 2, effectively enable OTR ' + 'since v2 is the only supported version', + 'require_encryption' : 'refuse to send unencrypted messages when OTR is ' + 'enabled', + 'log' : 'enable logging of OTR conversations', + 'send_tag' : 'advertise your OTR capability using the whitespace tag', + 'html_escape' : 'escape HTML special characters in outbound messages', + 'html_filter' : 'filter HTML in incoming messages', + } + +READ_ONLY_POLICIES = { + 'allow_v1' : False, + } + +ACTION_PREFIX = '/me ' +IRC_ACTION_RE = re.compile('^\x01ACTION (?P.*)\x01$') +PLAIN_ACTION_RE = re.compile('^'+ACTION_PREFIX+'(?P.*)$') + +IRC_SANITIZE_TABLE = dict((ord(char), None) for char in '\n\r\x00') + +global otr_debug_buffer +otr_debug_buffer = None + +# Patch potr.proto.TaggedPlaintext to not end plaintext tags in a space. +# +# When POTR adds OTR tags to plaintext it puts them at the end of the message. +# The tags end in a space which gets stripped off by WeeChat because it +# strips trailing spaces from commands. This causes OTR initiation to fail so +# the following code adds an extra tab at the end of the plaintext tags if +# they end in a space. +# +# The patched version also skips OTR tagging for CTCP messages because it +# breaks the CTCP format. +def patched__bytes__(self): + # Do not tag CTCP messages. + if self.msg.startswith(b'\x01') and \ + self.msg.endswith(b'\x01'): + return self.msg + + data = self.msg + potr.proto.MESSAGE_TAG_BASE + for v in self.versions: + data += potr.proto.MESSAGE_TAGS[v] + if data.endswith(b' '): + data += b'\t' + return data + +potr.proto.TaggedPlaintext.__bytes__ = patched__bytes__ + +def command(buf, command_str): + """Wrap weechat.command() with utf-8 encode.""" + debug(command_str) + weechat.command(buf, PYVER.to_str(command_str)) + +def privmsg(server, nick, message): + """Send a private message to a nick.""" + for line in message.splitlines(): + command('', '/quote -server {server} PRIVMSG {nick} :{line}'.format( + server=irc_sanitize(server), + nick=irc_sanitize(nick), + line=irc_sanitize(line))) + +def build_privmsg_in(fromm, target, msg): + """Build inbound IRC PRIVMSG command.""" + return ':{user} PRIVMSG {target} :{msg}'.format( + user=irc_sanitize(fromm), + target=irc_sanitize(target), + msg=irc_sanitize(msg)) + +def build_privmsgs_in(fromm, target, msg, prefix=''): + """Build an inbound IRC PRIVMSG command for each line in msg. + If prefix is supplied, prefix each line of msg with it.""" + cmd = [] + for line in msg.splitlines(): + cmd.append(build_privmsg_in(fromm, target, prefix+line)) + return '\r\n'.join(cmd) + +def build_privmsg_out(target, msg): + """Build outbound IRC PRIVMSG command(s).""" + cmd = [] + for line in msg.splitlines(): + cmd.append('PRIVMSG {target} :{line}'.format( + target=irc_sanitize(target), + line=irc_sanitize(line))) + return '\r\n'.join(cmd) + +def irc_sanitize(msg): + """Remove NUL, CR and LF characters from msg. + The (utf-8 encoded version of a) string returned from this function + should be safe to use as an argument in an irc command.""" + return PYVER.unicode(msg).translate(IRC_SANITIZE_TABLE) + +def prnt(buf, message): + """Wrap weechat.prnt() with utf-8 encode.""" + weechat.prnt(buf, PYVER.to_str(message)) + +def print_buffer(buf, message, level='info'): + """Print message to buf with prefix, + using color according to level.""" + prnt(buf, '{prefix}\t{msg}'.format( + prefix=get_prefix(), + msg=colorize(message, 'buffer.{}'.format(level)))) + +def get_prefix(): + """Returns configured message prefix.""" + return weechat.string_eval_expression( + config_string('look.prefix'), + {}, {}, {}) + +def debug(msg): + """Send a debug message to the OTR debug buffer.""" + debug_option = weechat.config_get(config_prefix('general.debug')) + global otr_debug_buffer + + if weechat.config_boolean(debug_option): + if not otr_debug_buffer: + otr_debug_buffer = weechat.buffer_new("OTR Debug", "", "", + "debug_buffer_close_cb", "") + weechat.buffer_set(otr_debug_buffer, 'title', 'OTR Debug') + weechat.buffer_set(otr_debug_buffer, 'localvar_set_no_log', '1') + prnt(otr_debug_buffer, ('{script} debug\t{text}'.format( + script=SCRIPT_NAME, + text=PYVER.unicode(msg) + ))) + +def debug_buffer_close_cb(data, buf): + """Set the OTR debug buffer to None.""" + global otr_debug_buffer + otr_debug_buffer = None + return weechat.WEECHAT_RC_OK + +def current_user(server_name): + """Get the nick and server of the current user on a server.""" + return irc_user(info_get('irc_nick', server_name), server_name) + +def irc_user(nick, server): + """Build an IRC user string from a nick and server.""" + return '{nick}@{server}'.format( + nick=nick.lower(), + server=server) + +def isupport_value(server, feature): + """Get the value of an IRC server feature.""" + args = '{server},{feature}'.format(server=server, feature=feature) + return info_get('irc_server_isupport_value', args) + +def is_a_channel(channel, server): + """Return true if a string has an IRC channel prefix.""" + prefixes = \ + tuple(isupport_value(server, 'CHANTYPES')) + \ + tuple(isupport_value(server, 'STATUSMSG')) + + # If the server returns nothing for CHANTYPES and STATUSMSG use + # default prefixes. + if not prefixes: + prefixes = ('#', '&', '+', '!', '@') + + return channel.startswith(prefixes) + +# Exception class for PRIVMSG parsing exceptions. +class PrivmsgParseException(Exception): + pass + +def parse_irc_privmsg(message, server): + """Parse an IRC PRIVMSG command and return a dictionary. + + Either the to_channel key or the to_nick key will be set depending on + whether the message is to a nick or a channel. The other will be None. + + Example input: + + :nick!user@host PRIVMSG #weechat :message here + + Output: + + {'from': 'nick!user@host', + 'from_nick': 'nick', + 'to': '#weechat', + 'to_channel': '#weechat', + 'to_nick': None, + 'text': 'message here'} + """ + + weechat_result = weechat.info_get_hashtable( + 'irc_message_parse', dict(message=message)) + + if weechat_result['command'].upper() == 'PRIVMSG': + target, text = PYVER.to_unicode( + weechat_result['arguments']).split(' ', 1) + if text.startswith(':'): + text = text[1:] + + result = { + 'from': PYVER.to_unicode(weechat_result['host']), + 'to' : target, + 'text': text, + } + + if weechat_result['host']: + result['from_nick'] = PYVER.to_unicode(weechat_result['nick']) + else: + result['from_nick'] = '' + + if is_a_channel(target, server): + result['to_channel'] = target + result['to_nick'] = None + else: + result['to_channel'] = None + result['to_nick'] = target + + return result + else: + raise PrivmsgParseException(message) + +def has_otr_end(msg): + """Return True if the message is the end of an OTR message.""" + return msg.endswith('.') or msg.endswith(',') + +def first_instance(objs, klass): + """Return the first object in the list that is an instance of a class.""" + for obj in objs: + if isinstance(obj, klass): + return obj + +def config_prefix(option): + """Add the config prefix to an option and return the full option name.""" + return '{script}.{option}'.format( + script=SCRIPT_NAME, + option=option) + +def config_color(option): + """Get the color of a color config option.""" + return weechat.color(weechat.config_color(weechat.config_get( + config_prefix('color.{}'.format(option))))) + +def config_string(option): + """Get the string value of a config option with utf-8 decode.""" + return PYVER.to_unicode(weechat.config_string( + weechat.config_get(config_prefix(option)))) + +def buffer_get_string(buf, prop): + """Wrap weechat.buffer_get_string() with utf-8 encode/decode.""" + if buf is not None: + encoded_buf = PYVER.to_str(buf) + else: + encoded_buf = None + + return PYVER.to_unicode(weechat.buffer_get_string( + encoded_buf, PYVER.to_str(prop))) + +def buffer_is_private(buf): + """Return True if a buffer is private.""" + return buffer_get_string(buf, 'localvar_type') == 'private' + +def info_get(info_name, arguments): + """Wrap weechat.info_get() with utf-8 encode/decode.""" + return PYVER.to_unicode(weechat.info_get( + PYVER.to_str(info_name), PYVER.to_str(arguments))) + +def msg_irc_from_plain(msg): + """Transform a plain-text message to irc format. + This will replace lines that start with /me with the respective + irc command.""" + return PLAIN_ACTION_RE.sub('\x01ACTION \g\x01', msg) + +def msg_plain_from_irc(msg): + """Transform an irc message to plain-text. + Any ACTION found will be rewritten as /me .""" + return IRC_ACTION_RE.sub(ACTION_PREFIX + r'\g', msg) + +def default_peer_args(args, buf): + """Get the nick and server of a remote peer from command arguments or + a buffer. + + args is the [nick, server] slice of arguments from a command. + If these are present, return them. If args is empty and the buffer buf + is private, return the remote nick and server of buf.""" + result = None, None + + if len(args) == 2: + result = tuple(args) + else: + if buffer_is_private(buf): + result = ( + buffer_get_string(buf, 'localvar_channel'), + buffer_get_string(buf, 'localvar_server')) + + return result + +def format_default_policies(): + """Return current default policies formatted as a string for the user.""" + buf = io.StringIO() + + buf.write('Current default OTR policies:\n') + + for policy, desc in sorted(POLICIES.items()): + buf.write(' {policy} ({desc}) : {value}\n'.format( + policy=policy, + desc=desc, + value=config_string('policy.default.{}'.format(policy)))) + + buf.write('Change default policies with: /otr policy default NAME on|off') + + return buf.getvalue() + +def to_bytes(strng): + """Convert a python str or unicode to bytes.""" + return strng.encode('utf-8', 'replace') + +def colorize(msg, color): + """Colorize each line of msg using color.""" + result = [] + colorstr = config_color(color) + + for line in msg.splitlines(): + result.append('{color}{msg}'.format( + color=colorstr, + msg=line)) + + return '\r\n'.join(result) + +def accounts(): + """Return a list of all IrcOtrAccounts sorted by name.""" + result = [] + for key_path in glob.iglob(os.path.join(OTR_DIR, '*.key3')): + key_name, _ = os.path.splitext(os.path.basename(key_path)) + result.append(ACCOUNTS[key_name]) + + return sorted(result, key=lambda account: account.name) + +def show_account_fingerprints(): + """Print all account names and their fingerprints to the core buffer.""" + table_formatter = TableFormatter() + for account in accounts(): + table_formatter.add_row([ + account.name, + str(account.getPrivkey())]) + print_buffer('', table_formatter.format()) + +def show_peer_fingerprints(grep=None): + """Print peer names and their fingerprints to the core buffer. + + If grep is passed in, show all peer names containing that substring.""" + trust_descs = { + '' : 'unverified', + 'smp' : 'SMP verified', + 'verified' : 'verified', + } + + table_formatter = TableFormatter() + for account in accounts(): + for peer, peer_data in sorted(account.trusts.items()): + for fingerprint, trust in sorted(peer_data.items()): + if grep is None or grep in peer: + table_formatter.add_row([ + peer, + account.name, + potr.human_hash(fingerprint), + trust_descs[trust], + ]) + print_buffer('', table_formatter.format()) + +def private_key_file_path(account_name): + """Return the private key file path for an account.""" + return os.path.join(OTR_DIR, '{}.key3'.format(account_name)) + +def read_private_key(key_file_path): + """Return the private key in a private key file.""" + debug(('read private key', key_file_path)) + + with open(key_file_path, 'rb') as key_file: + return potr.crypt.PK.parsePrivateKey(key_file.read())[0] + +class AccountDict(collections.defaultdict): + """Dictionary that adds missing keys as IrcOtrAccount instances.""" + + def __missing__(self, key): + debug(('add account', key)) + self[key] = IrcOtrAccount(key) + + return self[key] + +class Assembler(object): + """Reassemble fragmented OTR messages. + + This does not deal with OTR fragmentation, which is handled by potr, but + fragmentation of received OTR messages that are too large for IRC. + """ + def __init__(self): + self.clear() + + def add(self, data): + """Add data to the buffer.""" + self.value += data + + def clear(self): + """Empty the buffer.""" + self.value = '' + + def is_done(self): + """Return True if the buffer is a complete message.""" + return self.is_query() or \ + not to_bytes(self.value).startswith(potr.proto.OTRTAG) or \ + has_otr_end(self.value) + + def get(self): + """Return the current value of the buffer and empty it.""" + result = self.value + self.clear() + + return result + + def is_query(self): + """Return true if the buffer is an OTR query.""" + return OTR_QUERY_RE.search(self.value) + +class IrcContext(potr.context.Context): + """Context class for OTR over IRC.""" + + def __init__(self, account, peername): + super(IrcContext, self).__init__(account, peername) + + self.peer_nick, self.peer_server = peername.split('@', 1) + self.in_assembler = Assembler() + self.in_otr_message = False + self.in_smp = False + self.smp_question = False + + def policy_config_option(self, policy): + """Get the option name of a policy option for this context.""" + return config_prefix('.'.join([ + 'policy', self.peer_server, self.user.nick, self.peer_nick, + policy.lower()])) + + def getPolicy(self, key): + """Get the value of a policy option for this context.""" + key_lower = key.lower() + + if key_lower in READ_ONLY_POLICIES: + result = READ_ONLY_POLICIES[key_lower] + elif key_lower == 'send_tag' and self.no_send_tag(): + result = False + else: + option = weechat.config_get( + PYVER.to_str(self.policy_config_option(key))) + + if option == '': + option = weechat.config_get( + PYVER.to_str(self.user.policy_config_option(key))) + + if option == '': + option = weechat.config_get(config_prefix('.'.join( + ['policy', self.peer_server, key_lower]))) + + if option == '': + option = weechat.config_get( + config_prefix('policy.default.{}'.format(key_lower))) + + result = bool(weechat.config_boolean(option)) + + debug(('getPolicy', key, result)) + + return result + + def inject(self, msg, appdata=None): + """Send a message to the remote peer.""" + if isinstance(msg, potr.proto.OTRMessage): + msg = PYVER.unicode(msg) + else: + msg = PYVER.to_unicode(msg) + + debug(('inject', msg, 'len {}'.format(len(msg)), appdata)) + + privmsg(self.peer_server, self.peer_nick, msg) + + def setState(self, newstate): + """Handle state transition.""" + debug(('state', self.state, newstate)) + + if self.is_encrypted(): + if newstate == potr.context.STATE_ENCRYPTED: + self.print_buffer( + 'Private conversation has been refreshed.', 'success') + elif newstate == potr.context.STATE_FINISHED: + self.print_buffer( + '{peer} has ended the private conversation. You should do ' + 'the same:\n/otr finish'.format(peer=self.peer_nick)) + elif newstate == potr.context.STATE_ENCRYPTED: + # unencrypted => encrypted + trust = self.getCurrentTrust() + + # Disable logging before any proof of OTR activity is generated. + # This is necessary when the session is started automatically, and + # not by /otr start. + if not self.getPolicy('log'): + self.previous_log_level = self.disable_logging() + else: + self.previous_log_level = self.get_log_level() + if self.is_logged(): + self.hint( + 'You have enabled the recording to disk of OTR ' + 'conversations. By doing this you are potentially ' + 'putting yourself and your correspondent in danger. ' + 'Please consider disabling this policy with ' + '"/otr policy default log off". To disable logging ' + 'for this OTR session, use "/otr log stop"') + + if trust is None: + fpr = str(self.getCurrentKey()) + self.print_buffer('New fingerprint: {}'.format(fpr), 'warning') + self.setCurrentTrust('') + + if bool(trust): + self.print_buffer( + 'Authenticated secured OTR conversation started.', + 'success') + else: + self.print_buffer( + 'Unauthenticated secured OTR conversation started.', + 'warning') + self.hint(self.verify_instructions()) + + if self.state != potr.context.STATE_PLAINTEXT and \ + newstate == potr.context.STATE_PLAINTEXT: + self.print_buffer('Private conversation ended.') + + # If we altered the logging value, restore it. + if self.previous_log_level is not None: + self.restore_logging(self.previous_log_level) + + super(IrcContext, self).setState(newstate) + + def maxMessageSize(self, appdata=None): + """Return the max message size for this context.""" + # remove 'PRIVMSG :' from max message size + result = self.user.maxMessageSize - 10 - len(self.peer_nick) + debug('max message size {}'.format(result)) + + return result + + def buffer(self): + """Get the buffer for this context.""" + return info_get( + 'irc_buffer', '{server},{nick}'.format( + server=self.peer_server, + nick=self.peer_nick + )) + + def print_buffer(self, msg, level='info'): + """Print a message to the buffer for this context. + level is used to colorize the message.""" + buf = self.buffer() + + # add [nick] prefix if we have only a server buffer for the query + if self.peer_nick and not buffer_is_private(buf): + msg = '[{nick}] {msg}'.format( + nick=self.peer_nick, + msg=msg) + + print_buffer(buf, msg, level) + + def hint(self, msg): + """Print a message to the buffer but only when hints are enabled.""" + hints_option = weechat.config_get(config_prefix('general.hints')) + + if weechat.config_boolean(hints_option): + self.print_buffer(msg, 'hint') + + def smp_finish(self, message=False, level='info'): + """Reset SMP state and send a message to the user.""" + self.in_smp = False + self.smp_question = False + + self.user.saveTrusts() + if message: + self.print_buffer(message, level) + + def handle_tlvs(self, tlvs): + """Handle SMP states.""" + if tlvs: + smp1q = first_instance(tlvs, potr.proto.SMP1QTLV) + smp3 = first_instance(tlvs, potr.proto.SMP3TLV) + smp4 = first_instance(tlvs, potr.proto.SMP4TLV) + + if first_instance(tlvs, potr.proto.SMPABORTTLV): + debug('SMP aborted by peer') + self.smp_finish('SMP aborted by peer.', 'warning') + elif self.in_smp and not self.smpIsValid(): + debug('SMP aborted') + self.smp_finish('SMP aborted.', 'error') + elif first_instance(tlvs, potr.proto.SMP1TLV): + debug('SMP1') + self.in_smp = True + + self.print_buffer( + """Peer has requested SMP verification. +Respond with: /otr smp respond """) + elif smp1q: + debug(('SMP1Q', smp1q.msg)) + self.in_smp = True + self.smp_question = True + + self.print_buffer( + """Peer has requested SMP verification: {msg} +Respond with: /otr smp respond """.format( + msg=PYVER.to_unicode(smp1q.msg))) + elif first_instance(tlvs, potr.proto.SMP2TLV): + if not self.in_smp: + debug('Received unexpected SMP2') + self.smp_finish() + else: + debug('SMP2') + self.print_buffer('SMP progressing.') + elif smp3 or smp4: + if smp3: + debug('SMP3') + elif smp4: + debug('SMP4') + + if self.smpIsSuccess(): + + if self.smp_question: + self.smp_finish('SMP verification succeeded.', + 'success') + if not self.is_verified: + self.print_buffer( + """You may want to authenticate your peer by asking your own question: +/otr smp ask <'question'> 'secret'""") + + else: + self.smp_finish('SMP verification succeeded.', + 'success') + + else: + self.smp_finish('SMP verification failed.', 'error') + + def verify_instructions(self): + """Generate verification instructions for user.""" + return """You can verify that this contact is who they claim to be in one of the following ways: + +1) Verify each other's fingerprints using a secure channel: + Your fingerprint : {your_fp} + {peer}'s fingerprint : {peer_fp} + then use the command: /otr trust {peer_nick} {peer_server} + +2) SMP pre-shared secret that you both know: + /otr smp ask {peer_nick} {peer_server} 'secret' + +3) SMP pre-shared secret that you both know with a question: + /otr smp ask {peer_nick} {peer_server} <'question'> 'secret' + +Note: You can safely omit specifying the peer and server when + executing these commands from the appropriate conversation + buffer +""".format( + your_fp=self.user.getPrivkey(), + peer=self.peer, + peer_nick=self.peer_nick, + peer_server=self.peer_server, + peer_fp=potr.human_hash( + self.crypto.theirPubkey.cfingerprint()), + ) + + def is_encrypted(self): + """Return True if the conversation with this context's peer is + currently encrypted.""" + return self.state == potr.context.STATE_ENCRYPTED + + def is_verified(self): + """Return True if this context's peer is verified.""" + return bool(self.getCurrentTrust()) + + def format_policies(self): + """Return current policies for this context formatted as a string for + the user.""" + buf = io.StringIO() + + buf.write('Current OTR policies for {peer}:\n'.format( + peer=self.peer)) + + for policy, desc in sorted(POLICIES.items()): + buf.write(' {policy} ({desc}) : {value}\n'.format( + policy=policy, + desc=desc, + value='on' if self.getPolicy(policy) else 'off')) + + buf.write('Change policies with: /otr policy NAME on|off') + + return buf.getvalue() + + def is_logged(self): + """Return True if conversations with this context's peer are currently + being logged to disk.""" + infolist = weechat.infolist_get('logger_buffer', '', '') + + buf = self.buffer() + + result = False + + while weechat.infolist_next(infolist): + if weechat.infolist_pointer(infolist, 'buffer') == buf: + result = bool(weechat.infolist_integer(infolist, 'log_enabled')) + break + + weechat.infolist_free(infolist) + + return result + + def get_log_level(self): + """Return the current logging level for this context's peer + or -1 if the buffer uses the default log level of weechat.""" + infolist = weechat.infolist_get('logger_buffer', '', '') + + buf = self.buffer() + + if not weechat.config_get(self.get_logger_option_name(buf)): + result = -1 + else: + result = 0 + + while weechat.infolist_next(infolist): + if weechat.infolist_pointer(infolist, 'buffer') == buf: + result = weechat.infolist_integer(infolist, 'log_level') + break + + weechat.infolist_free(infolist) + + return result + + def get_logger_option_name(self, buf): + """Returns the logger config option for the specified buffer.""" + name = buffer_get_string(buf, 'name') + plugin = buffer_get_string(buf, 'plugin') + + return 'logger.level.{plugin}.{name}'.format( + plugin=plugin, name=name) + + def disable_logging(self): + """Return the previous logger level and set the buffer logger level + to 0. If it was already 0, return None.""" + # If previous_log_level has not been previously set, return the level + # we detect now. + if not hasattr(self, 'previous_log_level'): + previous_log_level = self.get_log_level() + + if self.is_logged(): + weechat.command(self.buffer(), '/mute logger disable') + self.print_buffer( + 'Logs have been temporarily disabled for the session. They will be restored upon finishing the OTR session.') + + return previous_log_level + + # If previous_log_level was already set, it means we already altered it + # and that we just detected an already modified logging level. + # Return the pre-existing value so it doesn't get lost, and we can + # restore it later. + else: + return self.previous_log_level + + def restore_logging(self, previous_log_level): + """Restore the log level of the buffer.""" + buf = self.buffer() + + if (previous_log_level >= 0) and (previous_log_level < 10): + self.print_buffer( + 'Restoring buffer logging value to: {}'.format( + previous_log_level), 'warning') + weechat.command(buf, '/mute logger set {}'.format( + previous_log_level)) + + if previous_log_level == -1: + logger_option_name = self.get_logger_option_name(buf) + self.print_buffer( + 'Restoring buffer logging value to default', 'warning') + weechat.command(buf, '/mute unset {}'.format( + logger_option_name)) + + del self.previous_log_level + + def msg_convert_in(self, msg): + """Transform incoming OTR message to IRC format. + This includes stripping html, converting plain-text ACTIONs + and character encoding conversion. + Only character encoding is changed if context is unencrypted.""" + msg = PYVER.to_unicode(msg) + + if not self.is_encrypted(): + return msg + + if self.getPolicy('html_filter'): + try: + msg = IrcHTMLParser.parse(msg) + except PYVER.html_parser.HTMLParseError: + pass + + return msg_irc_from_plain(msg) + + def msg_convert_out(self, msg): + """Convert an outgoing IRC message to be sent over OTR. + This includes escaping html, converting ACTIONs to plain-text + and character encoding conversion + Only character encoding is changed if context is unencrypted.""" + if self.is_encrypted(): + msg = msg_plain_from_irc(msg) + + if self.getPolicy('html_escape'): + msg = PYVER.html_escape(msg) + + # potr expects bytes to be returned + return to_bytes(msg) + + def no_send_tag(self): + """Skip OTR whitespace tagging to bots and services. + + Any nicks matching the otr.general.no_send_tag_regex config setting + will not be tagged. + """ + no_send_tag_regex = config_string('general.no_send_tag_regex') + debug(('no_send_tag', no_send_tag_regex, self.peer_nick)) + if no_send_tag_regex: + return re.match(no_send_tag_regex, self.peer_nick, re.IGNORECASE) + + def __repr__(self): + return PYVER.to_str(('<{} {:x} peer_nick={c.peer_nick} ' + 'peer_server={c.peer_server}>').format( + self.__class__.__name__, id(self), c=self)) + +class IrcOtrAccount(potr.context.Account): + """Account class for OTR over IRC.""" + + contextclass = IrcContext + + PROTOCOL = 'irc' + MAX_MSG_SIZE = 415 + + def __init__(self, name): + super(IrcOtrAccount, self).__init__( + name, IrcOtrAccount.PROTOCOL, IrcOtrAccount.MAX_MSG_SIZE) + + self.nick, self.server = self.name.split('@', 1) + + # IRC messages cannot have newlines, OTR query and "no plugin" text + # need to be one message + self.defaultQuery = self.defaultQuery.replace("\n", ' ') + + self.key_file_path = private_key_file_path(name) + self.fpr_file_path = os.path.join(OTR_DIR, '{}.fpr'.format(name)) + + self.load_trusts() + + def load_trusts(self): + """Load trust data from the fingerprint file.""" + if os.path.exists(self.fpr_file_path): + with open(self.fpr_file_path) as fpr_file: + for line in fpr_file: + debug(('load trust check', line)) + + context, account, protocol, fpr, trust = \ + PYVER.to_unicode(line[:-1]).split('\t') + + if account == self.name and \ + protocol == IrcOtrAccount.PROTOCOL: + debug(('set trust', context, fpr, trust)) + self.setTrust(context, fpr, trust) + + def loadPrivkey(self): + """Load key file. + + If no key file exists, load the default key. If there is no default + key, a new key will be generated automatically by potr.""" + debug(('load private key', self.key_file_path)) + + if os.path.exists(self.key_file_path): + return read_private_key(self.key_file_path) + else: + default_key = config_string('general.defaultkey') + if default_key: + default_key_path = private_key_file_path(default_key) + + if os.path.exists(default_key_path): + shutil.copyfile(default_key_path, self.key_file_path) + return read_private_key(self.key_file_path) + + def savePrivkey(self): + """Save key file.""" + debug(('save private key', self.key_file_path)) + + with open(self.key_file_path, 'wb') as key_file: + key_file.write(self.getPrivkey().serializePrivateKey()) + + def saveTrusts(self): + """Save trusts.""" + with open(self.fpr_file_path, 'w') as fpr_file: + for uid, trusts in self.trusts.items(): + for fpr, trust in trusts.items(): + debug(('trust write', uid, self.name, + IrcOtrAccount.PROTOCOL, fpr, trust)) + fpr_file.write(PYVER.to_str('\t'.join( + (uid, self.name, IrcOtrAccount.PROTOCOL, fpr, + trust)))) + fpr_file.write('\n') + + def end_all_private(self): + """End all currently encrypted conversations.""" + for context in self.ctxs.values(): + if context.is_encrypted(): + context.disconnect() + + def policy_config_option(self, policy): + """Get the option name of a policy option for this account.""" + return config_prefix('.'.join([ + 'policy', self.server, self.nick, policy.lower()])) + +class IrcHTMLParser(PYVER.html_parser.HTMLParser): + """A simple HTML parser that throws away anything but newlines and links""" + + @staticmethod + def parse(data): + """Create a temporary IrcHTMLParser and parse a single string""" + parser = IrcHTMLParser(**PYVER.html_parser_init_kwargs) + parser.feed(data) + parser.close() + return parser.result + + def reset(self): + """Forget all state, called from __init__""" + PYVER.html_parser.HTMLParser.reset(self) + self.result = '' + self.linktarget = '' + self.linkstart = 0 + + def handle_starttag(self, tag, attrs): + """Called when a start tag is encountered""" + if tag == 'br': + self.result += '\n' + elif tag == 'a': + attrs = dict(attrs) + if 'href' in attrs: + self.result += '[' + self.linktarget = attrs['href'] + self.linkstart = len(self.result) + + def handle_endtag(self, tag): + """Called when an end tag is encountered""" + if tag == 'a': + if self.linktarget: + if self.result[self.linkstart:] == self.linktarget: + self.result += ']' + else: + self.result += ']({})'.format(self.linktarget) + self.linktarget = '' + + def handle_data(self, data): + """Called for character data (i.e. text)""" + self.result += data + + def handle_entityref(self, name): + """Called for entity references, such as &""" + try: + self.result += PYVER.unichr( + PYVER.html_entities.name2codepoint[name]) + except KeyError: + self.result += '&{};'.format(name) + + def handle_charref(self, name): + """Called for character references, such as '""" + try: + if name.startswith('x'): + self.result += PYVER.unichr(int(name[1:], 16)) + else: + self.result += PYVER.unichr(int(name)) + except ValueError: + self.result += '&#{};'.format(name) + +class TableFormatter(object): + """Format lists of string into aligned tables.""" + + def __init__(self): + self.rows = [] + self.max_widths = None + + def add_row(self, row): + """Add a row to the table.""" + self.rows.append(row) + row_widths = [ len(s) for s in row ] + if self.max_widths is None: + self.max_widths = row_widths + else: + self.max_widths = list(map(max, self.max_widths, row_widths)) + + def format(self): + """Return the formatted table as a string.""" + return '\n'.join([ self.format_row(row) for row in self.rows ]) + + def format_row(self, row): + """Format a single row as a string.""" + return ' |'.join( + [ s.ljust(self.max_widths[i]) for i, s in enumerate(row) ]) + +def message_in_cb(data, modifier, modifier_data, string): + """Incoming message callback""" + debug(('message_in_cb', data, modifier, modifier_data, string)) + + parsed = parse_irc_privmsg( + PYVER.to_unicode(string), PYVER.to_unicode(modifier_data)) + debug(('parsed message', parsed)) + + # skip processing messages to public channels + if parsed['to_channel']: + return string + + server = PYVER.to_unicode(modifier_data) + + from_user = irc_user(parsed['from_nick'], server) + local_user = current_user(server) + + context = ACCOUNTS[local_user].getContext(from_user) + + context.in_assembler.add(parsed['text']) + + result = '' + + if context.in_assembler.is_done(): + try: + msg, tlvs = context.receiveMessage( + # potr expects bytes + to_bytes(context.in_assembler.get())) + + debug(('receive', msg, tlvs)) + + if msg: + result = PYVER.to_str(build_privmsgs_in( + parsed['from'], parsed['to'], + context.msg_convert_in(msg))) + + context.handle_tlvs(tlvs) + except potr.context.ErrorReceived as err: + context.print_buffer('Received OTR error: {}'.format( + PYVER.to_unicode(err.args[0].error)), 'error') + except potr.context.NotEncryptedError: + context.print_buffer( + 'Received encrypted data but no private session established.', + 'warning') + except potr.context.NotOTRMessage: + result = string + except potr.context.UnencryptedMessage as err: + result = PYVER.to_str(build_privmsgs_in( + parsed['from'], parsed['to'], PYVER.to_unicode( + msg_plain_from_irc(err.args[0])), + 'Unencrypted message received: ')) + + weechat.bar_item_update(SCRIPT_NAME) + + return result + +def message_out_cb(data, modifier, modifier_data, string): + """Outgoing message callback.""" + result = '' + + # If any exception is raised in this function, WeeChat will not send the + # outgoing message, which could be something that the user intended to be + # encrypted. This paranoid exception handling ensures that the system + # fails closed and not open. + try: + debug(('message_out_cb', data, modifier, modifier_data, string)) + + parsed = parse_irc_privmsg( + PYVER.to_unicode(string), PYVER.to_unicode(modifier_data)) + debug(('parsed message', parsed)) + + # skip processing messages to public channels + if parsed['to_channel']: + return string + + server = PYVER.to_unicode(modifier_data) + + to_user = irc_user(parsed['to_nick'], server) + local_user = current_user(server) + + context = ACCOUNTS[local_user].getContext(to_user) + is_query = OTR_QUERY_RE.search(parsed['text']) + + parsed_text_bytes = to_bytes(parsed['text']) + + is_otr_message = \ + parsed_text_bytes[:len(potr.proto.OTRTAG)] == potr.proto.OTRTAG + + if is_otr_message and not is_query: + if not has_otr_end(parsed['text']): + debug('in OTR message') + context.in_otr_message = True + else: + debug('complete OTR message') + result = string + elif context.in_otr_message: + if has_otr_end(parsed['text']): + context.in_otr_message = False + debug('in OTR message end') + result = string + else: + debug(('context send message', parsed['text'], parsed['to_nick'], + server)) + + if context.policyOtrEnabled() and \ + not context.is_encrypted() and \ + not is_query and \ + context.getPolicy('require_encryption'): + context.print_buffer( + 'Your message will not be sent, because policy requires an ' + 'encrypted connection.', 'error') + context.hint( + 'Wait for the OTR connection or change the policy to allow ' + 'clear-text messages:\n' + '/policy set require_encryption off') + + try: + ret = context.sendMessage( + potr.context.FRAGMENT_SEND_ALL, + context.msg_convert_out(parsed['text'])) + + if ret: + debug(('sendMessage returned', ret)) + result = PYVER.to_str( + build_privmsg_out( + parsed['to_nick'], PYVER.to_unicode(ret) + )) + + except potr.context.NotEncryptedError as err: + if err.args[0] == potr.context.EXC_FINISHED: + context.print_buffer( + """Your message was not sent. End your private conversation:\n/otr finish""", + 'error') + else: + raise + + weechat.bar_item_update(SCRIPT_NAME) + except: + try: + print_buffer('', traceback.format_exc(), 'error') + print_buffer('', 'Versions: {versions}'.format( + versions=dependency_versions()), 'error') + context.print_buffer( + 'Failed to send message. See core buffer for traceback.', + 'error') + except: + pass + + return result + +def shutdown(): + """Script unload callback.""" + debug('shutdown') + + weechat.config_write(CONFIG_FILE) + + for account in ACCOUNTS.values(): + account.end_all_private() + + free_all_config() + + weechat.bar_item_remove(OTR_STATUSBAR) + + return weechat.WEECHAT_RC_OK + +def command_cb(data, buf, args): + """Parse and dispatch WeeChat OTR commands.""" + result = weechat.WEECHAT_RC_ERROR + + try: + arg_parts = [PYVER.to_unicode(arg) for arg in shlex.split(args)] + except: + debug("Command parsing error.") + return result + + if len(arg_parts) in (1, 3) and arg_parts[0] in ('start', 'refresh'): + nick, server = default_peer_args(arg_parts[1:3], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + # We need to wall disable_logging() here so that no OTR-related + # buffer messages get logged at any point. disable_logging() will + # be called again when effectively switching to encrypted, but + # the previous_log_level we set here will be preserved for later + # restoring. + if not context.getPolicy('log'): + context.previous_log_level = context.disable_logging() + else: + context.previous_log_level = context.get_log_level() + + context.hint('Sending OTR query... Please await confirmation of the OTR session being started before sending a message.') + if not context.getPolicy('send_tag'): + context.hint( + 'To try OTR on all conversations with {peer}: /otr policy send_tag on'.format( + peer=context.peer)) + + privmsg(server, nick, '?OTR?') + + result = weechat.WEECHAT_RC_OK + elif len(arg_parts) in (1, 3) and arg_parts[0] in ('finish', 'end'): + nick, server = default_peer_args(arg_parts[1:3], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + context.disconnect() + + result = weechat.WEECHAT_RC_OK + + elif len(arg_parts) in (1, 3) and arg_parts[0] == 'status': + nick, server = default_peer_args(arg_parts[1:3], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + if context.is_encrypted(): + context.print_buffer( + 'This conversation is encrypted.', 'success') + context.print_buffer("Your fingerprint is: {}".format( + context.user.getPrivkey())) + context.print_buffer("Your peer's fingerprint is: {}".format( + potr.human_hash(context.crypto.theirPubkey.cfingerprint()))) + if context.is_verified(): + context.print_buffer( + "The peer's identity has been verified.", + 'success') + else: + context.print_buffer( + "You have not verified the peer's identity yet.", + 'warning') + else: + context.print_buffer( + "This current conversation is not encrypted.", + 'warning') + + result = weechat.WEECHAT_RC_OK + + elif len(arg_parts) in range(2, 7) and arg_parts[0] == 'smp': + action = arg_parts[1] + + if action == 'respond': + # Check if nickname and server are specified + if len(arg_parts) == 3: + nick, server = default_peer_args([], buf) + secret = arg_parts[2] + elif len(arg_parts) == 5: + nick, server = default_peer_args(arg_parts[2:4], buf) + secret = arg_parts[4] + else: + return weechat.WEECHAT_RC_ERROR + + if secret: + secret = PYVER.to_str(secret) + + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + context.smpGotSecret(secret) + + result = weechat.WEECHAT_RC_OK + + elif action == 'ask': + question = None + secret = None + + # Nickname and server are not specified + # Check whether it's a simple challenge or a question/answer request + if len(arg_parts) == 3: + nick, server = default_peer_args([], buf) + secret = arg_parts[2] + elif len(arg_parts) == 4: + nick, server = default_peer_args([], buf) + secret = arg_parts[3] + question = arg_parts[2] + + # Nickname and server are specified + # Check whether it's a simple challenge or a question/answer request + elif len(arg_parts) == 5: + nick, server = default_peer_args(arg_parts[2:4], buf) + secret = arg_parts[4] + elif len(arg_parts) == 6: + nick, server = default_peer_args(arg_parts[2:4], buf) + secret = arg_parts[5] + question = arg_parts[4] + else: + return weechat.WEECHAT_RC_ERROR + + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + if secret: + secret = PYVER.to_str(secret) + if question: + question = PYVER.to_str(question) + + try: + context.smpInit(secret, question) + except potr.context.NotEncryptedError: + context.print_buffer( + 'There is currently no encrypted session with {}.'.format( + context.peer), 'error') + else: + if question: + context.print_buffer('SMP challenge sent...') + else: + context.print_buffer('SMP question sent...') + context.in_smp = True + result = weechat.WEECHAT_RC_OK + + elif action == 'abort': + # Nickname and server are not specified + if len(arg_parts) == 2: + nick, server = default_peer_args([], buf) + # Nickname and server are specified + elif len(arg_parts) == 4: + nick, server = default_peer_args(arg_parts[2:4], buf) + else: + return weechat.WEECHAT_RC_ERROR + + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + if context.in_smp: + try: + context.smpAbort() + except potr.context.NotEncryptedError: + context.print_buffer( + 'There is currently no encrypted session with {}.'.format( + context.peer), 'error') + else: + debug('SMP aborted') + context.smp_finish('SMP aborted.') + result = weechat.WEECHAT_RC_OK + + elif len(arg_parts) in (1, 3) and arg_parts[0] == 'trust': + nick, server = default_peer_args(arg_parts[1:3], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + if context.crypto.theirPubkey is not None: + context.setCurrentTrust('verified') + context.print_buffer('{peer} is now authenticated.'.format( + peer=context.peer)) + + weechat.bar_item_update(SCRIPT_NAME) + else: + context.print_buffer( + 'No fingerprint for {peer}. Start an OTR conversation first: /otr start'.format( + peer=context.peer), 'error') + + result = weechat.WEECHAT_RC_OK + elif len(arg_parts) in (1, 3) and arg_parts[0] == 'distrust': + nick, server = default_peer_args(arg_parts[1:3], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + if context.crypto.theirPubkey is not None: + context.setCurrentTrust('') + context.print_buffer( + '{peer} is now de-authenticated.'.format( + peer=context.peer)) + + weechat.bar_item_update(SCRIPT_NAME) + else: + context.print_buffer( + 'No fingerprint for {peer}. Start an OTR conversation first: /otr start'.format( + peer=context.peer), 'error') + + result = weechat.WEECHAT_RC_OK + + elif len(arg_parts) in (1, 2) and arg_parts[0] == 'log': + nick, server = default_peer_args([], buf) + if len(arg_parts) == 1: + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + if context.is_encrypted(): + if context.is_logged(): + context.print_buffer( + 'This conversation is currently being logged.', + 'warning') + result = weechat.WEECHAT_RC_OK + + else: + context.print_buffer( + 'This conversation is currently NOT being logged.') + result = weechat.WEECHAT_RC_OK + else: + context.print_buffer( + 'OTR LOG: Not in an OTR session', 'error') + result = weechat.WEECHAT_RC_OK + + else: + print_buffer('', 'OTR LOG: Not in an OTR session', 'error') + result = weechat.WEECHAT_RC_OK + + if len(arg_parts) == 2: + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + if arg_parts[1] == 'start' and \ + not context.is_logged() and \ + context.is_encrypted(): + if context.previous_log_level is None: + context.previous_log_level = context.get_log_level() + context.print_buffer('From this point on, this conversation will be logged. Please keep in mind that by doing so you are potentially putting yourself and your interlocutor at risk. You can disable this by doing /otr log stop', 'warning') + weechat.command(buf, '/mute logger set 9') + result = weechat.WEECHAT_RC_OK + + elif arg_parts[1] == 'stop' and \ + context.is_logged() and \ + context.is_encrypted(): + if context.previous_log_level is None: + context.previous_log_level = context.get_log_level() + weechat.command(buf, '/mute logger set 0') + context.print_buffer('From this point on, this conversation will NOT be logged ANYMORE.') + result = weechat.WEECHAT_RC_OK + + elif not context.is_encrypted(): + context.print_buffer( + 'OTR LOG: Not in an OTR session', 'error') + result = weechat.WEECHAT_RC_OK + + else: + # Don't need to do anything. + result = weechat.WEECHAT_RC_OK + + else: + print_buffer('', 'OTR LOG: Not in an OTR session', 'error') + + elif len(arg_parts) in (1, 2, 3, 4) and arg_parts[0] == 'policy': + if len(arg_parts) == 1: + nick, server = default_peer_args([], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + context.print_buffer(context.format_policies()) + else: + prnt('', format_default_policies()) + + result = weechat.WEECHAT_RC_OK + + elif len(arg_parts) == 2 and arg_parts[1].lower() == 'default': + nick, server = default_peer_args([], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + context.print_buffer(format_default_policies()) + else: + prnt('', format_default_policies()) + + result = weechat.WEECHAT_RC_OK + + elif len(arg_parts) == 3 and arg_parts[1].lower() in POLICIES: + nick, server = default_peer_args([], buf) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + policy_var = context.policy_config_option(arg_parts[1].lower()) + + command('', '/set {policy} {value}'.format( + policy=policy_var, + value=arg_parts[2])) + + context.print_buffer(context.format_policies()) + + result = weechat.WEECHAT_RC_OK + + elif len(arg_parts) == 4 and \ + arg_parts[1].lower() == 'default' and \ + arg_parts[2].lower() in POLICIES: + nick, server = default_peer_args([], buf) + + policy_var = "otr.policy.default." + arg_parts[2].lower() + + command('', '/set {policy} {value}'.format( + policy=policy_var, + value=arg_parts[3])) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + + context.print_buffer(format_default_policies()) + else: + prnt('', format_default_policies()) + + result = weechat.WEECHAT_RC_OK + elif len(arg_parts) in (1, 2) and arg_parts[0] == 'fingerprint': + if len(arg_parts) == 1: + show_account_fingerprints() + result = weechat.WEECHAT_RC_OK + elif len(arg_parts) == 2: + if arg_parts[1] == 'all': + show_peer_fingerprints() + else: + show_peer_fingerprints(grep=arg_parts[1]) + result = weechat.WEECHAT_RC_OK + + return result + +def otr_statusbar_cb(data, item, window): + """Update the statusbar.""" + if window: + buf = weechat.window_get_pointer(window, 'buffer') + else: + # If the bar item is in a root bar that is not in a window, window + # will be empty. + buf = weechat.current_buffer() + + result = '' + + if buffer_is_private(buf): + local_user = irc_user( + buffer_get_string(buf, 'localvar_nick'), + buffer_get_string(buf, 'localvar_server')) + + remote_user = irc_user( + buffer_get_string(buf, 'localvar_channel'), + buffer_get_string(buf, 'localvar_server')) + + context = ACCOUNTS[local_user].getContext(remote_user) + + encrypted_str = config_string('look.bar.state.encrypted') + unencrypted_str = config_string('look.bar.state.unencrypted') + authenticated_str = config_string('look.bar.state.authenticated') + unauthenticated_str = config_string('look.bar.state.unauthenticated') + logged_str = config_string('look.bar.state.logged') + notlogged_str = config_string('look.bar.state.notlogged') + + bar_parts = [] + + if context.is_encrypted(): + if encrypted_str: + bar_parts.append(''.join([ + config_color('status.encrypted'), + encrypted_str, + config_color('status.default')])) + + if context.is_verified(): + if authenticated_str: + bar_parts.append(''.join([ + config_color('status.authenticated'), + authenticated_str, + config_color('status.default')])) + elif unauthenticated_str: + bar_parts.append(''.join([ + config_color('status.unauthenticated'), + unauthenticated_str, + config_color('status.default')])) + + if context.is_logged(): + if logged_str: + bar_parts.append(''.join([ + config_color('status.logged'), + logged_str, + config_color('status.default')])) + elif notlogged_str: + bar_parts.append(''.join([ + config_color('status.notlogged'), + notlogged_str, + config_color('status.default')])) + + elif unencrypted_str: + bar_parts.append(''.join([ + config_color('status.unencrypted'), + unencrypted_str, + config_color('status.default')])) + + result = config_string('look.bar.state.separator').join(bar_parts) + + if result: + result = '{color}{prefix}{result}'.format( + color=config_color('status.default'), + prefix=config_string('look.bar.prefix'), + result=result) + + return result + +def bar_config_update_cb(data, option): + """Callback for updating the status bar when its config changes.""" + weechat.bar_item_update(SCRIPT_NAME) + + return weechat.WEECHAT_RC_OK + +def policy_completion_cb(data, completion_item, buf, completion): + """Callback for policy tab completion.""" + for policy in POLICIES: + weechat.hook_completion_list_add( + completion, policy, 0, weechat.WEECHAT_LIST_POS_SORT) + + return weechat.WEECHAT_RC_OK + +def policy_create_option_cb(data, config_file, section, name, value): + """Callback for creating a new policy option when the user sets one + that doesn't exist.""" + weechat.config_new_option( + config_file, section, name, 'boolean', '', '', 0, 0, value, value, 0, + '', '', '', '', '', '') + + return weechat.WEECHAT_CONFIG_OPTION_SET_OK_CHANGED + +def logger_level_update_cb(data, option, value): + """Callback called when any logger level changes.""" + weechat.bar_item_update(SCRIPT_NAME) + + return weechat.WEECHAT_RC_OK + +def buffer_switch_cb(data, signal, signal_data): + """Callback for buffer switched. + + Used for updating the status bar item when it is in a root bar. + """ + weechat.bar_item_update(SCRIPT_NAME) + + return weechat.WEECHAT_RC_OK + +def buffer_closing_cb(data, signal, signal_data): + """Callback for buffer closed. + + It closes the OTR session when the buffer is about to be closed. + """ + result = weechat.WEECHAT_RC_ERROR + nick, server = default_peer_args([], signal_data) + + if nick is not None and server is not None: + context = ACCOUNTS[current_user(server)].getContext( + irc_user(nick, server)) + context.disconnect() + + result = weechat.WEECHAT_RC_OK + return result + +def init_config(): + """Set up configuration options and load config file.""" + global CONFIG_FILE + CONFIG_FILE = weechat.config_new(SCRIPT_NAME, 'config_reload_cb', '') + + global CONFIG_SECTIONS + CONFIG_SECTIONS = {} + + CONFIG_SECTIONS['general'] = weechat.config_new_section( + CONFIG_FILE, 'general', 0, 0, '', '', '', '', '', '', '', '', '', '') + + for option, typ, desc, default in [ + ('debug', 'boolean', 'OTR script debugging', 'off'), + ('hints', 'boolean', 'Give helpful hints how to use this script and how to stay secure while using OTR (recommended)', 'on'), + ('defaultkey', 'string', + 'default private key to use for new accounts (nick@server)', ''), + ('no_send_tag_regex', 'string', + 'do not OTR whitespace tag messages to nicks matching this regex ' + '(case insensitive)', + '^(alis|chanfix|global|.+serv|\*.+)$'), + ]: + weechat.config_new_option( + CONFIG_FILE, CONFIG_SECTIONS['general'], option, typ, desc, '', 0, + 0, default, default, 0, '', '', '', '', '', '') + + CONFIG_SECTIONS['color'] = weechat.config_new_section( + CONFIG_FILE, 'color', 0, 0, '', '', '', '', '', '', '', '', '', '') + + for option, desc, default, update_cb in [ + ('status.default', 'status bar default color', 'default', + 'bar_config_update_cb'), + ('status.encrypted', 'status bar encrypted indicator color', 'green', + 'bar_config_update_cb'), + ('status.unencrypted', 'status bar unencrypted indicator color', + 'lightred', 'bar_config_update_cb'), + ('status.authenticated', 'status bar authenticated indicator color', + 'green', 'bar_config_update_cb'), + ('status.unauthenticated', 'status bar unauthenticated indicator color', + 'lightred', 'bar_config_update_cb'), + ('status.logged', 'status bar logged indicator color', 'lightred', + 'bar_config_update_cb'), + ('status.notlogged', 'status bar not logged indicator color', + 'green', 'bar_config_update_cb'), + ('buffer.hint', 'text color for hints', 'lightblue', ''), + ('buffer.info', 'text color for informational messages', 'default', ''), + ('buffer.success', 'text color for success messages', 'lightgreen', ''), + ('buffer.warning', 'text color for warnings', 'yellow', ''), + ('buffer.error', 'text color for errors', 'lightred', ''), + ]: + weechat.config_new_option( + CONFIG_FILE, CONFIG_SECTIONS['color'], option, 'color', desc, '', 0, + 0, default, default, 0, '', '', update_cb, '', '', '') + + CONFIG_SECTIONS['look'] = weechat.config_new_section( + CONFIG_FILE, 'look', 0, 0, '', '', '', '', '', '', '', '', '', '') + + for option, desc, default, update_cb in [ + ('bar.prefix', 'prefix for OTR status bar item', 'OTR:', + 'bar_config_update_cb'), + ('bar.state.encrypted', + 'shown in status bar when conversation is encrypted', 'SEC', + 'bar_config_update_cb'), + ('bar.state.unencrypted', + 'shown in status bar when conversation is not encrypted', '!SEC', + 'bar_config_update_cb'), + ('bar.state.authenticated', + 'shown in status bar when peer is authenticated', 'AUTH', + 'bar_config_update_cb'), + ('bar.state.unauthenticated', + 'shown in status bar when peer is not authenticated', '!AUTH', + 'bar_config_update_cb'), + ('bar.state.logged', + 'shown in status bar when peer conversation is being logged to disk', + 'LOG', + 'bar_config_update_cb'), + ('bar.state.notlogged', + 'shown in status bar when peer conversation is not being logged to disk', + '!LOG', + 'bar_config_update_cb'), + ('bar.state.separator', 'separator for states in the status bar', ',', + 'bar_config_update_cb'), + ('prefix', 'prefix used for messages from otr (note: content is evaluated, see /help eval)', + '${color:default}:! ${color:brown}otr${color:default} !:', ''), + ]: + weechat.config_new_option( + CONFIG_FILE, CONFIG_SECTIONS['look'], option, 'string', desc, '', + 0, 0, default, default, 0, '', '', update_cb, '', '', '') + + CONFIG_SECTIONS['policy'] = weechat.config_new_section( + CONFIG_FILE, 'policy', 1, 1, '', '', '', '', '', '', + 'policy_create_option_cb', '', '', '') + + for option, desc, default in [ + ('default.allow_v2', 'default allow OTR v2 policy', 'on'), + ('default.require_encryption', 'default require encryption policy', + 'off'), + ('default.log', 'default enable logging to disk', 'off'), + ('default.send_tag', 'default send tag policy', 'off'), + ('default.html_escape', 'default HTML escape policy', 'off'), + ('default.html_filter', 'default HTML filter policy', 'on'), + ]: + weechat.config_new_option( + CONFIG_FILE, CONFIG_SECTIONS['policy'], option, 'boolean', desc, '', + 0, 0, default, default, 0, '', '', '', '', '', '') + + weechat.config_read(CONFIG_FILE) + +def config_reload_cb(data, config_file): + """/reload callback to reload config from file.""" + free_all_config() + init_config() + + return weechat.WEECHAT_CONFIG_READ_OK + +def free_all_config(): + """Free all config options, sections and config file.""" + for section in CONFIG_SECTIONS.values(): + weechat.config_section_free_options(section) + weechat.config_section_free(section) + + weechat.config_free(CONFIG_FILE) + +def create_dir(): + """Create the OTR subdirectory in the WeeChat config directory if it does + not exist.""" + if not os.path.exists(OTR_DIR): + weechat.mkdir_home(OTR_DIR_NAME, 0o700) + +def git_info(): + """If this script is part of a git repository return the repo state.""" + result = None + script_dir = os.path.dirname(os.path.realpath(__file__)) + git_dir = os.path.join(script_dir, '.git') + if os.path.isdir(git_dir): + import subprocess + try: + result = PYVER.to_unicode(subprocess.check_output([ + 'git', + '--git-dir', git_dir, + '--work-tree', script_dir, + 'describe', '--dirty', '--always', + ])).lstrip('v').rstrip() + except (OSError, subprocess.CalledProcessError): + pass + + return result + +def weechat_version_ok(): + """Check if the WeeChat version is compatible with this script. + + If WeeChat version < 0.4.2 log an error to the core buffer and return + False. Otherwise return True. + """ + weechat_version = weechat.info_get('version_number', '') or 0 + if int(weechat_version) < 0x00040200: + error_message = ( + '{script_name} requires WeeChat version >= 0.4.2. The current ' + 'version is {current_version}.').format( + script_name=SCRIPT_NAME, + current_version=weechat.info_get('version', '')) + prnt('', error_message) + return False + else: + return True + +SCRIPT_VERSION = git_info() or SCRIPT_VERSION + +def dependency_versions(): + """Return a string containing the versions of all dependencies.""" + return ('weechat-otr {script_version}, ' + 'potr {potr_major}.{potr_minor}.{potr_patch}-{potr_sub}, ' + 'Python {python_version}, ' + 'WeeChat {weechat_version}' + ).format( + script_version=SCRIPT_VERSION, + potr_major=potr.VERSION[0], + potr_minor=potr.VERSION[1], + potr_patch=potr.VERSION[2], + potr_sub=potr.VERSION[3], + python_version=platform.python_version(), + weechat_version=weechat.info_get('version', '')) + +def excepthook(typ, value, traceback): + sys.stderr.write('Versions: ') + sys.stderr.write(dependency_versions()) + sys.stderr.write('\n') + + sys.__excepthook__(typ, value, traceback) + +sys.excepthook = excepthook + +if weechat.register( + SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENCE, SCRIPT_DESC, + 'shutdown', ''): + if weechat_version_ok(): + init_config() + + OTR_DIR = os.path.join(info_get('weechat_dir', ''), OTR_DIR_NAME) + create_dir() + + ACCOUNTS = AccountDict() + + weechat.hook_modifier('irc_in_privmsg', 'message_in_cb', '') + weechat.hook_modifier('irc_out_privmsg', 'message_out_cb', '') + + weechat.hook_command( + SCRIPT_NAME, SCRIPT_HELP, + 'start [NICK SERVER] || ' + 'refresh [NICK SERVER] || ' + 'finish [NICK SERVER] || ' + 'end [NICK SERVER] || ' + 'status [NICK SERVER] || ' + 'smp ask [NICK SERVER] [QUESTION] SECRET || ' + 'smp respond [NICK SERVER] SECRET || ' + 'smp abort [NICK SERVER] || ' + 'trust [NICK SERVER] || ' + 'distrust [NICK SERVER] || ' + 'log [on|off] || ' + 'policy [POLICY on|off] || ' + 'fingerprint [SEARCH|all]', + '', + 'start %(nick) %(irc_servers) %-||' + 'refresh %(nick) %(irc_servers) %-||' + 'finish %(nick) %(irc_servers) %-||' + 'end %(nick) %(irc_servers) %-||' + 'status %(nick) %(irc_servers) %-||' + 'smp ask|respond %(nick) %(irc_servers) %-||' + 'smp abort %(nick) %(irc_servers) %-||' + 'trust %(nick) %(irc_servers) %-||' + 'distrust %(nick) %(irc_servers) %-||' + 'log on|off %-||' + 'policy %(otr_policy) on|off %-||' + 'fingerprint all %-||', + 'command_cb', + '') + + weechat.hook_completion( + 'otr_policy', 'OTR policies', 'policy_completion_cb', '') + + weechat.hook_config('logger.level.irc.*', 'logger_level_update_cb', '') + + weechat.hook_signal('buffer_switch', 'buffer_switch_cb', '') + weechat.hook_signal('buffer_closing', 'buffer_closing_cb', '') + + OTR_STATUSBAR = weechat.bar_item_new( + SCRIPT_NAME, 'otr_statusbar_cb', '') + weechat.bar_item_update(SCRIPT_NAME) diff --git a/.weechat/python/screen_away.py b/.weechat/python/screen_away.py new file mode 100644 index 0000000..8f68505 --- /dev/null +++ b/.weechat/python/screen_away.py @@ -0,0 +1,197 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2009 by xt +# Copyright (c) 2009 by penryu +# Copyright (c) 2010 by Blake Winton +# Copyright (c) 2010 by Aron Griffis +# Copyright (c) 2010 by Jani Kesänen +# +# 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 . +# + +# +# (this script requires WeeChat 0.3.0 or newer) +# +# History: +# 2014-08-02, Nils Görs +# version 0.14: add time to detach message. (idea by Mikaela) +# 2014-06-19, Anders Bergh +# version 0.13: Fix a simple typo in an option description. +# 2014-01-12, Phyks (Lucas Verney) +# version 0.12: Added an option to check status of relays to set unaway in +# case of a connected relay. +# 2013-08-30, Anders Einar Hilden +# version: 0.11: Fix reading of set_away +# 2013-06-16, Renato Botelho +# version 0.10: add option to don't set away, only change nick +# allow multiple commands on attach/dettach +# do not add suffix if nick already have it +# 2012-12-29, David Flatz +# version 0.9: add option to ignore servers and don't set away status for them +# add descriptions to config options +# 2010-08-07, Filip H.F. "FiXato" Slagter +# version 0.8: add command on attach feature +# 2010-05-07, Jani Kesänen +# version 0.7: add command on detach feature +# 2010-03-07, Aron Griffis +# version 0.6: move socket check to register, +# add hook_config for interval, +# reduce default interval from 60 to 5 +# 2010-02-19, Blake Winton +# version 0.5: add option to change nick when away +# 2010-01-18, xt +# version 0.4: only update servers that are connected +# 2009-11-30, xt +# version 0.3: do not touch servers that are manually set away +# 2009-11-27, xt +# version 0.2: code for TMUX from penryu +# 2009-11-27, xt +# version 0.1: initial release + +import weechat as w +import re +import os +import datetime, time + +SCRIPT_NAME = "screen_away" +SCRIPT_AUTHOR = "xt " +SCRIPT_VERSION = "0.14" +SCRIPT_LICENSE = "GPL3" +SCRIPT_DESC = "Set away status on screen detach" + +settings = { + 'message': ('Detached from screen', 'Away message'), + 'time_format': ('since %Y-%m-%d %H:%M:%S%z', 'time format append to away message'), + 'interval': ('5', 'How often in seconds to check screen status'), + 'away_suffix': ('', 'What to append to your nick when you\'re away.'), + 'command_on_attach': ('', 'Commands to execute on attach, separated by semicolon'), + 'command_on_detach': ('', 'Commands to execute on detach, separated by semicolon'), + 'ignore': ('', 'Comma-separated list of servers to ignore.'), + 'set_away': ('on', 'Set user as away.'), + 'ignore_relays': ('off', 'Only check screen status and ignore relay interfaces'), +} + +TIMER = None +SOCK = None +AWAY = False +CONNECTED_RELAY = False + +def set_timer(): + '''Update timer hook with new interval''' + + global TIMER + if TIMER: + w.unhook(TIMER) + TIMER = w.hook_timer(int(w.config_get_plugin('interval')) * 1000, + 0, 0, "screen_away_timer_cb", '') + +def screen_away_config_cb(data, option, value): + if option.endswith(".interval"): + set_timer() + return w.WEECHAT_RC_OK + +def get_servers(): + '''Get the servers that are not away, or were set away by this script''' + + ignores = w.config_get_plugin('ignore').split(',') + infolist = w.infolist_get('irc_server','','') + buffers = [] + while w.infolist_next(infolist): + if not w.infolist_integer(infolist, 'is_connected') == 1 or \ + w.infolist_string(infolist, 'name') in ignores: + continue + if not w.config_string_to_boolean(w.config_get_plugin('set_away')) or \ + not w.infolist_integer(infolist, 'is_away') or \ + w.config_get_plugin('message') in w.infolist_string(infolist, 'away_message'): +# w.infolist_string(infolist, 'away_message') == \ +# w.config_get_plugin('message'): + buffers.append((w.infolist_pointer(infolist, 'buffer'), + w.infolist_string(infolist, 'nick'))) + w.infolist_free(infolist) + return buffers + +def screen_away_timer_cb(buffer, args): + '''Check if screen is attached, update awayness''' + + global AWAY, SOCK, CONNECTED_RELAY + + set_away = w.config_string_to_boolean(w.config_get_plugin('set_away')) + check_relays = not w.config_string_to_boolean(w.config_get_plugin('ignore_relays')) + suffix = w.config_get_plugin('away_suffix') + attached = os.access(SOCK, os.X_OK) # X bit indicates attached + + # Check wether a client is connected on relay or not + CONNECTED_RELAY = False + if check_relays: + infolist = w.infolist_get('relay', '', '') + if infolist: + while w.infolist_next(infolist): + status = w.infolist_string(infolist, 'status_string') + if status == 'connected': + CONNECTED_RELAY = True + break + w.infolist_free(infolist) + + if (attached and AWAY) or (check_relays and CONNECTED_RELAY and not attached and AWAY): + w.prnt('', '%s: Screen attached. Clearing away status' % SCRIPT_NAME) + for server, nick in get_servers(): + if set_away: + w.command(server, "/away") + if suffix and nick.endswith(suffix): + nick = nick[:-len(suffix)] + w.command(server, "/nick %s" % nick) + AWAY = False + for cmd in w.config_get_plugin("command_on_attach").split(";"): + w.command("", cmd) + + elif not attached and not AWAY: + if not CONNECTED_RELAY: + w.prnt('', '%s: Screen detached. Setting away status' % SCRIPT_NAME) + for server, nick in get_servers(): + if suffix and not nick.endswith(suffix): + w.command(server, "/nick %s%s" % (nick, suffix)); + if set_away: + w.command(server, "/away %s %s" % (w.config_get_plugin('message'), time.strftime(w.config_get_plugin('time_format')))) + AWAY = True + for cmd in w.config_get_plugin("command_on_detach").split(";"): + w.command("", cmd) + + return w.WEECHAT_RC_OK + + +if w.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE, + SCRIPT_DESC, "", ""): + version = w.info_get('version_number', '') or 0 + for option, default_desc in settings.iteritems(): + if not w.config_is_set_plugin(option): + w.config_set_plugin(option, default_desc[0]) + if int(version) >= 0x00030500: + w.config_set_desc_plugin(option, default_desc[1]) + + if 'STY' in os.environ.keys(): + # We are running under screen + cmd_output = os.popen('env LC_ALL=C screen -ls').read() + match = re.search(r'Sockets? in (/.+)\.', cmd_output) + if match: + SOCK = os.path.join(match.group(1), os.environ['STY']) + + if not SOCK and 'TMUX' in os.environ.keys(): + # We are running under tmux + socket_data = os.environ['TMUX'] + SOCK = socket_data.rsplit(',',2)[0] + + if SOCK: + set_timer() + w.hook_config("plugins.var.python." + SCRIPT_NAME + ".*", + "screen_away_config_cb", "") diff --git a/.weechat/python/urlview.py b/.weechat/python/urlview.py new file mode 100644 index 0000000..a429f1e --- /dev/null +++ b/.weechat/python/urlview.py @@ -0,0 +1,57 @@ +# This weechat plugin pipes the current weechat buffer through urlview +# +# Usage: +# /urlview +# +# History: +# 10-04-2015 +# Version 1.0.0: initial release +# Version 1.0.1: reverse text passed to urlview +# Version 1.0.2: remove weechat color from messages + +import distutils.spawn +import os +import pipes +import weechat + + +def urlview(data, buf, args): + infolist = weechat.infolist_get("buffer_lines", buf, "") + lines = [] + while weechat.infolist_next(infolist) == 1: + lines.append( + weechat.string_remove_color( + weechat.infolist_string(infolist, "message"), + "" + ) + ) + + weechat.infolist_free(infolist) + + if not lines: + weechat.prnt(buf, "No URLs found") + return weechat.WEECHAT_RC_OK + + text = "\n".join(reversed(lines)) + response = os.system("echo %s | urlview" % pipes.quote(text)) + if response != 0: + weechat.prnt(buf, "No URLs found") + + weechat.command(buf, "/window refresh") + + return weechat.WEECHAT_RC_OK + + +def main(): + if distutils.spawn.find_executable("urlview") is None: + return weechat.WEECHAT_RC_ERROR + + if not weechat.register("urlview", "Keith Smiley", "1.0.2", "MIT", + "Use urlview on the current buffer", "", ""): + return weechat.WEECHAT_RC_ERROR + + weechat.hook_command("urlview", "Pass the current buffer to urlview", "", + "", "", "urlview", "") + +if __name__ == "__main__": + main() diff --git a/.weechat/relay.conf b/.weechat/relay.conf new file mode 100644 index 0000000..fa3976a --- /dev/null +++ b/.weechat/relay.conf @@ -0,0 +1,38 @@ +# +# relay.conf -- weechat v1.0.1 +# + +[look] +auto_open_buffer = on +raw_messages = 256 + +[color] +client = cyan +status_active = lightblue +status_auth_failed = lightred +status_connecting = 130 +status_disconnected = lightred +status_waiting_auth = brown +text = default +text_bg = default +text_selected = white + +[network] +allowed_ips = "" +bind_address = "" +clients_purge_delay = 0 +compression_level = 6 +ipv6 = on +max_clients = 5 +password = "" +ssl_cert_key = "%h/ssl/relay.pem" +websocket_allowed_origins = "" + +[irc] +backlog_max_minutes = 1440 +backlog_max_number = 256 +backlog_since_last_disconnect = on +backlog_tags = "irc_privmsg" +backlog_time_format = "[%H:%M] " + +[port] diff --git a/.weechat/script.conf b/.weechat/script.conf new file mode 100644 index 0000000..d0e3ecf --- /dev/null +++ b/.weechat/script.conf @@ -0,0 +1,50 @@ +# +# script.conf -- weechat v1.0.1 +# + +[look] +columns = "%s %n %V %v %u │ %d │ %t" +diff_color = on +diff_command = "auto" +display_source = on +quiet_actions = on +sort = "p,n" +translate_description = on +use_keys = on + +[color] +status_autoloaded = cyan +status_held = white +status_installed = lightcyan +status_obsolete = lightmagenta +status_popular = 130 +status_running = lightgreen +status_unknown = lightred +text = default +text_bg = default +text_bg_selected = 235 +text_date = default +text_date_selected = white +text_delimiters = 130 +text_description = default +text_description_selected = white +text_extension = default +text_extension_selected = white +text_name = cyan +text_name_selected = lightcyan +text_selected = white +text_tags = brown +text_tags_selected = 130 +text_version = magenta +text_version_loaded = default +text_version_loaded_selected = white +text_version_selected = lightmagenta + +[scripts] +autoload = on +cache_expire = 1440 +download_timeout = 30 +path = "%h/script" +hold = "" +url = "http://weechat.org/files/plugins.xml.gz" +url_force_https = on diff --git a/.weechat/script/plugins.xml.gz b/.weechat/script/plugins.xml.gz new file mode 100644 index 0000000..4dcd39f Binary files /dev/null and b/.weechat/script/plugins.xml.gz differ diff --git a/.weechat/sec.conf b/.weechat/sec.conf new file mode 100644 index 0000000..c8a08d8 --- /dev/null +++ b/.weechat/sec.conf @@ -0,0 +1,11 @@ +# +# sec.conf -- weechat v1.0.1 +# + +[crypt] +cipher = aes256 +hash_algo = sha256 +passphrase_file = "" +salt = on + +[data] diff --git a/.weechat/trigger.conf b/.weechat/trigger.conf new file mode 100644 index 0000000..2a1384c --- /dev/null +++ b/.weechat/trigger.conf @@ -0,0 +1,47 @@ +# +# trigger.conf -- weechat v1.0.1 +# + +[look] +enabled = on +monitor_strip_colors = off + +[color] +flag_command = lightgreen +flag_conditions = 130 +flag_regex = lightcyan +flag_return_code = lightmagenta +regex = white +replace = cyan +trigger = green +trigger_disabled = red + +[trigger] +beep.arguments = "" +beep.command = "/print -beep" +beep.conditions = "${tg_highlight} || ${tg_msg_pv}" +beep.enabled = on +beep.hook = print +beep.regex = "" +beep.return_code = ok +cmd_pass.arguments = "5000|input_text_display;5000|history_add;5000|irc_command_auth" +cmd_pass.command = "" +cmd_pass.conditions = "" +cmd_pass.enabled = on +cmd_pass.hook = modifier +cmd_pass.regex = "==^((/(msg|m|quote) +nickserv +(id|identify|register|ghost +[^ ]+|release +[^ ]+|regain +[^ ]+) +)|/oper +[^ ]+ +|/quote +pass +|/set +[^ ]*password[^ ]* +|/secure +(passphrase|decrypt|set +[^ ]+) +)(.*)==${re:1}${hide:*,${re:+}}" +cmd_pass.return_code = ok +msg_auth.arguments = "5000|irc_message_auth" +msg_auth.command = "" +msg_auth.conditions = "" +msg_auth.enabled = on +msg_auth.hook = modifier +msg_auth.regex = "==^(.*(id|identify|register|ghost +[^ ]+|release +[^ ]+) +)(.*)==${re:1}${hide:*,${re:+}}" +msg_auth.return_code = ok +server_pass.arguments = "5000|input_text_display;5000|history_add" +server_pass.command = "" +server_pass.conditions = "" +server_pass.enabled = on +server_pass.hook = modifier +server_pass.regex = "==^(/(server|connect) .*-(sasl_)?password=)([^ ]+)(.*)==${re:1}${hide:*,${re:4}}${re:5}" +server_pass.return_code = ok diff --git a/.weechat/weechat.conf b/.weechat/weechat.conf new file mode 100644 index 0000000..071f2ef --- /dev/null +++ b/.weechat/weechat.conf @@ -0,0 +1,619 @@ +# +# weechat.conf -- weechat v1.0.1 +# + +[debug] + +[startup] +command_after_plugins = "" +command_before_plugins = "" +display_logo = on +display_version = on +sys_rlimit = "" + +[look] +align_end_of_lines = message +bar_more_down = "++" +bar_more_left = "<<" +bar_more_right = ">>" +bar_more_up = "--" +bare_display_exit_on_input = on +bare_display_time_format = "%H:%M" +buffer_auto_renumber = on +buffer_notify_default = all +buffer_position = end +buffer_search_case_sensitive = off +buffer_search_force_default = off +buffer_search_regex = off +buffer_search_where = prefix_message +buffer_time_format = "${color:250}%H${color:lightcyan}:${color:245}%M${color:lightcyan}:${color:240}%S" +color_basic_force_bold = off +color_inactive_buffer = on +color_inactive_message = on +color_inactive_prefix = on +color_inactive_prefix_buffer = on +color_inactive_time = off +color_inactive_window = on +color_nick_offline = on +color_pairs_auto_reset = 5 +color_real_white = off +command_chars = "" +confirm_quit = off +day_change = on +day_change_message_1date = "-- %a, %d %b %Y --" +day_change_message_2dates = "-- %%a, %%d %%b %%Y (%a, %d %b %Y) --" +eat_newline_glitch = off +emphasized_attributes = "" +highlight = "" +highlight_regex = "" +highlight_tags = "" +hotlist_add_conditions = "${away} || ${buffer.num_displayed} == 0" +hotlist_buffer_separator = ", " +hotlist_count_max = 2 +hotlist_count_min_msg = 2 +hotlist_names_count = 3 +hotlist_names_length = 0 +hotlist_names_level = 12 +hotlist_names_merged_buffers = off +hotlist_prefix = "H: " +hotlist_remove = merged +hotlist_short_names = on +hotlist_sort = group_time_asc +hotlist_suffix = "" +hotlist_unique_numbers = on +input_cursor_scroll = 20 +input_share = none +input_share_overwrite = off +input_undo_max = 32 +item_buffer_filter = "*" +item_buffer_zoom = "!" +item_time_format = "%H:%M" +jump_current_to_previous_buffer = on +jump_previous_buffer_when_closing = on +jump_smart_back_to_buffer = on +key_bind_safe = on +mouse = off +mouse_timer_delay = 100 +nick_prefix = "" +nick_suffix = "" +paste_bracketed = on +paste_bracketed_timer_delay = 10 +paste_max_lines = 1 +prefix_action = " *" +prefix_align = right +prefix_align_max = 15 +prefix_align_min = 15 +prefix_align_more = "+" +prefix_align_more_after = on +prefix_buffer_align = right +prefix_buffer_align_max = 0 +prefix_buffer_align_more = "+" +prefix_buffer_align_more_after = on +prefix_error = "=!=" +prefix_join = "-->" +prefix_network = "--" +prefix_quit = "<--" +prefix_same_nick = "" +prefix_suffix = "│" +read_marker = line +read_marker_always_show = off +read_marker_string = "- " +save_config_on_exit = on +save_layout_on_exit = none +scroll_amount = 3 +scroll_bottom_after_switch = off +scroll_page_percent = 100 +search_text_not_found_alert = on +separator_horizontal = "-" +separator_vertical = "" +tab_width = 1 +time_format = "%a, %d %b %Y %T" +window_auto_zoom = off +window_separator_horizontal = on +window_separator_vertical = on +window_title = "WeeChat ${info:version}" + +[palette] + +[color] +bar_more = lightcyan +chat = default +chat_bg = default +chat_buffer = white +chat_channel = white +chat_day_change = cyan +chat_delimiters = 235 +chat_highlight = lightcyan +chat_highlight_bg = 235 +chat_host = cyan +chat_inactive_buffer = default +chat_inactive_window = default +chat_nick = lightcyan +chat_nick_colors = "cyan,magenta,green,brown,lightblue,default,lightcyan,lightmagenta,lightgreen,blue" +chat_nick_offline = blue +chat_nick_offline_highlight = default +chat_nick_offline_highlight_bg = blue +chat_nick_other = cyan +chat_nick_prefix = green +chat_nick_self = red +chat_nick_suffix = green +chat_prefix_action = white +chat_prefix_buffer = brown +chat_prefix_buffer_inactive_buffer = default +chat_prefix_error = 130 +chat_prefix_join = lightgreen +chat_prefix_more = lightmagenta +chat_prefix_network = magenta +chat_prefix_quit = lightred +chat_prefix_suffix = 235 +chat_read_marker = magenta +chat_read_marker_bg = default +chat_server = brown +chat_tags = red +chat_text_found = 130 +chat_text_found_bg = lightmagenta +chat_time = default +chat_time_delimiters = brown +chat_value = cyan +emphasized = 130 +emphasized_bg = magenta +input_actions = lightgreen +input_text_not_found = red +nicklist_away = cyan +nicklist_group = green +separator = 235 +status_count_highlight = magenta +status_count_msg = brown +status_count_other = default +status_count_private = green +status_data_highlight = lightmagenta +status_data_msg = 130 +status_data_other = default +status_data_private = lightgreen +status_filter = green +status_more = 130 +status_name = white +status_name_ssl = lightgreen +status_nicklist_count = default +status_number = 130 +status_time = default + +[completion] +base_word_until_cursor = on +default_template = "%(nicks)|%(irc_channels)" +nick_add_space = on +nick_completer = ":" +nick_first_only = off +nick_ignore_chars = "[]`_-^" +partial_completion_alert = on +partial_completion_command = off +partial_completion_command_arg = off +partial_completion_count = on +partial_completion_other = off + +[history] +display_default = 5 +max_buffer_lines_minutes = 0 +max_buffer_lines_number = 4096 +max_commands = 100 +max_visited_buffers = 50 + +[proxy] + +[network] +connection_timeout = 60 +gnutls_ca_file = "/etc/ssl/certs/ca-certificates.crt" +gnutls_handshake_timeout = 30 +proxy_curl = "" + +[plugin] +autoload = "*" +debug = off +extension = ".so,.dll" +path = "%h/plugins" +save_config_on_unload = on + +[bar] +buflist.color_bg = default +buflist.color_delim = default +buflist.color_fg = default +buflist.conditions = "" +buflist.filling_left_right = vertical +buflist.filling_top_bottom = columns_vertical +buflist.hidden = off +buflist.items = "buflist" +buflist.position = left +buflist.priority = 100 +buflist.separator = on +buflist.size = 0 +buflist.size_max = 0 +buflist.type = root +isetbar.color_bg = default +isetbar.color_delim = cyan +isetbar.color_fg = default +isetbar.conditions = "" +isetbar.filling_left_right = vertical +isetbar.filling_top_bottom = horizontal +isetbar.hidden = on +isetbar.items = "isetbar_help" +isetbar.position = top +isetbar.priority = 0 +isetbar.separator = on +isetbar.size = 3 +isetbar.size_max = 3 +isetbar.type = window +nicklist.color_bg = default +nicklist.color_delim = cyan +nicklist.color_fg = default +nicklist.conditions = "${nicklist}" +nicklist.filling_left_right = vertical +nicklist.filling_top_bottom = columns_vertical +nicklist.hidden = off +nicklist.items = "buffer_nicklist" +nicklist.position = right +nicklist.priority = 200 +nicklist.separator = on +nicklist.size = 0 +nicklist.size_max = 0 +nicklist.type = window +rootinput.color_bg = default +rootinput.color_delim = cyan +rootinput.color_fg = default +rootinput.conditions = "" +rootinput.filling_left_right = vertical +rootinput.filling_top_bottom = horizontal +rootinput.hidden = off +rootinput.items = "[input_prompt]+(away),[input_search],[input_paste],input_text" +rootinput.position = bottom +rootinput.priority = 50 +rootinput.separator = off +rootinput.size = 1 +rootinput.size_max = 0 +rootinput.type = root +rootstatus.color_bg = 235 +rootstatus.color_delim = lightcyan +rootstatus.color_fg = default +rootstatus.conditions = "" +rootstatus.filling_left_right = vertical +rootstatus.filling_top_bottom = horizontal +rootstatus.hidden = off +rootstatus.items = "[time],[buffer_last_number],[buffer_plugin],buffer_number+:+buffer_name+(buffer_modes)+{buffer_nicklist_count}+buffer_zoom+buffer_filter,[lag],[hotlist],(mouse_status),completion,scroll" +rootstatus.position = bottom +rootstatus.priority = 25 +rootstatus.separator = off +rootstatus.size = 1 +rootstatus.size_max = 0 +rootstatus.type = root +title.color_bg = 235 +title.color_delim = lightcyan +title.color_fg = default +title.conditions = "" +title.filling_left_right = vertical +title.filling_top_bottom = horizontal +title.hidden = off +title.items = "buffer_title" +title.position = top +title.priority = 500 +title.separator = off +title.size = 0 +title.size_max = 0 +title.type = window + +[layout] +default.buffer = "core;weechat;1" +default.buffer = "perl;highmon;1" +default.buffer = "irc;server.tilde;1" +default.buffer = "irc;tilde.#meta;2" +default.buffer = "irc;tilde.#team;3" +default.window = "1;0;15;1;-;-" +default.window = "2;1;0;0;irc;tilde.#team" +default.window = "3;1;0;0;core;weechat" +default.current = on + +[notify] + +[filter] + +[key] +ctrl-? = "/input delete_previous_char" +ctrl-A = "/input move_beginning_of_line" +ctrl-B = "/input move_previous_char" +ctrl-C_ = "/input insert \x1F" +ctrl-Cb = "/input insert \x02" +ctrl-Cc = "/input insert \x03" +ctrl-Ci = "/input insert \x1D" +ctrl-Co = "/input insert \x0F" +ctrl-Cv = "/input insert \x16" +ctrl-D = "/input delete_next_char" +ctrl-E = "/input move_end_of_line" +ctrl-F = "/input move_next_char" +ctrl-H = "/input delete_previous_char" +ctrl-I = "/input complete_next" +ctrl-J = "/input return" +ctrl-K = "/input delete_end_of_line" +ctrl-L = "/window refresh" +ctrl-M = "/input return" +ctrl-N = "/buffer +1" +ctrl-P = "/buffer -1" +ctrl-R = "/input search_text" +ctrl-Sctrl-U = "/input set_unread" +ctrl-T = "/input transpose_chars" +ctrl-U = "/input delete_beginning_of_line" +ctrl-W = "/input delete_previous_word" +ctrl-X = "/input switch_active_buffer" +ctrl-Y = "/input clipboard_paste" +meta-meta2-1~ = "/window scroll_top" +meta-meta2-23~ = "/bar scroll nicklist * b" +meta-meta2-24~ = "/bar scroll nicklist * e" +meta-meta2-4~ = "/window scroll_bottom" +meta-meta2-5~ = "/window scroll_up" +meta-meta2-6~ = "/window scroll_down" +meta-meta2-7~ = "/window scroll_top" +meta-meta2-8~ = "/window scroll_bottom" +meta-meta2-A = "/buffer -1" +meta-meta2-B = "/buffer +1" +meta-meta2-C = "/buffer +1" +meta-meta2-D = "/buffer -1" +meta-- = "/filter toggle @" +meta-/ = "/input jump_last_buffer_displayed" +meta-0 = "/buffer *10" +meta-1 = "/buffer *1" +meta-2 = "/buffer *2" +meta-3 = "/buffer *3" +meta-4 = "/buffer *4" +meta-5 = "/buffer *5" +meta-6 = "/buffer *6" +meta-7 = "/buffer *7" +meta-8 = "/buffer *8" +meta-9 = "/buffer *9" +meta-< = "/input jump_previously_visited_buffer" +meta-= = "/filter toggle" +meta-> = "/input jump_next_visited_buffer" +meta-OA = "/input history_global_previous" +meta-OB = "/input history_global_next" +meta-OC = "/input move_next_word" +meta-OD = "/input move_previous_word" +meta-OF = "/input move_end_of_line" +meta-OH = "/input move_beginning_of_line" +meta-Oa = "/input history_global_previous" +meta-Ob = "/input history_global_next" +meta-Oc = "/input move_next_word" +meta-Od = "/input move_previous_word" +meta2-15~ = "/buffer -1" +meta2-17~ = "/buffer +1" +meta2-18~ = "/window -1" +meta2-19~ = "/window +1" +meta2-1;3A = "/buffer -1" +meta2-1;3B = "/buffer +1" +meta2-1;3C = "/buffer +1" +meta2-1;3D = "/buffer -1" +meta2-1;3F = "/window scroll_bottom" +meta2-1;3H = "/window scroll_top" +meta2-1;5A = "/input history_global_previous" +meta2-1;5B = "/input history_global_next" +meta2-1;5C = "/input move_next_word" +meta2-1;5D = "/input move_previous_word" +meta2-1~ = "/input move_beginning_of_line" +meta2-200~ = "/input paste_start" +meta2-201~ = "/input paste_stop" +meta2-20~ = "/bar scroll title * -30%" +meta2-21~ = "/bar scroll title * +30%" +meta2-23;3~ = "/bar scroll nicklist * b" +meta2-23~ = "/bar scroll nicklist * -100%" +meta2-24;3~ = "/bar scroll nicklist * e" +meta2-24~ = "/bar scroll nicklist * +100%" +meta2-3~ = "/input delete_next_char" +meta2-4~ = "/input move_end_of_line" +meta2-5;3~ = "/window scroll_up" +meta2-5~ = "/window page_up" +meta2-6;3~ = "/window scroll_down" +meta2-6~ = "/window page_down" +meta2-7~ = "/input move_beginning_of_line" +meta2-8~ = "/input move_end_of_line" +meta2-A = "/input history_previous" +meta2-B = "/input history_next" +meta2-C = "/input move_next_char" +meta2-D = "/input move_previous_char" +meta2-F = "/input move_end_of_line" +meta2-G = "/window page_down" +meta2-H = "/input move_beginning_of_line" +meta2-I = "/window page_up" +meta2-Z = "/input complete_previous" +meta2-[E = "/buffer -1" +meta-_ = "/input redo" +meta-a = "/input jump_smart" +meta-b = "/input move_previous_word" +meta-d = "/input delete_next_word" +meta-f = "/input move_next_word" +meta-h = "/input hotlist_clear" +meta-jmeta-f = "/buffer -" +meta-jmeta-l = "/buffer +" +meta-jmeta-r = "/server raw" +meta-jmeta-s = "/server jump" +meta-j01 = "/buffer 1" +meta-j02 = "/buffer 2" +meta-j03 = "/buffer 3" +meta-j04 = "/buffer 4" +meta-j05 = "/buffer 5" +meta-j06 = "/buffer 6" +meta-j07 = "/buffer 7" +meta-j08 = "/buffer 8" +meta-j09 = "/buffer 9" +meta-j10 = "/buffer 10" +meta-j11 = "/buffer 11" +meta-j12 = "/buffer 12" +meta-j13 = "/buffer 13" +meta-j14 = "/buffer 14" +meta-j15 = "/buffer 15" +meta-j16 = "/buffer 16" +meta-j17 = "/buffer 17" +meta-j18 = "/buffer 18" +meta-j19 = "/buffer 19" +meta-j20 = "/buffer 20" +meta-j21 = "/buffer 21" +meta-j22 = "/buffer 22" +meta-j23 = "/buffer 23" +meta-j24 = "/buffer 24" +meta-j25 = "/buffer 25" +meta-j26 = "/buffer 26" +meta-j27 = "/buffer 27" +meta-j28 = "/buffer 28" +meta-j29 = "/buffer 29" +meta-j30 = "/buffer 30" +meta-j31 = "/buffer 31" +meta-j32 = "/buffer 32" +meta-j33 = "/buffer 33" +meta-j34 = "/buffer 34" +meta-j35 = "/buffer 35" +meta-j36 = "/buffer 36" +meta-j37 = "/buffer 37" +meta-j38 = "/buffer 38" +meta-j39 = "/buffer 39" +meta-j40 = "/buffer 40" +meta-j41 = "/buffer 41" +meta-j42 = "/buffer 42" +meta-j43 = "/buffer 43" +meta-j44 = "/buffer 44" +meta-j45 = "/buffer 45" +meta-j46 = "/buffer 46" +meta-j47 = "/buffer 47" +meta-j48 = "/buffer 48" +meta-j49 = "/buffer 49" +meta-j50 = "/buffer 50" +meta-j51 = "/buffer 51" +meta-j52 = "/buffer 52" +meta-j53 = "/buffer 53" +meta-j54 = "/buffer 54" +meta-j55 = "/buffer 55" +meta-j56 = "/buffer 56" +meta-j57 = "/buffer 57" +meta-j58 = "/buffer 58" +meta-j59 = "/buffer 59" +meta-j60 = "/buffer 60" +meta-j61 = "/buffer 61" +meta-j62 = "/buffer 62" +meta-j63 = "/buffer 63" +meta-j64 = "/buffer 64" +meta-j65 = "/buffer 65" +meta-j66 = "/buffer 66" +meta-j67 = "/buffer 67" +meta-j68 = "/buffer 68" +meta-j69 = "/buffer 69" +meta-j70 = "/buffer 70" +meta-j71 = "/buffer 71" +meta-j72 = "/buffer 72" +meta-j73 = "/buffer 73" +meta-j74 = "/buffer 74" +meta-j75 = "/buffer 75" +meta-j76 = "/buffer 76" +meta-j77 = "/buffer 77" +meta-j78 = "/buffer 78" +meta-j79 = "/buffer 79" +meta-j80 = "/buffer 80" +meta-j81 = "/buffer 81" +meta-j82 = "/buffer 82" +meta-j83 = "/buffer 83" +meta-j84 = "/buffer 84" +meta-j85 = "/buffer 85" +meta-j86 = "/buffer 86" +meta-j87 = "/buffer 87" +meta-j88 = "/buffer 88" +meta-j89 = "/buffer 89" +meta-j90 = "/buffer 90" +meta-j91 = "/buffer 91" +meta-j92 = "/buffer 92" +meta-j93 = "/buffer 93" +meta-j94 = "/buffer 94" +meta-j95 = "/buffer 95" +meta-j96 = "/buffer 96" +meta-j97 = "/buffer 97" +meta-j98 = "/buffer 98" +meta-j99 = "/buffer 99" +meta-k = "/input grab_key_command" +meta-l = "/window bare" +meta-m = "/mute mouse toggle" +meta-n = "/window scroll_next_highlight" +meta-p = "/window scroll_previous_highlight" +meta-r = "/input delete_line" +meta-s = "/mute aspell toggle" +meta-u = "/window scroll_unread" +meta-wmeta-meta2-A = "/window up" +meta-wmeta-meta2-B = "/window down" +meta-wmeta-meta2-C = "/window right" +meta-wmeta-meta2-D = "/window left" +meta-wmeta2-1;3A = "/window up" +meta-wmeta2-1;3B = "/window down" +meta-wmeta2-1;3C = "/window right" +meta-wmeta2-1;3D = "/window left" +meta-wmeta-b = "/window balance" +meta-wmeta-s = "/window swap" +meta-x = "/input zoom_merged_buffer" +meta-z = "/window zoom" +ctrl-_ = "/input undo" + +[key_search] +ctrl-I = "/input search_switch_where" +ctrl-J = "/input search_stop" +ctrl-M = "/input search_stop" +ctrl-R = "/input search_switch_regex" +meta2-A = "/input search_previous" +meta2-B = "/input search_next" +meta-c = "/input search_switch_case" + +[key_cursor] +ctrl-J = "/cursor stop" +ctrl-M = "/cursor stop" +meta-meta2-A = "/cursor move area_up" +meta-meta2-B = "/cursor move area_down" +meta-meta2-C = "/cursor move area_right" +meta-meta2-D = "/cursor move area_left" +meta2-1;3A = "/cursor move area_up" +meta2-1;3B = "/cursor move area_down" +meta2-1;3C = "/cursor move area_right" +meta2-1;3D = "/cursor move area_left" +meta2-A = "/cursor move up" +meta2-B = "/cursor move down" +meta2-C = "/cursor move right" +meta2-D = "/cursor move left" +@item(buffer_nicklist):K = "/window ${_window_number};/kickban ${nick}" +@item(buffer_nicklist):b = "/window ${_window_number};/ban ${nick}" +@item(buffer_nicklist):k = "/window ${_window_number};/kick ${nick}" +@item(buffer_nicklist):q = "/window ${_window_number};/query ${nick};/cursor stop" +@item(buffer_nicklist):w = "/window ${_window_number};/whois ${nick}" +@chat:Q = "hsignal:chat_quote_time_prefix_message;/cursor stop" +@chat:m = "hsignal:chat_quote_message;/cursor stop" +@chat:q = "hsignal:chat_quote_prefix_message;/cursor stop" + +[key_mouse] +@bar(buflist):ctrl-wheeldown = "hsignal:buflist_mouse" +@bar(buflist):ctrl-wheelup = "hsignal:buflist_mouse" +@bar(input):button2 = "/input grab_mouse_area" +@bar(nicklist):button1-gesture-down = "/bar scroll nicklist ${_window_number} +100%" +@bar(nicklist):button1-gesture-down-long = "/bar scroll nicklist ${_window_number} e" +@bar(nicklist):button1-gesture-up = "/bar scroll nicklist ${_window_number} -100%" +@bar(nicklist):button1-gesture-up-long = "/bar scroll nicklist ${_window_number} b" +@chat(perl.iset):button1 = "hsignal:iset_mouse" +@chat(perl.iset):button2* = "hsignal:iset_mouse" +@chat(perl.iset):wheeldown = "/repeat 5 /iset **down" +@chat(perl.iset):wheelup = "/repeat 5 /iset **up" +@chat(script.scripts):button1 = "/window ${_window_number};/script go ${_chat_line_y}" +@chat(script.scripts):button2 = "/window ${_window_number};/script go ${_chat_line_y};/script installremove -q ${script_name_with_extension}" +@chat(script.scripts):wheeldown = "/script down 5" +@chat(script.scripts):wheelup = "/script up 5" +@item(buffer_nicklist):button1 = "/window ${_window_number};/query ${nick}" +@item(buffer_nicklist):button1-gesture-left = "/window ${_window_number};/kick ${nick}" +@item(buffer_nicklist):button1-gesture-left-long = "/window ${_window_number};/kickban ${nick}" +@item(buffer_nicklist):button2 = "/window ${_window_number};/whois ${nick}" +@item(buffer_nicklist):button2-gesture-left = "/window ${_window_number};/ban ${nick}" +@bar:wheeldown = "/bar scroll ${_bar_name} ${_window_number} +20%" +@bar:wheelup = "/bar scroll ${_bar_name} ${_window_number} -20%" +@chat:button1 = "/window ${_window_number}" +@chat:button1-gesture-left = "/window ${_window_number};/buffer -1" +@chat:button1-gesture-left-long = "/window ${_window_number};/buffer 1" +@chat:button1-gesture-right = "/window ${_window_number};/buffer +1" +@chat:button1-gesture-right-long = "/window ${_window_number};/input jump_last_buffer" +@chat:ctrl-wheeldown = "/window scroll_horiz -window ${_window_number} +10%" +@chat:ctrl-wheelup = "/window scroll_horiz -window ${_window_number} -10%" +@chat:wheeldown = "/window scroll_down -window ${_window_number}" +@chat:wheelup = "/window scroll_up -window ${_window_number}" +@*:button3 = "/cursor go ${_x},${_y}" diff --git a/.weechat/xfer.conf b/.weechat/xfer.conf new file mode 100644 index 0000000..10d14d7 --- /dev/null +++ b/.weechat/xfer.conf @@ -0,0 +1,39 @@ +# +# xfer.conf -- weechat v1.0.1 +# + +[look] +auto_open_buffer = on +progress_bar_size = 20 +pv_tags = "notify_private" + +[color] +status_aborted = lightred +status_active = lightblue +status_connecting = 130 +status_done = lightgreen +status_failed = lightred +status_waiting = lightcyan +text = default +text_bg = default +text_selected = white + +[network] +blocksize = 65536 +fast_send = on +own_ip = "" +port_range = "" +speed_limit = 0 +timeout = 300 + +[file] +auto_accept_chats = off +auto_accept_files = off +auto_accept_nicks = "" +auto_check_crc32 = off +auto_rename = on +auto_resume = on +convert_spaces = on +download_path = "%h/xfer" +upload_path = "~" +use_nick_in_filename = on diff --git a/public_html/index.php b/public_html/index.php new file mode 100755 index 0000000..52b0ce8 --- /dev/null +++ b/public_html/index.php @@ -0,0 +1,28 @@ + + + + + + + + + + ~<?=$user?> | tilde.center + + + +
+
+ return to tilde.center +

+ ~ +

+
+

+ Login to tilde.center to change this page from the file: + $HOME/public_html/index.html +

+
+ + +