summaryrefslogtreecommitdiff
path: root/doc/en/weechat_scripting.en.asciidoc
blob: 956b3989fc83125f881e148390776f43152127dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
= WeeChat scripting guide
:author: Sébastien Helleu
:email: flashcode@flashtux.org
:lang: en
:toc:
:toclevels: 3


This manual documents WeeChat chat client, it is part of WeeChat.

Latest version of this document can be found on this page:
https://weechat.org/doc


[[introduction]]
== Introduction

WeeChat (Wee Enhanced Environment for Chat) is a free chat client, fast and
light, designed for many operating systems.

This manual documents way to write scripts for WeeChat, using one of supported
script languages:

* python
* perl
* ruby
* lua
* tcl
* guile (scheme)

[NOTE]
Almost all examples in this doc are written in Python, but API is the same for
other languages.

[[scripts_in_weechat]]
== Scripts in WeeChat

[[languages_specificities]]
=== Languages specificities

==== Python

* You have to `import weechat`
* Functions `print*` are called `prnt*` in python (because 'print' is reserved
  keyword)
* Functions are called with `weechat.xxx(arg1, arg2, ...)`

==== Perl

* Functions are called with `weechat::xxx(arg1, arg2, ...);`

==== Ruby

* You have to define 'weechat_init' and call 'register' inside
* Functions are called with `Weechat.xxx(arg1, arg2, ...)`
* Due to a limitation of Ruby (15 arguments max by function), the function
  `Weechat.config_new_option` receives the callbacks in an array of 6 strings
  (3 callbacks + 3 data strings), so a call to this function looks like:

[source,ruby]
----
Weechat.config_new_option(config, section, "name", "string", "description of option", "", 0, 0,
                          "value", "value", 0, ["check_cb", "", "change_cb", "", "delete_cb", ""])
----

==== Lua

* Functions are called with `weechat.xxx(arg1, arg2, ...)`

==== Tcl

* Functions are called with `weechat::xxx arg1 arg2 ...`

==== Guile (scheme)

* Functions are called with `(weechat:xxx arg1 arg2 ...)`
* Following functions take one list of arguments (instead of many arguments
  for other functions), because number of arguments exceed number of allowed
  arguments in Guile:
** config_new_section
** config_new_option
** bar_new

[[register_function]]
=== Register function

All WeeChat scripts must "register" themselves to WeeChat, and this must be
first WeeChat function called in script.

Prototype:

[source,python]
----
weechat.register(name, author, version, license, description, shutdown_function, charset)
----

Arguments:

* 'name': string, internal name of script
* 'author': string, author name
* 'version': string, script version
* 'license': string, script license
* 'description': string, short description of script
* 'shutdown_function': string, name of function called when script is unloaded
  (can be empty string)
* 'charset': string, script charset (if your script is UTF-8, you can use blank
  value here, because UTF-8 is default charset)

Example of script, for each language:

* python:

[source,python]
----
import weechat

weechat.register("test_python", "FlashCode", "1.0", "GPL3", "Test script", "", "")
weechat.prnt("", "Hello, from python script!")
----

* perl:

[source,perl]
----
weechat::register("test_perl", "FlashCode", "1.0", "GPL3", "Test script", "", "");
weechat::print("", "Hello, from perl script!");
----

* ruby:

[source,ruby]
----
def weechat_init
  Weechat.register("test_ruby", "FlashCode", "1.0", "GPL3", "Test script", "", "")
  Weechat.print("", "Hello, from ruby script!")
  return Weechat::WEECHAT_RC_OK
end
----

* lua:

[source,lua]
----
weechat.register("test_lua", "FlashCode", "1.0", "GPL3", "Test script", "", "")
weechat.print("", "Hello, from lua script!")
----

* tcl:

[source,tcl]
----
weechat::register "test_tcl" "FlashCode" "1.0" "GPL3" "Test script" "" ""
weechat::print "" "Hello, from tcl script!"
----

* guile (scheme):

[source,lisp]
----
(weechat:register "test_scheme" "FlashCode" "1.0" "GPL3" "Test script" "" "")
(weechat:print "" "Hello, from scheme script!")
----

[[load_script]]
=== Load script

