Merge branch 'vim'
[MacVim.git] / src / if_ruby.c
blobaf6eae26a16a98a626385603cc45bfe3c2404087
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Ruby interface by Shugo Maeda
6 * with improvements by SegPhault (Ryan Paul)
8 * Do ":help uganda" in Vim to read copying and usage conditions.
9 * Do ":help credits" in Vim to see a list of people who contributed.
10 * See README.txt for an overview of the Vim source code.
13 #include <stdio.h>
14 #include <string.h>
16 #ifdef _WIN32
17 # if !defined(DYNAMIC_RUBY_VER) || (DYNAMIC_RUBY_VER < 18)
18 # define NT
19 # endif
20 # ifndef DYNAMIC_RUBY
21 # define IMPORT /* For static dll usage __declspec(dllimport) */
22 # define RUBYEXTERN __declspec(dllimport)
23 # endif
24 #endif
25 #ifndef RUBYEXTERN
26 # define RUBYEXTERN extern
27 #endif
30 * This is tricky. In ruby.h there is (inline) function rb_class_of()
31 * definition. This function use these variables. But we want function to
32 * use dll_* variables.
34 #ifdef DYNAMIC_RUBY
35 # define rb_cFalseClass (*dll_rb_cFalseClass)
36 # define rb_cFixnum (*dll_rb_cFixnum)
37 # define rb_cNilClass (*dll_rb_cNilClass)
38 # define rb_cSymbol (*dll_rb_cSymbol)
39 # define rb_cTrueClass (*dll_rb_cTrueClass)
40 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
42 * On ver 1.8, all Ruby functions are exported with "__declspec(dllimport)"
43 * in ruby.h. But it causes trouble for these variables, because it is
44 * defined in this file. When defined this RUBY_EXPORT it modified to
45 * "extern" and be able to avoid this problem.
47 # define RUBY_EXPORT
48 # endif
49 #endif
51 /* suggested by Ariya Mizutani */
52 #if (_MSC_VER == 1200)
53 # undef _WIN32_WINNT
54 #endif
56 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 19) \
57 || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19)
58 # define RUBY19_OR_LATER 1
59 #endif
61 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19
62 /* Ruby 1.9 defines a number of static functions which use rb_num2long and
63 * rb_int2big */
64 # define rb_num2long rb_num2long_stub
65 # define rb_int2big rb_int2big_stub
66 #endif
68 #ifdef FEAT_GUI_MACVIM
69 # include <Ruby/ruby.h>
70 #else
71 # include <ruby.h>
72 #endif
74 #ifdef RUBY19_OR_LATER
75 # include <ruby/encoding.h>
76 #endif
78 #undef EXTERN
79 #undef _
81 /* T_DATA defined both by Ruby and Mac header files, hack around it... */
82 #if defined(MACOS_X_UNIX) || defined(macintosh)
83 # define __OPENTRANSPORT__
84 # define __OPENTRANSPORTPROTOCOL__
85 # define __OPENTRANSPORTPROVIDERS__
86 #endif
89 * Backward compatiblity for Ruby 1.8 and earlier.
90 * Ruby 1.9 does not provide STR2CSTR, instead StringValuePtr is provided.
91 * Ruby 1.9 does not provide RXXX(s)->len and RXXX(s)->ptr, instead
92 * RXXX_LEN(s) and RXXX_PTR(s) are provided.
94 #ifndef StringValuePtr
95 # define StringValuePtr(s) STR2CSTR(s)
96 #endif
97 #ifndef RARRAY_LEN
98 # define RARRAY_LEN(s) RARRAY(s)->len
99 #endif
100 #ifndef RARRAY_PTR
101 # define RARRAY_PTR(s) RARRAY(s)->ptr
102 #endif
103 #ifndef RSTRING_LEN
104 # define RSTRING_LEN(s) RSTRING(s)->len
105 #endif
106 #ifndef RSTRING_PTR
107 # define RSTRING_PTR(s) RSTRING(s)->ptr
108 #endif
110 #include "vim.h"
111 #include "version.h"
113 #if defined(PROTO) && !defined(FEAT_RUBY)
114 /* Define these to be able to generate the function prototypes. */
115 # define VALUE int
116 # define RUBY_DATA_FUNC int
117 #endif
119 static int ruby_initialized = 0;
120 static VALUE objtbl;
122 static VALUE mVIM;
123 static VALUE cBuffer;
124 static VALUE cVimWindow;
125 static VALUE eDeletedBufferError;
126 static VALUE eDeletedWindowError;
128 static int ensure_ruby_initialized(void);
129 static void error_print(int);
130 static void ruby_io_init(void);
131 static void ruby_vim_init(void);
133 #if defined(DYNAMIC_RUBY) || defined(PROTO)
134 #ifdef PROTO
135 # define HINSTANCE int /* for generating prototypes */
136 #endif
139 * Wrapper defines
141 #define rb_assoc_new dll_rb_assoc_new
142 #define rb_cObject (*dll_rb_cObject)
143 #define rb_check_type dll_rb_check_type
144 #define rb_class_path dll_rb_class_path
145 #define rb_data_object_alloc dll_rb_data_object_alloc
146 #define rb_define_class_under dll_rb_define_class_under
147 #define rb_define_const dll_rb_define_const
148 #define rb_define_global_function dll_rb_define_global_function
149 #define rb_define_method dll_rb_define_method
150 #define rb_define_module dll_rb_define_module
151 #define rb_define_module_function dll_rb_define_module_function
152 #define rb_define_singleton_method dll_rb_define_singleton_method
153 #define rb_define_virtual_variable dll_rb_define_virtual_variable
154 #define rb_stdout (*dll_rb_stdout)
155 #define rb_eArgError (*dll_rb_eArgError)
156 #define rb_eIndexError (*dll_rb_eIndexError)
157 #define rb_eRuntimeError (*dll_rb_eRuntimeError)
158 #define rb_eStandardError (*dll_rb_eStandardError)
159 #define rb_eval_string_protect dll_rb_eval_string_protect
160 #define rb_global_variable dll_rb_global_variable
161 #define rb_hash_aset dll_rb_hash_aset
162 #define rb_hash_new dll_rb_hash_new
163 #define rb_inspect dll_rb_inspect
164 #define rb_int2inum dll_rb_int2inum
165 #define rb_lastline_get dll_rb_lastline_get
166 #define rb_lastline_set dll_rb_lastline_set
167 #define rb_load_protect dll_rb_load_protect
168 #define rb_num2long dll_rb_num2long
169 #define rb_num2ulong dll_rb_num2ulong
170 #define rb_obj_alloc dll_rb_obj_alloc
171 #define rb_obj_as_string dll_rb_obj_as_string
172 #define rb_obj_id dll_rb_obj_id
173 #define rb_raise dll_rb_raise
174 #define rb_str2cstr dll_rb_str2cstr
175 #define rb_str_cat dll_rb_str_cat
176 #define rb_str_concat dll_rb_str_concat
177 #define rb_str_new dll_rb_str_new
178 #define rb_str_new2 dll_rb_str_new2
179 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
180 # define rb_string_value_ptr dll_rb_string_value_ptr
181 # define rb_float_new dll_rb_float_new
182 # define rb_ary_new dll_rb_ary_new
183 # define rb_ary_push dll_rb_ary_push
184 #endif
185 #ifdef RUBY19_OR_LATER
186 # define rb_errinfo dll_rb_errinfo
187 #else
188 # define ruby_errinfo (*dll_ruby_errinfo)
189 #endif
190 #define ruby_init dll_ruby_init
191 #define ruby_init_loadpath dll_ruby_init_loadpath
192 #define NtInitialize dll_NtInitialize
193 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
194 # define rb_w32_snprintf dll_rb_w32_snprintf
195 #endif
197 #ifdef RUBY19_OR_LATER
198 # define ruby_script dll_ruby_script
199 # define rb_enc_find_index dll_rb_enc_find_index
200 # define rb_enc_find dll_rb_enc_find
201 # define rb_enc_str_new dll_rb_enc_str_new
202 # define rb_sprintf dll_rb_sprintf
203 # define ruby_init_stack dll_ruby_init_stack
204 #endif
207 * Pointers for dynamic link
209 static VALUE (*dll_rb_assoc_new) (VALUE, VALUE);
210 static VALUE *dll_rb_cFalseClass;
211 static VALUE *dll_rb_cFixnum;
212 static VALUE *dll_rb_cNilClass;
213 static VALUE *dll_rb_cObject;
214 static VALUE *dll_rb_cSymbol;
215 static VALUE *dll_rb_cTrueClass;
216 static void (*dll_rb_check_type) (VALUE,int);
217 static VALUE (*dll_rb_class_path) (VALUE);
218 static VALUE (*dll_rb_data_object_alloc) (VALUE, void*, RUBY_DATA_FUNC, RUBY_DATA_FUNC);
219 static VALUE (*dll_rb_define_class_under) (VALUE, const char*, VALUE);
220 static void (*dll_rb_define_const) (VALUE,const char*,VALUE);
221 static void (*dll_rb_define_global_function) (const char*,VALUE(*)(),int);
222 static void (*dll_rb_define_method) (VALUE,const char*,VALUE(*)(),int);
223 static VALUE (*dll_rb_define_module) (const char*);
224 static void (*dll_rb_define_module_function) (VALUE,const char*,VALUE(*)(),int);
225 static void (*dll_rb_define_singleton_method) (VALUE,const char*,VALUE(*)(),int);
226 static void (*dll_rb_define_virtual_variable) (const char*,VALUE(*)(),void(*)());
227 static VALUE *dll_rb_stdout;
228 static VALUE *dll_rb_eArgError;
229 static VALUE *dll_rb_eIndexError;
230 static VALUE *dll_rb_eRuntimeError;
231 static VALUE *dll_rb_eStandardError;
232 static VALUE (*dll_rb_eval_string_protect) (const char*, int*);
233 static void (*dll_rb_global_variable) (VALUE*);
234 static VALUE (*dll_rb_hash_aset) (VALUE, VALUE, VALUE);
235 static VALUE (*dll_rb_hash_new) (void);
236 static VALUE (*dll_rb_inspect) (VALUE);
237 static VALUE (*dll_rb_int2inum) (long);
238 static VALUE (*dll_rb_int2inum) (long);
239 static VALUE (*dll_rb_lastline_get) (void);
240 static void (*dll_rb_lastline_set) (VALUE);
241 static void (*dll_rb_load_protect) (VALUE, int, int*);
242 static long (*dll_rb_num2long) (VALUE);
243 static unsigned long (*dll_rb_num2ulong) (VALUE);
244 static VALUE (*dll_rb_obj_alloc) (VALUE);
245 static VALUE (*dll_rb_obj_as_string) (VALUE);
246 static VALUE (*dll_rb_obj_id) (VALUE);
247 static void (*dll_rb_raise) (VALUE, const char*, ...);
248 static char *(*dll_rb_str2cstr) (VALUE,int*);
249 static VALUE (*dll_rb_str_cat) (VALUE, const char*, long);
250 static VALUE (*dll_rb_str_concat) (VALUE, VALUE);
251 static VALUE (*dll_rb_str_new) (const char*, long);
252 static VALUE (*dll_rb_str_new2) (const char*);
253 #ifdef RUBY19_OR_LATER
254 static VALUE (*dll_rb_errinfo) (void);
255 #else
256 static VALUE *dll_ruby_errinfo;
257 #endif
258 static void (*dll_ruby_init) (void);
259 static void (*dll_ruby_init_loadpath) (void);
260 static void (*dll_NtInitialize) (int*, char***);
261 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
262 static char * (*dll_rb_string_value_ptr) (volatile VALUE*);
263 static VALUE (*dll_rb_float_new) (double);
264 static VALUE (*dll_rb_ary_new) (void);
265 static VALUE (*dll_rb_ary_push) (VALUE, VALUE);
266 #endif
267 #ifdef RUBY19_OR_LATER
268 static VALUE (*dll_rb_int2big)(SIGNED_VALUE);
269 #endif
270 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
271 static int (*dll_rb_w32_snprintf)(char*, size_t, const char*, ...);
272 #endif
274 #ifdef RUBY19_OR_LATER
275 static void (*dll_ruby_script) (const char*);
276 static int (*dll_rb_enc_find_index) (const char*);
277 static rb_encoding* (*dll_rb_enc_find) (const char*);
278 static VALUE (*dll_rb_enc_str_new) (const char*, long, rb_encoding*);
279 static VALUE (*dll_rb_sprintf) (const char*, ...);
280 static void (*ruby_init_stack)(VALUE*);
281 #endif
283 #ifdef RUBY19_OR_LATER
284 static SIGNED_VALUE rb_num2long_stub(VALUE x)
286 return dll_rb_num2long(x);
288 static VALUE rb_int2big_stub(SIGNED_VALUE x)
290 return dll_rb_int2big(x);
292 #endif
294 static HINSTANCE hinstRuby = 0; /* Instance of ruby.dll */
297 * Table of name to function pointer of ruby.
299 #define RUBY_PROC FARPROC
300 static struct
302 char *name;
303 RUBY_PROC *ptr;
304 } ruby_funcname_table[] =
306 {"rb_assoc_new", (RUBY_PROC*)&dll_rb_assoc_new},
307 {"rb_cFalseClass", (RUBY_PROC*)&dll_rb_cFalseClass},
308 {"rb_cFixnum", (RUBY_PROC*)&dll_rb_cFixnum},
309 {"rb_cNilClass", (RUBY_PROC*)&dll_rb_cNilClass},
310 {"rb_cObject", (RUBY_PROC*)&dll_rb_cObject},
311 {"rb_cSymbol", (RUBY_PROC*)&dll_rb_cSymbol},
312 {"rb_cTrueClass", (RUBY_PROC*)&dll_rb_cTrueClass},
313 {"rb_check_type", (RUBY_PROC*)&dll_rb_check_type},
314 {"rb_class_path", (RUBY_PROC*)&dll_rb_class_path},
315 {"rb_data_object_alloc", (RUBY_PROC*)&dll_rb_data_object_alloc},
316 {"rb_define_class_under", (RUBY_PROC*)&dll_rb_define_class_under},
317 {"rb_define_const", (RUBY_PROC*)&dll_rb_define_const},
318 {"rb_define_global_function", (RUBY_PROC*)&dll_rb_define_global_function},
319 {"rb_define_method", (RUBY_PROC*)&dll_rb_define_method},
320 {"rb_define_module", (RUBY_PROC*)&dll_rb_define_module},
321 {"rb_define_module_function", (RUBY_PROC*)&dll_rb_define_module_function},
322 {"rb_define_singleton_method", (RUBY_PROC*)&dll_rb_define_singleton_method},
323 {"rb_define_virtual_variable", (RUBY_PROC*)&dll_rb_define_virtual_variable},
324 {"rb_stdout", (RUBY_PROC*)&dll_rb_stdout},
325 {"rb_eArgError", (RUBY_PROC*)&dll_rb_eArgError},
326 {"rb_eIndexError", (RUBY_PROC*)&dll_rb_eIndexError},
327 {"rb_eRuntimeError", (RUBY_PROC*)&dll_rb_eRuntimeError},
328 {"rb_eStandardError", (RUBY_PROC*)&dll_rb_eStandardError},
329 {"rb_eval_string_protect", (RUBY_PROC*)&dll_rb_eval_string_protect},
330 {"rb_global_variable", (RUBY_PROC*)&dll_rb_global_variable},
331 {"rb_hash_aset", (RUBY_PROC*)&dll_rb_hash_aset},
332 {"rb_hash_new", (RUBY_PROC*)&dll_rb_hash_new},
333 {"rb_inspect", (RUBY_PROC*)&dll_rb_inspect},
334 {"rb_int2inum", (RUBY_PROC*)&dll_rb_int2inum},
335 {"rb_lastline_get", (RUBY_PROC*)&dll_rb_lastline_get},
336 {"rb_lastline_set", (RUBY_PROC*)&dll_rb_lastline_set},
337 {"rb_load_protect", (RUBY_PROC*)&dll_rb_load_protect},
338 {"rb_num2long", (RUBY_PROC*)&dll_rb_num2long},
339 {"rb_num2ulong", (RUBY_PROC*)&dll_rb_num2ulong},
340 {"rb_obj_alloc", (RUBY_PROC*)&dll_rb_obj_alloc},
341 {"rb_obj_as_string", (RUBY_PROC*)&dll_rb_obj_as_string},
342 {"rb_obj_id", (RUBY_PROC*)&dll_rb_obj_id},
343 {"rb_raise", (RUBY_PROC*)&dll_rb_raise},
344 {"rb_str2cstr", (RUBY_PROC*)&dll_rb_str2cstr},
345 {"rb_str_cat", (RUBY_PROC*)&dll_rb_str_cat},
346 {"rb_str_concat", (RUBY_PROC*)&dll_rb_str_concat},
347 {"rb_str_new", (RUBY_PROC*)&dll_rb_str_new},
348 {"rb_str_new2", (RUBY_PROC*)&dll_rb_str_new2},
349 #ifdef RUBY19_OR_LATER
350 {"rb_errinfo", (RUBY_PROC*)&dll_rb_errinfo},
351 #else
352 {"ruby_errinfo", (RUBY_PROC*)&dll_ruby_errinfo},
353 #endif
354 {"ruby_init", (RUBY_PROC*)&dll_ruby_init},
355 {"ruby_init_loadpath", (RUBY_PROC*)&dll_ruby_init_loadpath},
357 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER < 19
358 "NtInitialize",
359 #else
360 "ruby_sysinit",
361 #endif
362 (RUBY_PROC*)&dll_NtInitialize},
363 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
364 {"rb_w32_snprintf", (RUBY_PROC*)&dll_rb_w32_snprintf},
365 #endif
366 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
367 {"rb_string_value_ptr", (RUBY_PROC*)&dll_rb_string_value_ptr},
368 {"rb_float_new", (RUBY_PROC*)&dll_rb_float_new},
369 {"rb_ary_new", (RUBY_PROC*)&dll_rb_ary_new},
370 {"rb_ary_push", (RUBY_PROC*)&dll_rb_ary_push},
371 #endif
372 #ifdef RUBY19_OR_LATER
373 {"rb_int2big", (RUBY_PROC*)&dll_rb_int2big},
374 {"ruby_script", (RUBY_PROC*)&dll_ruby_script},
375 {"rb_enc_find_index", (RUBY_PROC*)&dll_rb_enc_find_index},
376 {"rb_enc_find", (RUBY_PROC*)&dll_rb_enc_find},
377 {"rb_enc_str_new", (RUBY_PROC*)&dll_rb_enc_str_new},
378 {"rb_sprintf", (RUBY_PROC*)&dll_rb_sprintf},
379 {"ruby_init_stack", (RUBY_PROC*)&dll_ruby_init_stack},
380 #endif
381 {"", NULL},
385 * Free ruby.dll
387 static void
388 end_dynamic_ruby()
390 if (hinstRuby)
392 FreeLibrary(hinstRuby);
393 hinstRuby = 0;
398 * Load library and get all pointers.
399 * Parameter 'libname' provides name of DLL.
400 * Return OK or FAIL.
402 static int
403 ruby_runtime_link_init(char *libname, int verbose)
405 int i;
407 if (hinstRuby)
408 return OK;
409 hinstRuby = LoadLibrary(libname);
410 if (!hinstRuby)
412 if (verbose)
413 EMSG2(_(e_loadlib), libname);
414 return FAIL;
417 for (i = 0; ruby_funcname_table[i].ptr; ++i)
419 if (!(*ruby_funcname_table[i].ptr = GetProcAddress(hinstRuby,
420 ruby_funcname_table[i].name)))
422 FreeLibrary(hinstRuby);
423 hinstRuby = 0;
424 if (verbose)
425 EMSG2(_(e_loadfunc), ruby_funcname_table[i].name);
426 return FAIL;
429 return OK;
433 * If ruby is enabled (there is installed ruby on Windows system) return TRUE,
434 * else FALSE.
437 ruby_enabled(verbose)
438 int verbose;
440 return ruby_runtime_link_init(DYNAMIC_RUBY_DLL, verbose) == OK;
442 #endif /* defined(DYNAMIC_RUBY) || defined(PROTO) */
444 void
445 ruby_end()
447 #ifdef DYNAMIC_RUBY
448 end_dynamic_ruby();
449 #endif
452 void ex_ruby(exarg_T *eap)
454 int state;
455 char *script = NULL;
457 script = (char *)script_get(eap, eap->arg);
458 if (!eap->skip && ensure_ruby_initialized())
460 if (script == NULL)
461 rb_eval_string_protect((char *)eap->arg, &state);
462 else
463 rb_eval_string_protect(script, &state);
464 if (state)
465 error_print(state);
467 vim_free(script);
471 * In Ruby 1.9 or later, ruby String object has encoding.
472 * conversion buffer string of vim to ruby String object using
473 * VIM encoding option.
475 static VALUE
476 vim_str2rb_enc_str(const char *s)
478 #ifdef RUBY19_OR_LATER
479 int isnum;
480 long lval;
481 char_u *sval;
482 rb_encoding *enc;
484 isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
485 if (isnum == 0)
487 enc = rb_enc_find((char *)sval);
488 vim_free(sval);
489 if (enc) {
490 return rb_enc_str_new(s, strlen(s), enc);
493 #endif
494 return rb_str_new2(s);
497 static VALUE
498 eval_enc_string_protect(const char *str, int *state)
500 #ifdef RUBY19_OR_LATER
501 int isnum;
502 long lval;
503 char_u *sval;
504 rb_encoding *enc;
505 VALUE v;
507 isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
508 if (isnum == 0)
510 enc = rb_enc_find((char *)sval);
511 vim_free(sval);
512 if (enc)
514 v = rb_sprintf("#-*- coding:%s -*-\n%s", rb_enc_name(enc), str);
515 return rb_eval_string_protect(StringValuePtr(v), state);
518 #endif
519 return rb_eval_string_protect(str, state);
522 void ex_rubydo(exarg_T *eap)
524 int state;
525 linenr_T i;
527 if (ensure_ruby_initialized())
529 if (u_save(eap->line1 - 1, eap->line2 + 1) != OK)
530 return;
531 for (i = eap->line1; i <= eap->line2; i++) {
532 VALUE line, oldline;
534 line = oldline = vim_str2rb_enc_str((char *)ml_get(i));
535 rb_lastline_set(line);
536 eval_enc_string_protect((char *) eap->arg, &state);
537 if (state) {
538 error_print(state);
539 break;
541 line = rb_lastline_get();
542 if (!NIL_P(line)) {
543 if (TYPE(line) != T_STRING) {
544 EMSG(_("E265: $_ must be an instance of String"));
545 return;
547 ml_replace(i, (char_u *) StringValuePtr(line), 1);
548 changed();
549 #ifdef SYNTAX_HL
550 syn_changed(i); /* recompute syntax hl. for this line */
551 #endif
554 check_cursor();
555 update_curbuf(NOT_VALID);
559 void ex_rubyfile(exarg_T *eap)
561 int state;
563 if (ensure_ruby_initialized())
565 rb_load_protect(rb_str_new2((char *) eap->arg), 0, &state);
566 if (state) error_print(state);
570 void ruby_buffer_free(buf_T *buf)
572 if (buf->b_ruby_ref)
574 rb_hash_aset(objtbl, rb_obj_id((VALUE) buf->b_ruby_ref), Qnil);
575 RDATA(buf->b_ruby_ref)->data = NULL;
579 void ruby_window_free(win_T *win)
581 if (win->w_ruby_ref)
583 rb_hash_aset(objtbl, rb_obj_id((VALUE) win->w_ruby_ref), Qnil);
584 RDATA(win->w_ruby_ref)->data = NULL;
588 static int ensure_ruby_initialized(void)
590 if (!ruby_initialized)
592 #ifdef DYNAMIC_RUBY
593 if (ruby_enabled(TRUE))
595 #endif
596 #ifdef _WIN32
597 /* suggested by Ariya Mizutani */
598 int argc = 1;
599 char *argv[] = {"gvim.exe"};
600 NtInitialize(&argc, &argv);
601 #endif
602 #ifdef RUBY19_OR_LATER
603 RUBY_INIT_STACK;
604 #endif
605 ruby_init();
606 #ifdef RUBY19_OR_LATER
607 ruby_script("vim-ruby");
608 #endif
609 ruby_init_loadpath();
610 ruby_io_init();
611 #ifdef RUBY19_OR_LATER
612 rb_enc_find_index("encdb");
613 #endif
614 ruby_vim_init();
615 ruby_initialized = 1;
616 #ifdef DYNAMIC_RUBY
618 else
620 EMSG(_("E266: Sorry, this command is disabled, the Ruby library could not be loaded."));
621 return 0;
623 #endif
625 return ruby_initialized;
628 static void error_print(int state)
630 #ifndef DYNAMIC_RUBY
631 #if !(defined(RUBY_VERSION) && RUBY_VERSION >= 19) \
632 && !(defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19)
633 RUBYEXTERN VALUE ruby_errinfo;
634 #endif
635 #endif
636 VALUE eclass;
637 VALUE einfo;
638 char buff[BUFSIZ];
640 #define TAG_RETURN 0x1
641 #define TAG_BREAK 0x2
642 #define TAG_NEXT 0x3
643 #define TAG_RETRY 0x4
644 #define TAG_REDO 0x5
645 #define TAG_RAISE 0x6
646 #define TAG_THROW 0x7
647 #define TAG_FATAL 0x8
648 #define TAG_MASK 0xf
650 switch (state) {
651 case TAG_RETURN:
652 EMSG(_("E267: unexpected return"));
653 break;
654 case TAG_NEXT:
655 EMSG(_("E268: unexpected next"));
656 break;
657 case TAG_BREAK:
658 EMSG(_("E269: unexpected break"));
659 break;
660 case TAG_REDO:
661 EMSG(_("E270: unexpected redo"));
662 break;
663 case TAG_RETRY:
664 EMSG(_("E271: retry outside of rescue clause"));
665 break;
666 case TAG_RAISE:
667 case TAG_FATAL:
668 #ifdef RUBY19_OR_LATER
669 eclass = CLASS_OF(rb_errinfo());
670 einfo = rb_obj_as_string(rb_errinfo());
671 #else
672 eclass = CLASS_OF(ruby_errinfo);
673 einfo = rb_obj_as_string(ruby_errinfo);
674 #endif
675 if (eclass == rb_eRuntimeError && RSTRING_LEN(einfo) == 0) {
676 EMSG(_("E272: unhandled exception"));
678 else {
679 VALUE epath;
680 char *p;
682 epath = rb_class_path(eclass);
683 vim_snprintf(buff, BUFSIZ, "%s: %s",
684 RSTRING_PTR(epath), RSTRING_PTR(einfo));
685 p = strchr(buff, '\n');
686 if (p) *p = '\0';
687 EMSG(buff);
689 break;
690 default:
691 vim_snprintf(buff, BUFSIZ, _("E273: unknown longjmp status %d"), state);
692 EMSG(buff);
693 break;
697 static VALUE vim_message(VALUE self UNUSED, VALUE str)
699 char *buff, *p;
701 str = rb_obj_as_string(str);
702 buff = ALLOCA_N(char, RSTRING_LEN(str));
703 strcpy(buff, RSTRING_PTR(str));
704 p = strchr(buff, '\n');
705 if (p) *p = '\0';
706 MSG(buff);
707 return Qnil;
710 static VALUE vim_set_option(VALUE self UNUSED, VALUE str)
712 do_set((char_u *)StringValuePtr(str), 0);
713 update_screen(NOT_VALID);
714 return Qnil;
717 static VALUE vim_command(VALUE self UNUSED, VALUE str)
719 do_cmdline_cmd((char_u *)StringValuePtr(str));
720 return Qnil;
723 #ifdef FEAT_EVAL
724 static VALUE vim_to_ruby(typval_T *tv)
726 VALUE result = Qnil;
728 if (tv->v_type == VAR_STRING)
730 result = rb_str_new2(tv->vval.v_string == NULL
731 ? "" : (char *)(tv->vval.v_string));
733 else if (tv->v_type == VAR_NUMBER)
735 result = INT2NUM(tv->vval.v_number);
737 # ifdef FEAT_FLOAT
738 else if (tv->v_type == VAR_FLOAT)
740 result = rb_float_new(tv->vval.v_float);
742 # endif
743 else if (tv->v_type == VAR_LIST)
745 list_T *list = tv->vval.v_list;
746 listitem_T *curr;
748 result = rb_ary_new();
750 if (list != NULL)
752 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
754 rb_ary_push(result, vim_to_ruby(&curr->li_tv));
758 else if (tv->v_type == VAR_DICT)
760 result = rb_hash_new();
762 if (tv->vval.v_dict != NULL)
764 hashtab_T *ht = &tv->vval.v_dict->dv_hashtab;
765 long_u todo = ht->ht_used;
766 hashitem_T *hi;
767 dictitem_T *di;
769 for (hi = ht->ht_array; todo > 0; ++hi)
771 if (!HASHITEM_EMPTY(hi))
773 --todo;
775 di = dict_lookup(hi);
776 rb_hash_aset(result, rb_str_new2((char *)hi->hi_key),
777 vim_to_ruby(&di->di_tv));
781 } /* else return Qnil; */
783 return result;
785 #endif
787 static VALUE vim_evaluate(VALUE self UNUSED, VALUE str)
789 #ifdef FEAT_EVAL
790 typval_T *tv;
791 VALUE result;
793 tv = eval_expr((char_u *)StringValuePtr(str), NULL);
794 if (tv == NULL)
796 return Qnil;
798 result = vim_to_ruby(tv);
800 free_tv(tv);
802 return result;
803 #else
804 return Qnil;
805 #endif
808 static VALUE buffer_new(buf_T *buf)
810 if (buf->b_ruby_ref)
812 return (VALUE) buf->b_ruby_ref;
814 else
816 VALUE obj = Data_Wrap_Struct(cBuffer, 0, 0, buf);
817 buf->b_ruby_ref = (void *) obj;
818 rb_hash_aset(objtbl, rb_obj_id(obj), obj);
819 return obj;
823 static buf_T *get_buf(VALUE obj)
825 buf_T *buf;
827 Data_Get_Struct(obj, buf_T, buf);
828 if (buf == NULL)
829 rb_raise(eDeletedBufferError, "attempt to refer to deleted buffer");
830 return buf;
833 static VALUE buffer_s_current()
835 return buffer_new(curbuf);
838 static VALUE buffer_s_count()
840 buf_T *b;
841 int n = 0;
843 for (b = firstbuf; b != NULL; b = b->b_next)
845 /* Deleted buffers should not be counted
846 * SegPhault - 01/07/05 */
847 if (b->b_p_bl)
848 n++;
851 return INT2NUM(n);
854 static VALUE buffer_s_aref(VALUE self UNUSED, VALUE num)
856 buf_T *b;
857 int n = NUM2INT(num);
859 for (b = firstbuf; b != NULL; b = b->b_next)
861 /* Deleted buffers should not be counted
862 * SegPhault - 01/07/05 */
863 if (!b->b_p_bl)
864 continue;
866 if (n == 0)
867 return buffer_new(b);
869 n--;
871 return Qnil;
874 static VALUE buffer_name(VALUE self)
876 buf_T *buf = get_buf(self);
878 return buf->b_ffname ? rb_str_new2((char *)buf->b_ffname) : Qnil;
881 static VALUE buffer_number(VALUE self)
883 buf_T *buf = get_buf(self);
885 return INT2NUM(buf->b_fnum);
888 static VALUE buffer_count(VALUE self)
890 buf_T *buf = get_buf(self);
892 return INT2NUM(buf->b_ml.ml_line_count);
895 static VALUE get_buffer_line(buf_T *buf, linenr_T n)
897 if (n > 0 && n <= buf->b_ml.ml_line_count)
899 char *line = (char *)ml_get_buf(buf, n, FALSE);
900 return line ? vim_str2rb_enc_str(line) : Qnil;
902 rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
903 #ifndef __GNUC__
904 return Qnil; /* For stop warning */
905 #endif
908 static VALUE buffer_aref(VALUE self, VALUE num)
910 buf_T *buf = get_buf(self);
912 if (buf != NULL)
913 return get_buffer_line(buf, (linenr_T)NUM2LONG(num));
914 return Qnil; /* For stop warning */
917 static VALUE set_buffer_line(buf_T *buf, linenr_T n, VALUE str)
919 char *line = StringValuePtr(str);
920 aco_save_T aco;
922 if (n > 0 && n <= buf->b_ml.ml_line_count && line != NULL)
924 /* set curwin/curbuf for "buf" and save some things */
925 aucmd_prepbuf(&aco, buf);
927 if (u_savesub(n) == OK) {
928 ml_replace(n, (char_u *)line, TRUE);
929 changed();
930 #ifdef SYNTAX_HL
931 syn_changed(n); /* recompute syntax hl. for this line */
932 #endif
935 /* restore curwin/curbuf and a few other things */
936 aucmd_restbuf(&aco);
937 /* Careful: autocommands may have made "buf" invalid! */
939 update_curbuf(NOT_VALID);
941 else
943 rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
944 #ifndef __GNUC__
945 return Qnil; /* For stop warning */
946 #endif
948 return str;
951 static VALUE buffer_aset(VALUE self, VALUE num, VALUE str)
953 buf_T *buf = get_buf(self);
955 if (buf != NULL)
956 return set_buffer_line(buf, (linenr_T)NUM2LONG(num), str);
957 return str;
960 static VALUE buffer_delete(VALUE self, VALUE num)
962 buf_T *buf = get_buf(self);
963 long n = NUM2LONG(num);
964 aco_save_T aco;
966 if (n > 0 && n <= buf->b_ml.ml_line_count)
968 /* set curwin/curbuf for "buf" and save some things */
969 aucmd_prepbuf(&aco, buf);
971 if (u_savedel(n, 1) == OK) {
972 ml_delete(n, 0);
974 /* Changes to non-active buffers should properly refresh
975 * SegPhault - 01/09/05 */
976 deleted_lines_mark(n, 1L);
978 changed();
981 /* restore curwin/curbuf and a few other things */
982 aucmd_restbuf(&aco);
983 /* Careful: autocommands may have made "buf" invalid! */
985 update_curbuf(NOT_VALID);
987 else
989 rb_raise(rb_eIndexError, "line number %ld out of range", n);
991 return Qnil;
994 static VALUE buffer_append(VALUE self, VALUE num, VALUE str)
996 buf_T *buf = get_buf(self);
997 char *line = StringValuePtr(str);
998 long n = NUM2LONG(num);
999 aco_save_T aco;
1001 if (line == NULL) {
1002 rb_raise(rb_eIndexError, "NULL line");
1004 else if (n >= 0 && n <= buf->b_ml.ml_line_count)
1006 /* set curwin/curbuf for "buf" and save some things */
1007 aucmd_prepbuf(&aco, buf);
1009 if (u_inssub(n + 1) == OK) {
1010 ml_append(n, (char_u *) line, (colnr_T) 0, FALSE);
1012 /* Changes to non-active buffers should properly refresh screen
1013 * SegPhault - 12/20/04 */
1014 appended_lines_mark(n, 1L);
1016 changed();
1019 /* restore curwin/curbuf and a few other things */
1020 aucmd_restbuf(&aco);
1021 /* Careful: autocommands may have made "buf" invalid! */
1023 update_curbuf(NOT_VALID);
1025 else {
1026 rb_raise(rb_eIndexError, "line number %ld out of range", n);
1028 return str;
1031 static VALUE window_new(win_T *win)
1033 if (win->w_ruby_ref)
1035 return (VALUE) win->w_ruby_ref;
1037 else
1039 VALUE obj = Data_Wrap_Struct(cVimWindow, 0, 0, win);
1040 win->w_ruby_ref = (void *) obj;
1041 rb_hash_aset(objtbl, rb_obj_id(obj), obj);
1042 return obj;
1046 static win_T *get_win(VALUE obj)
1048 win_T *win;
1050 Data_Get_Struct(obj, win_T, win);
1051 if (win == NULL)
1052 rb_raise(eDeletedWindowError, "attempt to refer to deleted window");
1053 return win;
1056 static VALUE window_s_current()
1058 return window_new(curwin);
1062 * Added line manipulation functions
1063 * SegPhault - 03/07/05
1065 static VALUE line_s_current()
1067 return get_buffer_line(curbuf, curwin->w_cursor.lnum);
1070 static VALUE set_current_line(VALUE self UNUSED, VALUE str)
1072 return set_buffer_line(curbuf, curwin->w_cursor.lnum, str);
1075 static VALUE current_line_number()
1077 return INT2FIX((int)curwin->w_cursor.lnum);
1082 static VALUE window_s_count()
1084 #ifdef FEAT_WINDOWS
1085 win_T *w;
1086 int n = 0;
1088 for (w = firstwin; w != NULL; w = w->w_next)
1089 n++;
1090 return INT2NUM(n);
1091 #else
1092 return INT2NUM(1);
1093 #endif
1096 static VALUE window_s_aref(VALUE self UNUSED, VALUE num)
1098 win_T *w;
1099 int n = NUM2INT(num);
1101 #ifndef FEAT_WINDOWS
1102 w = curwin;
1103 #else
1104 for (w = firstwin; w != NULL; w = w->w_next, --n)
1105 #endif
1106 if (n == 0)
1107 return window_new(w);
1108 return Qnil;
1111 static VALUE window_buffer(VALUE self)
1113 win_T *win = get_win(self);
1115 return buffer_new(win->w_buffer);
1118 static VALUE window_height(VALUE self)
1120 win_T *win = get_win(self);
1122 return INT2NUM(win->w_height);
1125 static VALUE window_set_height(VALUE self, VALUE height)
1127 win_T *win = get_win(self);
1128 win_T *savewin = curwin;
1130 curwin = win;
1131 win_setheight(NUM2INT(height));
1132 curwin = savewin;
1133 return height;
1136 static VALUE window_width(VALUE self)
1138 win_T *win = get_win(self);
1140 return INT2NUM(win->w_width);
1143 static VALUE window_set_width(VALUE self, VALUE width)
1145 win_T *win = get_win(self);
1146 win_T *savewin = curwin;
1148 curwin = win;
1149 win_setwidth(NUM2INT(width));
1150 curwin = savewin;
1151 return width;
1154 static VALUE window_cursor(VALUE self)
1156 win_T *win = get_win(self);
1158 return rb_assoc_new(INT2NUM(win->w_cursor.lnum), INT2NUM(win->w_cursor.col));
1161 static VALUE window_set_cursor(VALUE self, VALUE pos)
1163 VALUE lnum, col;
1164 win_T *win = get_win(self);
1166 Check_Type(pos, T_ARRAY);
1167 if (RARRAY_LEN(pos) != 2)
1168 rb_raise(rb_eArgError, "array length must be 2");
1169 lnum = RARRAY_PTR(pos)[0];
1170 col = RARRAY_PTR(pos)[1];
1171 win->w_cursor.lnum = NUM2LONG(lnum);
1172 win->w_cursor.col = NUM2UINT(col);
1173 check_cursor(); /* put cursor on an existing line */
1174 update_screen(NOT_VALID);
1175 return Qnil;
1178 static VALUE f_p(int argc, VALUE *argv, VALUE self UNUSED)
1180 int i;
1181 VALUE str = rb_str_new("", 0);
1183 for (i = 0; i < argc; i++) {
1184 if (i > 0) rb_str_cat(str, ", ", 2);
1185 rb_str_concat(str, rb_inspect(argv[i]));
1187 MSG(RSTRING_PTR(str));
1188 return Qnil;
1191 static void ruby_io_init(void)
1193 #ifndef DYNAMIC_RUBY
1194 RUBYEXTERN VALUE rb_stdout;
1195 #endif
1197 rb_stdout = rb_obj_alloc(rb_cObject);
1198 rb_define_singleton_method(rb_stdout, "write", vim_message, 1);
1199 rb_define_global_function("p", f_p, -1);
1202 static void ruby_vim_init(void)
1204 objtbl = rb_hash_new();
1205 rb_global_variable(&objtbl);
1207 /* The Vim module used to be called "VIM", but "Vim" is better. Make an
1208 * alias "VIM" for backwards compatiblity. */
1209 mVIM = rb_define_module("Vim");
1210 rb_define_const(rb_cObject, "VIM", mVIM);
1211 rb_define_const(mVIM, "VERSION_MAJOR", INT2NUM(VIM_VERSION_MAJOR));
1212 rb_define_const(mVIM, "VERSION_MINOR", INT2NUM(VIM_VERSION_MINOR));
1213 rb_define_const(mVIM, "VERSION_BUILD", INT2NUM(VIM_VERSION_BUILD));
1214 rb_define_const(mVIM, "VERSION_PATCHLEVEL", INT2NUM(VIM_VERSION_PATCHLEVEL));
1215 rb_define_const(mVIM, "VERSION_SHORT", rb_str_new2(VIM_VERSION_SHORT));
1216 rb_define_const(mVIM, "VERSION_MEDIUM", rb_str_new2(VIM_VERSION_MEDIUM));
1217 rb_define_const(mVIM, "VERSION_LONG", rb_str_new2(VIM_VERSION_LONG));
1218 rb_define_const(mVIM, "VERSION_LONG_DATE", rb_str_new2(VIM_VERSION_LONG_DATE));
1219 rb_define_module_function(mVIM, "message", vim_message, 1);
1220 rb_define_module_function(mVIM, "set_option", vim_set_option, 1);
1221 rb_define_module_function(mVIM, "command", vim_command, 1);
1222 rb_define_module_function(mVIM, "evaluate", vim_evaluate, 1);
1224 eDeletedBufferError = rb_define_class_under(mVIM, "DeletedBufferError",
1225 rb_eStandardError);
1226 eDeletedWindowError = rb_define_class_under(mVIM, "DeletedWindowError",
1227 rb_eStandardError);
1229 cBuffer = rb_define_class_under(mVIM, "Buffer", rb_cObject);
1230 rb_define_singleton_method(cBuffer, "current", buffer_s_current, 0);
1231 rb_define_singleton_method(cBuffer, "count", buffer_s_count, 0);
1232 rb_define_singleton_method(cBuffer, "[]", buffer_s_aref, 1);
1233 rb_define_method(cBuffer, "name", buffer_name, 0);
1234 rb_define_method(cBuffer, "number", buffer_number, 0);
1235 rb_define_method(cBuffer, "count", buffer_count, 0);
1236 rb_define_method(cBuffer, "length", buffer_count, 0);
1237 rb_define_method(cBuffer, "[]", buffer_aref, 1);
1238 rb_define_method(cBuffer, "[]=", buffer_aset, 2);
1239 rb_define_method(cBuffer, "delete", buffer_delete, 1);
1240 rb_define_method(cBuffer, "append", buffer_append, 2);
1242 /* Added line manipulation functions
1243 * SegPhault - 03/07/05 */
1244 rb_define_method(cBuffer, "line_number", current_line_number, 0);
1245 rb_define_method(cBuffer, "line", line_s_current, 0);
1246 rb_define_method(cBuffer, "line=", set_current_line, 1);
1249 cVimWindow = rb_define_class_under(mVIM, "Window", rb_cObject);
1250 rb_define_singleton_method(cVimWindow, "current", window_s_current, 0);
1251 rb_define_singleton_method(cVimWindow, "count", window_s_count, 0);
1252 rb_define_singleton_method(cVimWindow, "[]", window_s_aref, 1);
1253 rb_define_method(cVimWindow, "buffer", window_buffer, 0);
1254 rb_define_method(cVimWindow, "height", window_height, 0);
1255 rb_define_method(cVimWindow, "height=", window_set_height, 1);
1256 rb_define_method(cVimWindow, "width", window_width, 0);
1257 rb_define_method(cVimWindow, "width=", window_set_width, 1);
1258 rb_define_method(cVimWindow, "cursor", window_cursor, 0);
1259 rb_define_method(cVimWindow, "cursor=", window_set_cursor, 1);
1261 rb_define_virtual_variable("$curbuf", buffer_s_current, 0);
1262 rb_define_virtual_variable("$curwin", window_s_current, 0);