It is recommended to use the "script" plugin to load scripts, for example:

----
/script load script.py
/script load script.pl
/script load script.rb
/script load script.lua
/script load script.tcl
/script load script.scm
----

Each language has also its own command:

----
/python load python/script.py
/perl load perl/script.pl
/ruby load ruby/script.rb
/lua load lua/script.lua
/tcl load tcl/script.tcl
/guile load guile/script.scm
----

You can make link in directory 'language/autoload' to autoload script when
WeeChat is starting.

For example with Python:

----
$ cd ~/.weechat/python/autoload
$ ln -s ../script.py
----

[NOTE]
When installing a script with command `/script install` the link in 'autoload'
directory is automatically created.

[[differences_with_c_api]]
== Differences with C API

Script API is almost the same as C plugin API.
You can look at 'WeeChat Plugin API Reference' for detail about each function
in API: prototype, arguments, return values, examples.

It's important to make difference between a 'plugin' and a 'script': a
'plugin' is a binary file compiled and loaded with command `/plugin`, whereas
a 'script' is a text file loaded with a plugin like 'python' with command
`/python`.

When your script 'test.py' calls a WeeChat API function, path is like that:

....
               ┌──────────────────────┐        ╔══════════════════╗
               │     python plugin    │        ║  WeeChat "core"  ║
               ├────────────┬─────────┤        ╟─────────┐        ║
test.py ─────► │ script API │  C API  │ ─────► ║  C API  │        ║
               └────────────┴─────────┘        ╚═════════╧════════╝
....

When WeeChat calls a callback in your script 'test.py', it's reverse of
previous path:

....
╔══════════════════╗        ┌──────────────────────┐
║  WeeChat "core"  ║        │     python plugin    │
║        ┌─────────╢        ├─────────┬────────────┤
║        │  C API  ║ ─────► │  C API  │ script API │ ─────► test.py
╚════════╧═════════╝        └─────────┴────────────┘
....

[[pointers]]
=== Pointers

As you probably know, there is not really "pointers" in scripts. So when API
functions return pointer, it is converted to string for script.

For example, if function return pointer 0x1234ab56, script will get string
"0x1234ab56".

And when an API function expects a pointer in arguments, script must give that
string value. C plugin will convert it to real pointer before calling C API
function.

Empty string or "0x0" are allowed, they means NULL in C.
For example, to print data on core buffer (WeeChat main buffer), you can do:

[source,python]
----
weechat.prnt("", "hi!")
----

[WARNING]
In many functions, for speed reasons, WeeChat does not check if your pointer
is correct or not. It's your job to check you're giving a valid pointer,
otherwise you may see a nice crash report ;)

[[callbacks]]
=== Callbacks

Almost all WeeChat callbacks must return WEECHAT_RC_OK or WEECHAT_RC_ERROR
(exception is modifier callback, which returns a string).

C callbacks are using a "data" argument, which is a pointer. In script API,
this "data" is a string with a any value (it's not a pointer).

Example of callback, for each language:

* python:

[source,python]
----
def timer_cb(data, remaining_calls):
    weechat.prnt("", "timer! data=%s" % data)
    return weechat.WEECHAT_RC_OK

weechat.hook_timer(1000, 0, 1, "timer_cb", "test")
----

* perl:

[source,perl]
----
sub timer_cb {
    my ($data, $remaining_calls) = @_;
    weechat::print("", "timer! data=$data");
    return weechat::WEECHAT_RC_OK;
}

weechat::hook_timer(1000, 0, 1, "timer_cb", "test");
----

* ruby:

[source,ruby]
----
def timer_cb(data, remaining_calls)
  Weechat.print("", "timer! data=#{data}");
  return Weechat::WEECHAT_RC_OK
end

Weechat.hook_timer(1000, 0, 1, "timer_cb", "test");
----

* lua:

[source,lua]
----
function timer_cb(data, remaining_calls)
    weechat.print("", "timer! data="..data)
    return weechat.WEECHAT_RC_OK
end

weechat.hook_timer(1000, 0, 1, "timer_cb", "test")
----

* tcl:

[source,tcl]
----
proc timer_cb { data remaining_calls } {
    weechat::print {} "timer! data=$data"
    return $::weechat::WEECHAT_RC_OK
}

weechat::hook_timer 1000 0 1 timer_cb test
----

* guile (scheme):

[source,lisp]
----
(define (timer_cb data remaining_calls)
  (weechat:print "" (string-append "timer! data=" data))
  weechat:WEECHAT_RC_OK
)

(weechat:hook_timer 1000 0 1 "timer_cb" "test")
----

[[script_api]]
== Script API

For more information about functions in API, please read
'WeeChat Plugin API Reference'.

[[script_api_functions]]
=== Functions

List of functions in script API:

[width="100%",cols="^1,10",options="header"]
|===
| Category            | Functions
| general             |
  register
| plugins             |
  plugin_get_name
| strings             |
  charset_set, iconv_to_internal, iconv_from_internal, gettext, ngettext, +
  strlen_screen, string_match, string_has_highlight, string_has_highlight_regex,
  string_mask_to_regex, string_remove_color, string_is_command_char,
  string_input_for_buffer, string_eval_expression
| directories         |
  mkdir_home, mkdir, mkdir_parents
| sorted lists        |
  list_new, list_add, list_search, list_search_pos, list_casesearch,
  list_casesearch_pos, list_get, list_set, list_next, list_prev, list_string,
  list_size, list_remove, list_remove_all, list_free
| configuration files |
  config_new, config_new_section, config_search_section, config_new_option,
  config_search_option, +
  config_string_to_boolean, config_option_reset, config_option_set,
  config_option_set_null, config_option_unset, config_option_rename,
  config_option_is_null, config_option_default_is_null, +
  config_boolean, config_boolean_default, config_integer, config_integer_default,
  config_string, config_string_default, config_color, config_color_default, +
  config_write_option, config_write_line, config_write, config_read,
  config_reload, +
  config_option_free, config_section_free_options, config_section_free,
  config_free, +
  config_get, config_get_plugin, config_is_set_plugin, config_set_plugin,
  config_set_desc_plugin, config_unset_plugin
| key bindings        |
  key_bind, key_unbind
| display             |
  prefix, color, print (for python: prnt), print_date_tags (for python:
  prnt_date_tags), print_y (for python: prnt_y), log_print
| hooks               |
  hook_command, hook_command_run, hook_timer, hook_fd, hook_process,
  hook_process_hashtable, hook_connect, hook_print, hook_signal,
  hook_signal_send, hook_hsignal, hook_hsignal_send, hook_config,
  hook_completion, hook_completion_list_add, hook_modifier, hook_modifier_exec,
  hook_info, hook_info_hashtable, hook_infolist, hook_focus, hook_set, unhook,
  unhook_all
| buffers             |
  buffer_new, current_buffer, buffer_search, buffer_search_main, buffer_clear,
  buffer_close, buffer_merge, buffer_unmerge, buffer_get_integer,
  buffer_get_string, buffer_get_pointer, buffer_set,
  buffer_string_replace_local_var, buffer_match_list
| windows             |
  current_window, window_search_with_buffer, window_get_integer,
  window_get_string, window_get_pointer, window_set_title
| nicklist            |
  nicklist_add_group, nicklist_search_group, nicklist_add_nick,
  nicklist_search_nick, nicklist_remove_group, nicklist_remove_nick,
  nicklist_remove_all, nicklist_group_get_integer, nicklist_group_get_string,
  nicklist_group_get_pointer, nicklist_group_set, nicklist_nick_get_integer,
  nicklist_nick_get_string, nicklist_nick_get_pointer, nicklist_nick_set
| bars                |
  bar_item_search, bar_item_new, bar_item_update, bar_item_remove, bar_search,
  bar_new, bar_set, bar_update, bar_remove
| commands            |
  command
| infos               |
  info_get, info_get_hashtable
| infolists           |
  infolist_new, infolist_new_item, infolist_new_var_integer,
  infolist_new_var_string, infolist_new_var_pointer, infolist_new_var_time, +
  infolist_get, infolist_next, infolist_prev, infolist_reset_item_cursor, +
  infolist_fields, infolist_integer, infolist_string, infolist_pointer, +
  infolist_time, infolist_free
| hdata               |
  hdata_get, hdata_get_var_offset, hdata_get_var_type_string,
  hdata_get_var_array_size, hdata_get_var_array_size_string,
  hdata_get_var_hdata, hdata_get_list, hdata_check_pointer, hdata_move,
  hdata_search, hdata_char, hdata_integer, hdata_long, hdata_string,
  hdata_pointer, hdata_time, hdata_hashtable, hdata_update, hdata_get_string
| upgrade             |
  upgrade_new, upgrade_write_object, upgrade_read, upgrade_close
|===

[[script_api_constants]]
=== Constants

List of constants in script API:

[width="100%",cols="^1,10",options="header"]
|===
| Category            | Constants
| return codes        |
  WEECHAT_RC_OK, WEECHAT_RC_OK_EAT, WEECHAT_RC_ERROR
| configuration files |
  WEECHAT_CONFIG_READ_OK, WEECHAT_CONFIG_READ_MEMORY_ERROR,
  WEECHAT_CONFIG_READ_FILE_NOT_FOUND, WEECHAT_CONFIG_WRITE_OK,
  WEECHAT_CONFIG_WRITE_ERROR, WEECHAT_CONFIG_WRITE_MEMORY_ERROR, +
  WEECHAT_CONFIG_OPTION_SET_OK_CHANGED, WEECHAT_CONFIG_OPTION_SET_OK_SAME_VALUE,
  WEECHAT_CONFIG_OPTION_SET_ERROR, WEECHAT_CONFIG_OPTION_SET_OPTION_NOT_FOUND,
  WEECHAT_CONFIG_OPTION_UNSET_OK_NO_RESET, WEECHAT_CONFIG_OPTION_UNSET_OK_RESET,
  WEECHAT_CONFIG_OPTION_UNSET_OK_REMOVED, WEECHAT_CONFIG_OPTION_UNSET_ERROR
| sorted lists        |
  WEECHAT_LIST_POS_SORT, WEECHAT_LIST_POS_BEGINNING, WEECHAT_LIST_POS_END
| hotlist             |
  WEECHAT_HOTLIST_LOW, WEECHAT_HOTLIST_MESSAGE, WEECHAT_HOTLIST_PRIVATE,
  WEECHAT_HOTLIST_HIGHLIGHT
| hook process        |
  WEECHAT_HOOK_PROCESS_RUNNING, WEECHAT_HOOK_PROCESS_ERROR
| hook connect        |
  WEECHAT_HOOK_CONNECT_OK, WEECHAT_HOOK_CONNECT_ADDRESS_NOT_FOUND,
  WEECHAT_HOOK_CONNECT_IP_ADDRESS_NOT_FOUND, WEECHAT_HOOK_CONNECT_CONNECTION_REFUSED,
  WEECHAT_HOOK_CONNECT_PROXY_ERROR, WEECHAT_HOOK_CONNECT_LOCAL_HOSTNAME_ERROR,
  WEECHAT_HOOK_CONNECT_GNUTLS_INIT_ERROR, WEECHAT_HOOK_CONNECT_GNUTLS_HANDSHAKE_ERROR,
  WEECHAT_HOOK_CONNECT_MEMORY_ERROR, WEECHAT_HOOK_CONNECT_TIMEOUT,
  WEECHAT_HOOK_CONNECT_SOCKET_ERROR
| hook signal         |
  WEECHAT_HOOK_SIGNAL_STRING, WEECHAT_HOOK_SIGNAL_INT, WEECHAT_HOOK_SIGNAL_POINTER
|===

[[common_tasks]]
== Common tasks

This chapter shows some common tasks, with examples.
Only partial things in API are used here, for full reference, see
'WeeChat Plugin API Reference'.

[[buffers]]
=== Buffers

[[buffers_display_messages]]
==== Display messages

An empty string is often used to work with WeeChat core buffer. For other
buffers, you must give pointer (as string, see <<pointers,pointers>>).

Examples:

[source,python]
----
# display "hello" on core buffer
weechat.prnt("", "hello")

# display "hello" on core buffer, but do not write it to log file
# (version >= 0.3.3 only)
weechat.prnt_date_tags("", 0, "no_log", "hello")

# display prefix "==>" and message "hello" on current buffer
# (prefix and message must be separated by tab)
weechat.prnt(weechat.current_buffer(), "==>\thello")

# display error message on core buffer (with error prefix)
weechat.prnt("", "%swrong arguments" % weechat.prefix("error"))

# display message with color on core buffer
weechat.prnt("", "text %syellow on blue" % weechat.color("yellow,blue"))

# search buffer and display message
# (full name of buffer is plugin.name, for example: "irc.freenode.#weechat")
buffer = weechat.buffer_search("irc", "freenode.#weechat")
weechat.prnt(buffer, "message on #weechat channel")

# other solution to find an IRC buffer (better)
# (note that server and channel are separated by a comma)
buffer = weechat.info_get("irc_buffer", "freenode,#weechat")
weechat.prnt(buffer, "message on #weechat channel")
----

[NOTE]
Print function is called `print` in Perl/Ruby/Lua/Tcl and `prnt` in Python.

[[buffers_send_text]]
==== Send text to buffer

You can send text or command to a buffer. This is exactly like if you type text
on command line and press [Enter].

Examples:

[source,python]
----
# execute command "/help" on current buffer (result is on core buffer)
weechat.command("", "/help")

# send "hello" to #weechat IRC channel (users on channel will see message)
buffer = weechat.info_get("irc_buffer", "freenode,#weechat")
weechat.command(buffer, "hello")
----

[[buffers_new]]
==== Create new buffer

You can create a new buffer in your script, then use it for displaying messages.

Two callbacks can be called (they are optional): one for input data (when you
type some text and press [Enter] on buffer), the other is called when buffer is
closed (for example by `/buffer close`).

Example:

[source,python]
----
# callback for data received in input
def buffer_input_cb(data, buffer, input_data):
    # ...
    return weechat.WEECHAT_RC_OK

# callback called when buffer is closed
def buffer_close_cb(data, buffer):
    # ...
    return weechat.WEECHAT_RC_OK

# create buffer
buffer = weechat.buffer_new("mybuffer", "buffer_input_cb", "", "buffer_close_cb", "")

# set title
weechat.buffer_set(buffer, "title", "This is title for my buffer.")

# disable logging, by setting local variable "no_log" to "1"
weechat.buffer_set(buffer, "localvar_set_no_log", "1")
----

[[buffers_properties]]
==== Buffer properties

You can read buffer properties, as string, integer or pointer.

Examples:

[source,python]
----
buffer = weechat.current_buffer()

number = weechat.buffer_get_integer(buffer, "number")
name = weechat.buffer_get_string(buffer, "name")
short_name = weechat.buffer_get_string(buffer, "short_name")
----

It is possible to add, read or delete local variables in buffer:

[source,python]
----
# add local variable
weechat.buffer_set(buffer, "localvar_set_myvar", "my_value")

# read local variable
myvar = weechat.buffer_get_string(buffer, "localvar_myvar")

# delete local variable
weechat.buffer_set(buffer, "localvar_del_myvar", "")
----

To see local variables of a buffer, do this command in WeeChat:

----
/buffer localvar
----

[[hooks]]
=== Hooks

[[hook_command]]
==== Add new command

Add a custom command with `hook_command`. You can use a custom completion
template to complete arguments of your command.

Example:

[source,python]
----
def my_command_cb(data, buffer, args):
    # ...
    return weechat.WEECHAT_RC_OK

hook = weechat.hook_command("myfilter", "description of myfilter",
    "[list] | [enable|disable|toggle [name]] | [add name plugin.buffer tags regex] | [del name|-all]",
    "description of arguments...",
    "list"
    " || enable %(filters_names)"
    " || disable %(filters_names)"
    " || toggle %(filters_names)"
    " || add %(filters_names) %(buffers_plugins_names)|*"
    " || del %(filters_names)|-all",
    "my_command_cb", "")
----

And then in WeeChat:

----
/help myfilter

/myfilter arguments...
----

[[hook_timer]]
==== Add a timer

Add a timer with `hook_timer`.

Example:

[source,python]
----
def timer_cb(data, remaining_calls):
    # ...
    return weechat.WEECHAT_RC_OK

# timer called each minute when second is 00
weechat.hook_timer(60 * 1000, 60, 0, "timer_cb", "")
----

[[hook_process]]
==== Run a background process

You can run a background process with `hook_process`. Your callback will be
called when data is ready. It may be called many times.

For the last call to your callback, 'rc' is set to 0 or positive value, it's
return code of command.

Example:

[source,python]
----
process_output = ""

def my_process_cb(data, command, rc, out, err):
    global process_output
    if out != "":
        process_output += out
    if int(rc) >= 0:
        weechat.prnt("", process_output)
    return weechat.WEECHAT_RC_OK

weechat.hook_process("/bin/ls -l /etc", 10 * 1000, "my_process_cb", "")
----

[[url_transfer]]
==== URL transfer

_New in version 0.3.7._

To download URL (or post to URL), you have to use function `hook_process`, or
`hook_process_hashtable` if you need to set options for URL transfer.

Example of URL transfer without option: the HTML page will be received as "out"
in callback (standard output of process):

[source,python]
----
# Display current stable version of WeeChat.
weechat_version = ""

def weechat_process_cb(data, command, rc, out, err):
    global weechat_version
    if out != "":
        weechat_version += out
    if int(rc) >= 0:
        weechat.prnt("", "Current WeeChat stable is: %s" % weechat_version)
    return weechat.WEECHAT_RC_OK

weechat.hook_process("url:https://weechat.org/dev/info/stable/",
                     30 * 1000, "weechat_process_cb", "")
----

[TIP]
All infos available about WeeChat are on page https://weechat.org/dev/info

Example of URL transfer with an option: download latest WeeChat development
package in file '/tmp/weechat-devel.tar.gz':

[source,python]
----
def my_process_cb(data, command, rc, out, err):
    if int(rc) >= 0:
        weechat.prnt("", "End of transfer (rc=%s)" % rc)
    return weechat.WEECHAT_RC_OK

weechat.hook_process_hashtable("url:https://weechat.org/files/src/weechat-devel.tar.gz",
                               {"file_out": "/tmp/weechat-devel.tar.gz"},
                               30 * 1000, "my_process_cb", "")
----

For more information about URL transfer and available options, see functions
`hook_process` and `hook_process_hashtable` in 'WeeChat Plugin API Reference'.

[[config_options]]
=== Config / options

[[config_options_set_script]]
==== Set options for script

Function `config_is_set_plugin` is used to check if an option is set or not,
and `config_set_plugin` to set option.

Example:

[source,python]
----
script_options = {
    "option1" : "value1",
    "option2" : "value2",
    "option3" : "value3",
}
for option, default_value in script_options.items():
    if not weechat.config_is_set_plugin(option):
        weechat.config_set_plugin(option, default_value)
----

[[config_options_detect_changes]]
==== Detect changes

You must use `hook_config` to be notified if user changes some script options.

Example:

[source,python]
----
SCRIPT_NAME = "myscript"

# ...

def config_cb(data, option, value):
    """Callback called when a script option is changed."""
    # for example, read all script options to script variables...
    # ...
    return weechat.WEECHAT_RC_OK

# ...

weechat.hook_config("plugins.var.python." + SCRIPT_NAME + ".*", "config_cb", "")
# for other languages, change "python" with your language ("perl", "ruby", "lua" or "tcl")
----

[[config_options_weechat]]
==== Read WeeChat options

Function `config_get` returns pointer to option. Then, depending on option type,
you must call `config_string`, `config_boolean`, `config_integer` or
`config_color`.

[source,python]
----
# string
weechat.prnt("", "value of option weechat.look.item_time_format is: %s"
                 % (weechat.config_string(weechat.config_get("weechat.look.item_time_format"))))

# boolean
weechat.prnt("", "value of option weechat.look.day_change is: %d"
                 % (weechat.config_boolean(weechat.config_get("weechat.look.day_change"))))

# integer
weechat.prnt("", "value of option weechat.look.scroll_page_percent is: %d"
                 % (weechat.config_integer(weechat.config_get("weechat.look.scroll_page_percent"))))

# color
weechat.prnt("", "value of option weechat.color.chat_delimiters is: %s"
                 % (weechat.config_color(weechat.config_get("weechat.color.chat_delimiters"))))
----

[[irc]]
=== IRC

[[irc_catch_messages]]
==== Catch messages

IRC plugin sends two signals for a message received (`xxx` is IRC internal
server name, `yyy` is IRC command name like JOIN, QUIT, PRIVMSG, 301, ..):

xxxx,irc_in_yyy::
    signal sent before processing message

xxx,irc_in2_yyy::
    signal sent after processing message

[source,python]
----
def join_cb(data, signal, signal_data):
    # signal is for example: "freenode,irc_in2_join"
    # signal_data is IRC message, for example: ":nick!user@host JOIN :#channel"
    nick = weechat.info_get("irc_nick_from_host", signal_data)
    server = signal.split(",")[0]
    channel = signal_data.split(":")[-1]
    buffer = weechat.info_get("irc_buffer", "%s,%s" % (server, channel))
    if buffer:
        weechat.prnt(buffer, "Eheh, %s has joined this channel!" % nick)
    return weechat.WEECHAT_RC_OK

# it is useful here to use "*" as server, to catch JOIN messages on all IRC
# servers
weechat.hook_signal("*,irc_in2_join", "join_cb", "")
----

[[irc_modify_messages]]
==== Modify messages

IRC plugin sends a "modifier" called "irc_in_xxx" ("xxx" is IRC command) for a
message received, so that you can modify it.

[source,python]
----
def modifier_cb(data, modifier, modifier_data, string):
    # add server name to all messages received
    # (OK that's not very useful, but that's just an example!)
    return "%s %s" % (string, modifier_data)

weechat.hook_modifier("irc_in_privmsg", "modifier_cb", "")
----

[WARNING]
A malformed message could crash WeeChat or cause severe problems!

[[irc_message_parse]]
==== Parse message

_New in version 0.3.4._

You can parse an IRC message with info_hashtable called "irc_message_parse".

[source,python]
----
dict = weechat.info_get_hashtable("irc_message_parse",
                                  {"message": ":nick!user@host PRIVMSG #weechat :message here"})
weechat.prnt("", "dict: %s" % dict)

# output:
#   dict: {'nick': 'nick', 'host': 'nick!user@host', 'command': 'PRIVMSG', 'arguments': '#weechat :message here', 'channel': '#weechat'}
----

[[infos]]
=== Infos

[[infos_weechat_version]]
==== WeeChat version

The best way to check version is to ask "version_number" and make integer
comparison with hexadecimal version number.

Example:

[source,python]
----
version = weechat.info_get("version_number", "") or 0
if int(version) >= 0x00030200:
    weechat.prnt("", "This is WeeChat 0.3.2 or newer")
else:
    weechat.prnt("", "This is WeeChat 0.3.1 or older")
----

[NOTE]
Versions ≤ 0.3.1.1 return empty string for 'info_get("version_number")' so you
must check that value returned is *not* empty.

To get version as string:

[source,python]
----
# this will display for example "Version 0.3.2"
weechat.prnt("", "Version %s" % weechat.info_get("version", ""))
----

[[infos_other]]
==== Other infos

[source,python]
----
# WeeChat home directory, for example: "/home/xxxx/.weechat"
weechat.prnt("", "WeeChat home dir: %s" % weechat.info_get("weechat_dir", ""))

# keyboard inactivity
weechat.prnt("", "Inactivity since %s seconds" % weechat.info_get("inactivity", ""))
----

[[infolists]]
=== Infolists

[[infolists_read]]
==== Read an infolist

You can read infolist built by WeeChat or other plugins.

Example:

[source,python]
----
# read infolist "buffer", to get list of buffers
infolist = weechat.infolist_get("buffer", "", "")
if infolist:
    while weechat.infolist_next(infolist):
        name = weechat.infolist_string(infolist, "name")
        weechat.prnt("", "buffer: %s" % name)
    weechat.infolist_free(infolist)
----

[IMPORTANT]
Don't forget to call `infolist_free` to free memory used by infolist, because
WeeChat will not automatically free memory.