Merge branch 'vim'
[MacVim.git] / src / if_ruby.c
blobef8af721a3fb77b4ebf2cf99b4a1ae496a261b77
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 "__declspce(dllimport)"
43 * in ruby.h. But it cause 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 #ifdef FEAT_GUI_MACVIM
57 # include <Ruby/ruby.h>
58 #else
59 # include <ruby.h>
60 #endif
61 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
62 # include <ruby/encoding.h>
63 #endif
65 #undef EXTERN
66 #undef _
68 /* T_DATA defined both by Ruby and Mac header files, hack around it... */
69 #if defined(MACOS_X_UNIX) || defined(macintosh)
70 # define __OPENTRANSPORT__
71 # define __OPENTRANSPORTPROTOCOL__
72 # define __OPENTRANSPORTPROVIDERS__
73 #endif
76 * Backward compatiblity for Ruby 1.8 and earlier.
77 * Ruby 1.9 does not provide STR2CSTR, instead StringValuePtr is provided.
78 * Ruby 1.9 does not provide RXXX(s)->len and RXXX(s)->ptr, instead
79 * RXXX_LEN(s) and RXXX_PTR(s) are provided.
81 #ifndef StringValuePtr
82 # define StringValuePtr(s) STR2CSTR(s)
83 #endif
84 #ifndef RARRAY_LEN
85 # define RARRAY_LEN(s) RARRAY(s)->len
86 #endif
87 #ifndef RARRAY_PTR
88 # define RARRAY_PTR(s) RARRAY(s)->ptr
89 #endif
90 #ifndef RSTRING_LEN
91 # define RSTRING_LEN(s) RSTRING(s)->len
92 #endif
93 #ifndef RSTRING_PTR
94 # define RSTRING_PTR(s) RSTRING(s)->ptr
95 #endif
97 #include "vim.h"
98 #include "version.h"
100 #if defined(PROTO) && !defined(FEAT_RUBY)
101 /* Define these to be able to generate the function prototypes. */
102 # define VALUE int
103 # define RUBY_DATA_FUNC int
104 #endif
106 static int ruby_initialized = 0;
107 static VALUE objtbl;
109 static VALUE mVIM;
110 static VALUE cBuffer;
111 static VALUE cVimWindow;
112 static VALUE eDeletedBufferError;
113 static VALUE eDeletedWindowError;
115 static int ensure_ruby_initialized(void);
116 static void error_print(int);
117 static void ruby_io_init(void);
118 static void ruby_vim_init(void);
120 #if defined(DYNAMIC_RUBY) || defined(PROTO)
121 #ifdef PROTO
122 # define HINSTANCE int /* for generating prototypes */
123 #endif
126 * Wrapper defines
128 #define rb_assoc_new dll_rb_assoc_new
129 #define rb_cObject (*dll_rb_cObject)
130 #define rb_check_type dll_rb_check_type
131 #define rb_class_path dll_rb_class_path
132 #define rb_data_object_alloc dll_rb_data_object_alloc
133 #define rb_define_class_under dll_rb_define_class_under
134 #define rb_define_const dll_rb_define_const
135 #define rb_define_global_function dll_rb_define_global_function
136 #define rb_define_method dll_rb_define_method
137 #define rb_define_module dll_rb_define_module
138 #define rb_define_module_function dll_rb_define_module_function
139 #define rb_define_singleton_method dll_rb_define_singleton_method
140 #define rb_define_virtual_variable dll_rb_define_virtual_variable
141 #define rb_stdout (*dll_rb_stdout)
142 #define rb_eArgError (*dll_rb_eArgError)
143 #define rb_eIndexError (*dll_rb_eIndexError)
144 #define rb_eRuntimeError (*dll_rb_eRuntimeError)
145 #define rb_eStandardError (*dll_rb_eStandardError)
146 #define rb_eval_string_protect dll_rb_eval_string_protect
147 #define rb_global_variable dll_rb_global_variable
148 #define rb_hash_aset dll_rb_hash_aset
149 #define rb_hash_new dll_rb_hash_new
150 #define rb_inspect dll_rb_inspect
151 #define rb_int2inum dll_rb_int2inum
152 #define rb_lastline_get dll_rb_lastline_get
153 #define rb_lastline_set dll_rb_lastline_set
154 #define rb_load_protect dll_rb_load_protect
155 #define rb_num2long dll_rb_num2long
156 #define rb_num2ulong dll_rb_num2ulong
157 #define rb_obj_alloc dll_rb_obj_alloc
158 #define rb_obj_as_string dll_rb_obj_as_string
159 #define rb_obj_id dll_rb_obj_id
160 #define rb_raise dll_rb_raise
161 #define rb_str2cstr dll_rb_str2cstr
162 #define rb_str_cat dll_rb_str_cat
163 #define rb_str_concat dll_rb_str_concat
164 #define rb_str_new dll_rb_str_new
165 #define rb_str_new2 dll_rb_str_new2
166 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
167 # define rb_errinfo dll_rb_errinfo
168 #else
169 # define ruby_errinfo (*dll_ruby_errinfo)
170 #endif
171 #define ruby_init dll_ruby_init
172 #define ruby_init_loadpath dll_ruby_init_loadpath
173 #define NtInitialize dll_NtInitialize
174 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
175 # define rb_w32_snprintf dll_rb_w32_snprintf
176 #endif
178 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
179 # define ruby_script dll_ruby_script
180 # define rb_enc_find_index dll_rb_enc_find_index
181 # define rb_enc_find dll_rb_enc_find
182 # define rb_enc_str_new dll_rb_enc_str_new
183 # define rb_sprintf dll_rb_sprintf
184 #endif
187 * Pointers for dynamic link
189 static VALUE (*dll_rb_assoc_new) (VALUE, VALUE);
190 static VALUE *dll_rb_cFalseClass;
191 static VALUE *dll_rb_cFixnum;
192 static VALUE *dll_rb_cNilClass;
193 static VALUE *dll_rb_cObject;
194 static VALUE *dll_rb_cSymbol;
195 static VALUE *dll_rb_cTrueClass;
196 static void (*dll_rb_check_type) (VALUE,int);
197 static VALUE (*dll_rb_class_path) (VALUE);
198 static VALUE (*dll_rb_data_object_alloc) (VALUE, void*, RUBY_DATA_FUNC, RUBY_DATA_FUNC);
199 static VALUE (*dll_rb_define_class_under) (VALUE, const char*, VALUE);
200 static void (*dll_rb_define_const) (VALUE,const char*,VALUE);
201 static void (*dll_rb_define_global_function) (const char*,VALUE(*)(),int);
202 static void (*dll_rb_define_method) (VALUE,const char*,VALUE(*)(),int);
203 static VALUE (*dll_rb_define_module) (const char*);
204 static void (*dll_rb_define_module_function) (VALUE,const char*,VALUE(*)(),int);
205 static void (*dll_rb_define_singleton_method) (VALUE,const char*,VALUE(*)(),int);
206 static void (*dll_rb_define_virtual_variable) (const char*,VALUE(*)(),void(*)());
207 static VALUE *dll_rb_stdout;
208 static VALUE *dll_rb_eArgError;
209 static VALUE *dll_rb_eIndexError;
210 static VALUE *dll_rb_eRuntimeError;
211 static VALUE *dll_rb_eStandardError;
212 static VALUE (*dll_rb_eval_string_protect) (const char*, int*);
213 static void (*dll_rb_global_variable) (VALUE*);
214 static VALUE (*dll_rb_hash_aset) (VALUE, VALUE, VALUE);
215 static VALUE (*dll_rb_hash_new) (void);
216 static VALUE (*dll_rb_inspect) (VALUE);
217 static VALUE (*dll_rb_int2inum) (long);
218 static VALUE (*dll_rb_int2inum) (long);
219 static VALUE (*dll_rb_lastline_get) (void);
220 static void (*dll_rb_lastline_set) (VALUE);
221 static void (*dll_rb_load_protect) (VALUE, int, int*);
222 static long (*dll_rb_num2long) (VALUE);
223 static unsigned long (*dll_rb_num2ulong) (VALUE);
224 static VALUE (*dll_rb_obj_alloc) (VALUE);
225 static VALUE (*dll_rb_obj_as_string) (VALUE);
226 static VALUE (*dll_rb_obj_id) (VALUE);
227 static void (*dll_rb_raise) (VALUE, const char*, ...);
228 static char *(*dll_rb_str2cstr) (VALUE,int*);
229 static VALUE (*dll_rb_str_cat) (VALUE, const char*, long);
230 static VALUE (*dll_rb_str_concat) (VALUE, VALUE);
231 static VALUE (*dll_rb_str_new) (const char*, long);
232 static VALUE (*dll_rb_str_new2) (const char*);
233 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
234 static VALUE (*dll_rb_errinfo) (void);
235 #else
236 static VALUE *dll_ruby_errinfo;
237 #endif
238 static void (*dll_ruby_init) (void);
239 static void (*dll_ruby_init_loadpath) (void);
240 static void (*dll_NtInitialize) (int*, char***);
241 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
242 static int (*dll_rb_w32_snprintf)(char*, size_t, const char*, ...);
243 #endif
245 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
246 static void (*dll_ruby_script) (const char*);
247 static int (*dll_rb_enc_find_index) (const char*);
248 static rb_encoding* (*dll_rb_enc_find) (const char*);
249 static VALUE (*dll_rb_enc_str_new) (const char*, long, rb_encoding*);
250 static VALUE (*dll_rb_sprintf) (const char*, ...);
251 #endif
253 static HINSTANCE hinstRuby = 0; /* Instance of ruby.dll */
256 * Table of name to function pointer of ruby.
258 #define RUBY_PROC FARPROC
259 static struct
261 char *name;
262 RUBY_PROC *ptr;
263 } ruby_funcname_table[] =
265 {"rb_assoc_new", (RUBY_PROC*)&dll_rb_assoc_new},
266 {"rb_cFalseClass", (RUBY_PROC*)&dll_rb_cFalseClass},
267 {"rb_cFixnum", (RUBY_PROC*)&dll_rb_cFixnum},
268 {"rb_cNilClass", (RUBY_PROC*)&dll_rb_cNilClass},
269 {"rb_cObject", (RUBY_PROC*)&dll_rb_cObject},
270 {"rb_cSymbol", (RUBY_PROC*)&dll_rb_cSymbol},
271 {"rb_cTrueClass", (RUBY_PROC*)&dll_rb_cTrueClass},
272 {"rb_check_type", (RUBY_PROC*)&dll_rb_check_type},
273 {"rb_class_path", (RUBY_PROC*)&dll_rb_class_path},
274 {"rb_data_object_alloc", (RUBY_PROC*)&dll_rb_data_object_alloc},
275 {"rb_define_class_under", (RUBY_PROC*)&dll_rb_define_class_under},
276 {"rb_define_const", (RUBY_PROC*)&dll_rb_define_const},
277 {"rb_define_global_function", (RUBY_PROC*)&dll_rb_define_global_function},
278 {"rb_define_method", (RUBY_PROC*)&dll_rb_define_method},
279 {"rb_define_module", (RUBY_PROC*)&dll_rb_define_module},
280 {"rb_define_module_function", (RUBY_PROC*)&dll_rb_define_module_function},
281 {"rb_define_singleton_method", (RUBY_PROC*)&dll_rb_define_singleton_method},
282 {"rb_define_virtual_variable", (RUBY_PROC*)&dll_rb_define_virtual_variable},
283 {"rb_stdout", (RUBY_PROC*)&dll_rb_stdout},
284 {"rb_eArgError", (RUBY_PROC*)&dll_rb_eArgError},
285 {"rb_eIndexError", (RUBY_PROC*)&dll_rb_eIndexError},
286 {"rb_eRuntimeError", (RUBY_PROC*)&dll_rb_eRuntimeError},
287 {"rb_eStandardError", (RUBY_PROC*)&dll_rb_eStandardError},
288 {"rb_eval_string_protect", (RUBY_PROC*)&dll_rb_eval_string_protect},
289 {"rb_global_variable", (RUBY_PROC*)&dll_rb_global_variable},
290 {"rb_hash_aset", (RUBY_PROC*)&dll_rb_hash_aset},
291 {"rb_hash_new", (RUBY_PROC*)&dll_rb_hash_new},
292 {"rb_inspect", (RUBY_PROC*)&dll_rb_inspect},
293 {"rb_int2inum", (RUBY_PROC*)&dll_rb_int2inum},
294 {"rb_lastline_get", (RUBY_PROC*)&dll_rb_lastline_get},
295 {"rb_lastline_set", (RUBY_PROC*)&dll_rb_lastline_set},
296 {"rb_load_protect", (RUBY_PROC*)&dll_rb_load_protect},
297 {"rb_num2long", (RUBY_PROC*)&dll_rb_num2long},
298 {"rb_num2ulong", (RUBY_PROC*)&dll_rb_num2ulong},
299 {"rb_obj_alloc", (RUBY_PROC*)&dll_rb_obj_alloc},
300 {"rb_obj_as_string", (RUBY_PROC*)&dll_rb_obj_as_string},
301 {"rb_obj_id", (RUBY_PROC*)&dll_rb_obj_id},
302 {"rb_raise", (RUBY_PROC*)&dll_rb_raise},
303 {"rb_str2cstr", (RUBY_PROC*)&dll_rb_str2cstr},
304 {"rb_str_cat", (RUBY_PROC*)&dll_rb_str_cat},
305 {"rb_str_concat", (RUBY_PROC*)&dll_rb_str_concat},
306 {"rb_str_new", (RUBY_PROC*)&dll_rb_str_new},
307 {"rb_str_new2", (RUBY_PROC*)&dll_rb_str_new2},
308 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
309 {"rb_errinfo", (RUBY_PROC*)&dll_rb_errinfo},
310 #else
311 {"ruby_errinfo", (RUBY_PROC*)&dll_ruby_errinfo},
312 #endif
313 {"ruby_init", (RUBY_PROC*)&dll_ruby_init},
314 {"ruby_init_loadpath", (RUBY_PROC*)&dll_ruby_init_loadpath},
315 {"NtInitialize", (RUBY_PROC*)&dll_NtInitialize},
316 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
317 {"rb_w32_snprintf", (RUBY_PROC*)&dll_rb_w32_snprintf},
318 #endif
319 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
320 {"ruby_script", (RUBY_PROC*)&dll_ruby_script},
321 {"rb_enc_find_index", (RUBY_PROC*)&dll_rb_enc_find_index},
322 {"rb_enc_find", (RUBY_PROC*)&dll_rb_enc_find},
323 {"rb_enc_str_new", (RUBY_PROC*)&dll_rb_enc_str_new},
324 {"rb_sprintf", (RUBY_PROC*)&dll_rb_sprintf},
325 #endif
326 {"", NULL},
330 * Free ruby.dll
332 static void
333 end_dynamic_ruby()
335 if (hinstRuby)
337 FreeLibrary(hinstRuby);
338 hinstRuby = 0;
343 * Load library and get all pointers.
344 * Parameter 'libname' provides name of DLL.
345 * Return OK or FAIL.
347 static int
348 ruby_runtime_link_init(char *libname, int verbose)
350 int i;
352 if (hinstRuby)
353 return OK;
354 hinstRuby = LoadLibrary(libname);
355 if (!hinstRuby)
357 if (verbose)
358 EMSG2(_(e_loadlib), libname);
359 return FAIL;
362 for (i = 0; ruby_funcname_table[i].ptr; ++i)
364 if (!(*ruby_funcname_table[i].ptr = GetProcAddress(hinstRuby,
365 ruby_funcname_table[i].name)))
367 FreeLibrary(hinstRuby);
368 hinstRuby = 0;
369 if (verbose)
370 EMSG2(_(e_loadfunc), ruby_funcname_table[i].name);
371 return FAIL;
374 return OK;
378 * If ruby is enabled (there is installed ruby on Windows system) return TRUE,
379 * else FALSE.
382 ruby_enabled(verbose)
383 int verbose;
385 return ruby_runtime_link_init(DYNAMIC_RUBY_DLL, verbose) == OK;
387 #endif /* defined(DYNAMIC_RUBY) || defined(PROTO) */
389 void
390 ruby_end()
392 #ifdef DYNAMIC_RUBY
393 end_dynamic_ruby();
394 #endif
397 void ex_ruby(exarg_T *eap)
399 int state;
400 char *script = NULL;
402 script = (char *)script_get(eap, eap->arg);
403 if (!eap->skip && ensure_ruby_initialized())
405 if (script == NULL)
406 rb_eval_string_protect((char *)eap->arg, &state);
407 else
408 rb_eval_string_protect(script, &state);
409 if (state)
410 error_print(state);
412 vim_free(script);
416 * In Ruby 1.9 or later, ruby String object has encoding.
417 * conversion buffer string of vim to ruby String object using
418 * VIM encoding option.
420 static VALUE
421 vim_str2rb_enc_str(const char *s)
423 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
424 int isnum;
425 long lval;
426 char_u *sval;
427 rb_encoding *enc;
429 isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
430 if (isnum == 0)
432 enc = rb_enc_find((char *)sval);
433 vim_free(sval);
434 if (enc) {
435 return rb_enc_str_new(s, strlen(s), enc);
438 #endif
439 return rb_str_new2(s);
442 static VALUE
443 eval_enc_string_protect(const char *str, int *state)
445 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
446 int isnum;
447 long lval;
448 char_u *sval;
449 rb_encoding *enc;
450 VALUE v;
452 isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
453 if (isnum == 0)
455 enc = rb_enc_find((char *)sval);
456 vim_free(sval);
457 if (enc)
459 v = rb_sprintf("#-*- coding:%s -*-\n%s", rb_enc_name(enc), str);
460 return rb_eval_string_protect(StringValuePtr(v), state);
463 #endif
464 return rb_eval_string_protect(str, state);
467 void ex_rubydo(exarg_T *eap)
469 int state;
470 linenr_T i;
472 if (ensure_ruby_initialized())
474 if (u_save(eap->line1 - 1, eap->line2 + 1) != OK)
475 return;
476 for (i = eap->line1; i <= eap->line2; i++) {
477 VALUE line, oldline;
479 line = oldline = vim_str2rb_enc_str((char *)ml_get(i));
480 rb_lastline_set(line);
481 eval_enc_string_protect((char *) eap->arg, &state);
482 if (state) {
483 error_print(state);
484 break;
486 line = rb_lastline_get();
487 if (!NIL_P(line)) {
488 if (TYPE(line) != T_STRING) {
489 EMSG(_("E265: $_ must be an instance of String"));
490 return;
492 ml_replace(i, (char_u *) StringValuePtr(line), 1);
493 changed();
494 #ifdef SYNTAX_HL
495 syn_changed(i); /* recompute syntax hl. for this line */
496 #endif
499 check_cursor();
500 update_curbuf(NOT_VALID);
504 void ex_rubyfile(exarg_T *eap)
506 int state;
508 if (ensure_ruby_initialized())
510 rb_load_protect(rb_str_new2((char *) eap->arg), 0, &state);
511 if (state) error_print(state);
515 void ruby_buffer_free(buf_T *buf)
517 if (buf->b_ruby_ref)
519 rb_hash_aset(objtbl, rb_obj_id((VALUE) buf->b_ruby_ref), Qnil);
520 RDATA(buf->b_ruby_ref)->data = NULL;
524 void ruby_window_free(win_T *win)
526 if (win->w_ruby_ref)
528 rb_hash_aset(objtbl, rb_obj_id((VALUE) win->w_ruby_ref), Qnil);
529 RDATA(win->w_ruby_ref)->data = NULL;
533 static int ensure_ruby_initialized(void)
535 if (!ruby_initialized)
537 #ifdef DYNAMIC_RUBY
538 if (ruby_enabled(TRUE))
540 #endif
541 #ifdef _WIN32
542 /* suggested by Ariya Mizutani */
543 int argc = 1;
544 char *argv[] = {"gvim.exe"};
545 NtInitialize(&argc, &argv);
546 #endif
547 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
548 RUBY_INIT_STACK;
549 #endif
550 ruby_init();
551 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
552 ruby_script("vim-ruby");
553 #endif
554 ruby_init_loadpath();
555 ruby_io_init();
556 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
557 rb_enc_find_index("encdb");
558 #endif
559 ruby_vim_init();
560 ruby_initialized = 1;
561 #ifdef DYNAMIC_RUBY
563 else
565 EMSG(_("E266: Sorry, this command is disabled, the Ruby library could not be loaded."));
566 return 0;
568 #endif
570 return ruby_initialized;
573 static void error_print(int state)
575 #ifndef DYNAMIC_RUBY
576 #if !(defined(RUBY_VERSION) && RUBY_VERSION >= 19)
577 RUBYEXTERN VALUE ruby_errinfo;
578 #endif
579 #endif
580 VALUE eclass;
581 VALUE einfo;
582 char buff[BUFSIZ];
584 #define TAG_RETURN 0x1
585 #define TAG_BREAK 0x2
586 #define TAG_NEXT 0x3
587 #define TAG_RETRY 0x4
588 #define TAG_REDO 0x5
589 #define TAG_RAISE 0x6
590 #define TAG_THROW 0x7
591 #define TAG_FATAL 0x8
592 #define TAG_MASK 0xf
594 switch (state) {
595 case TAG_RETURN:
596 EMSG(_("E267: unexpected return"));
597 break;
598 case TAG_NEXT:
599 EMSG(_("E268: unexpected next"));
600 break;
601 case TAG_BREAK:
602 EMSG(_("E269: unexpected break"));
603 break;
604 case TAG_REDO:
605 EMSG(_("E270: unexpected redo"));
606 break;
607 case TAG_RETRY:
608 EMSG(_("E271: retry outside of rescue clause"));
609 break;
610 case TAG_RAISE:
611 case TAG_FATAL:
612 #if defined(RUBY_VERSION) && RUBY_VERSION >= 19
613 eclass = CLASS_OF(rb_errinfo());
614 einfo = rb_obj_as_string(rb_errinfo());
615 #else
616 eclass = CLASS_OF(ruby_errinfo);
617 einfo = rb_obj_as_string(ruby_errinfo);
618 #endif
619 if (eclass == rb_eRuntimeError && RSTRING_LEN(einfo) == 0) {
620 EMSG(_("E272: unhandled exception"));
622 else {
623 VALUE epath;
624 char *p;
626 epath = rb_class_path(eclass);
627 vim_snprintf(buff, BUFSIZ, "%s: %s",
628 RSTRING_PTR(epath), RSTRING_PTR(einfo));
629 p = strchr(buff, '\n');
630 if (p) *p = '\0';
631 EMSG(buff);
633 break;
634 default:
635 vim_snprintf(buff, BUFSIZ, _("E273: unknown longjmp status %d"), state);
636 EMSG(buff);
637 break;
641 static VALUE vim_message(VALUE self UNUSED, VALUE str)
643 char *buff, *p;
645 str = rb_obj_as_string(str);
646 buff = ALLOCA_N(char, RSTRING_LEN(str));
647 strcpy(buff, RSTRING_PTR(str));
648 p = strchr(buff, '\n');
649 if (p) *p = '\0';
650 MSG(buff);
651 return Qnil;
654 static VALUE vim_set_option(VALUE self UNUSED, VALUE str)
656 do_set((char_u *)StringValuePtr(str), 0);
657 update_screen(NOT_VALID);
658 return Qnil;
661 static VALUE vim_command(VALUE self UNUSED, VALUE str)
663 do_cmdline_cmd((char_u *)StringValuePtr(str));
664 return Qnil;
667 #ifdef FEAT_EVAL
668 static VALUE vim_to_ruby(typval_T *tv)
670 VALUE result = Qnil;
672 if (tv->v_type == VAR_STRING)
674 result = rb_str_new2((char *)tv->vval.v_string);
676 else if (tv->v_type == VAR_NUMBER)
678 result = INT2NUM(tv->vval.v_number);
680 # ifdef FEAT_FLOAT
681 else if (tv->v_type == VAR_FLOAT)
683 result = rb_float_new(tv->vval.v_float);
685 # endif
686 else if (tv->v_type == VAR_LIST)
688 list_T *list = tv->vval.v_list;
689 listitem_T *curr;
691 result = rb_ary_new();
693 if (list != NULL)
695 for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
697 rb_ary_push(result, vim_to_ruby(&curr->li_tv));
701 else if (tv->v_type == VAR_DICT)
703 result = rb_hash_new();
705 if (tv->vval.v_dict != NULL)
707 hashtab_T *ht = &tv->vval.v_dict->dv_hashtab;
708 long_u todo = ht->ht_used;
709 hashitem_T *hi;
710 dictitem_T *di;
712 for (hi = ht->ht_array; todo > 0; ++hi)
714 if (!HASHITEM_EMPTY(hi))
716 --todo;
718 di = dict_lookup(hi);
719 rb_hash_aset(result, rb_str_new2((char *)hi->hi_key),
720 vim_to_ruby(&di->di_tv));
724 } /* else return Qnil; */
726 return result;
728 #endif
730 static VALUE vim_evaluate(VALUE self UNUSED, VALUE str)
732 #ifdef FEAT_EVAL
733 typval_T *tv;
734 VALUE result;
736 tv = eval_expr((char_u *)StringValuePtr(str), NULL);
737 if (tv == NULL)
739 return Qnil;
741 result = vim_to_ruby(tv);
743 free_tv(tv);
745 return result;
746 #else
747 return Qnil;
748 #endif
751 static VALUE buffer_new(buf_T *buf)
753 if (buf->b_ruby_ref)
755 return (VALUE) buf->b_ruby_ref;
757 else
759 VALUE obj = Data_Wrap_Struct(cBuffer, 0, 0, buf);
760 buf->b_ruby_ref = (void *) obj;
761 rb_hash_aset(objtbl, rb_obj_id(obj), obj);
762 return obj;
766 static buf_T *get_buf(VALUE obj)
768 buf_T *buf;
770 Data_Get_Struct(obj, buf_T, buf);
771 if (buf == NULL)
772 rb_raise(eDeletedBufferError, "attempt to refer to deleted buffer");
773 return buf;
776 static VALUE buffer_s_current()
778 return buffer_new(curbuf);
781 static VALUE buffer_s_count()
783 buf_T *b;
784 int n = 0;
786 for (b = firstbuf; b != NULL; b = b->b_next)
788 /* Deleted buffers should not be counted
789 * SegPhault - 01/07/05 */
790 if (b->b_p_bl)
791 n++;
794 return INT2NUM(n);
797 static VALUE buffer_s_aref(VALUE self UNUSED, VALUE num)
799 buf_T *b;
800 int n = NUM2INT(num);
802 for (b = firstbuf; b != NULL; b = b->b_next)
804 /* Deleted buffers should not be counted
805 * SegPhault - 01/07/05 */
806 if (!b->b_p_bl)
807 continue;
809 if (n == 0)
810 return buffer_new(b);
812 n--;
814 return Qnil;
817 static VALUE buffer_name(VALUE self)
819 buf_T *buf = get_buf(self);
821 return buf->b_ffname ? rb_str_new2((char *)buf->b_ffname) : Qnil;
824 static VALUE buffer_number(VALUE self)
826 buf_T *buf = get_buf(self);
828 return INT2NUM(buf->b_fnum);
831 static VALUE buffer_count(VALUE self)
833 buf_T *buf = get_buf(self);
835 return INT2NUM(buf->b_ml.ml_line_count);
838 static VALUE get_buffer_line(buf_T *buf, linenr_T n)
840 if (n > 0 && n <= buf->b_ml.ml_line_count)
842 char *line = (char *)ml_get_buf(buf, n, FALSE);
843 return line ? vim_str2rb_enc_str(line) : Qnil;
845 rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
846 #ifndef __GNUC__
847 return Qnil; /* For stop warning */
848 #endif
851 static VALUE buffer_aref(VALUE self, VALUE num)
853 buf_T *buf = get_buf(self);
855 if (buf != NULL)
856 return get_buffer_line(buf, (linenr_T)NUM2LONG(num));
857 return Qnil; /* For stop warning */
860 static VALUE set_buffer_line(buf_T *buf, linenr_T n, VALUE str)
862 char *line = StringValuePtr(str);
863 aco_save_T aco;
865 if (n > 0 && n <= buf->b_ml.ml_line_count && line != NULL)
867 /* set curwin/curbuf for "buf" and save some things */
868 aucmd_prepbuf(&aco, buf);
870 if (u_savesub(n) == OK) {
871 ml_replace(n, (char_u *)line, TRUE);
872 changed();
873 #ifdef SYNTAX_HL
874 syn_changed(n); /* recompute syntax hl. for this line */
875 #endif
878 /* restore curwin/curbuf and a few other things */
879 aucmd_restbuf(&aco);
880 /* Careful: autocommands may have made "buf" invalid! */
882 update_curbuf(NOT_VALID);
884 else
886 rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
887 #ifndef __GNUC__
888 return Qnil; /* For stop warning */
889 #endif
891 return str;
894 static VALUE buffer_aset(VALUE self, VALUE num, VALUE str)
896 buf_T *buf = get_buf(self);
898 if (buf != NULL)
899 return set_buffer_line(buf, (linenr_T)NUM2LONG(num), str);
900 return str;
903 static VALUE buffer_delete(VALUE self, VALUE num)
905 buf_T *buf = get_buf(self);
906 long n = NUM2LONG(num);
907 aco_save_T aco;
909 if (n > 0 && n <= buf->b_ml.ml_line_count)
911 /* set curwin/curbuf for "buf" and save some things */
912 aucmd_prepbuf(&aco, buf);
914 if (u_savedel(n, 1) == OK) {
915 ml_delete(n, 0);
917 /* Changes to non-active buffers should properly refresh
918 * SegPhault - 01/09/05 */
919 deleted_lines_mark(n, 1L);
921 changed();
924 /* restore curwin/curbuf and a few other things */
925 aucmd_restbuf(&aco);
926 /* Careful: autocommands may have made "buf" invalid! */
928 update_curbuf(NOT_VALID);
930 else
932 rb_raise(rb_eIndexError, "line number %ld out of range", n);
934 return Qnil;
937 static VALUE buffer_append(VALUE self, VALUE num, VALUE str)
939 buf_T *buf = get_buf(self);
940 char *line = StringValuePtr(str);
941 long n = NUM2LONG(num);
942 aco_save_T aco;
944 if (line == NULL) {
945 rb_raise(rb_eIndexError, "NULL line");
947 else if (n >= 0 && n <= buf->b_ml.ml_line_count)
949 /* set curwin/curbuf for "buf" and save some things */
950 aucmd_prepbuf(&aco, buf);
952 if (u_inssub(n + 1) == OK) {
953 ml_append(n, (char_u *) line, (colnr_T) 0, FALSE);
955 /* Changes to non-active buffers should properly refresh screen
956 * SegPhault - 12/20/04 */
957 appended_lines_mark(n, 1L);
959 changed();
962 /* restore curwin/curbuf and a few other things */
963 aucmd_restbuf(&aco);
964 /* Careful: autocommands may have made "buf" invalid! */
966 update_curbuf(NOT_VALID);
968 else {
969 rb_raise(rb_eIndexError, "line number %ld out of range", n);
971 return str;
974 static VALUE window_new(win_T *win)
976 if (win->w_ruby_ref)
978 return (VALUE) win->w_ruby_ref;
980 else
982 VALUE obj = Data_Wrap_Struct(cVimWindow, 0, 0, win);
983 win->w_ruby_ref = (void *) obj;
984 rb_hash_aset(objtbl, rb_obj_id(obj), obj);
985 return obj;
989 static win_T *get_win(VALUE obj)
991 win_T *win;
993 Data_Get_Struct(obj, win_T, win);
994 if (win == NULL)
995 rb_raise(eDeletedWindowError, "attempt to refer to deleted window");
996 return win;
999 static VALUE window_s_current()
1001 return window_new(curwin);
1005 * Added line manipulation functions
1006 * SegPhault - 03/07/05
1008 static VALUE line_s_current()
1010 return get_buffer_line(curbuf, curwin->w_cursor.lnum);
1013 static VALUE set_current_line(VALUE self UNUSED, VALUE str)
1015 return set_buffer_line(curbuf, curwin->w_cursor.lnum, str);
1018 static VALUE current_line_number()
1020 return INT2FIX((int)curwin->w_cursor.lnum);
1025 static VALUE window_s_count()
1027 #ifdef FEAT_WINDOWS
1028 win_T *w;
1029 int n = 0;
1031 for (w = firstwin; w != NULL; w = w->w_next)
1032 n++;
1033 return INT2NUM(n);
1034 #else
1035 return INT2NUM(1);
1036 #endif
1039 static VALUE window_s_aref(VALUE self UNUSED, VALUE num)
1041 win_T *w;
1042 int n = NUM2INT(num);
1044 #ifndef FEAT_WINDOWS
1045 w = curwin;
1046 #else
1047 for (w = firstwin; w != NULL; w = w->w_next, --n)
1048 #endif
1049 if (n == 0)
1050 return window_new(w);
1051 return Qnil;
1054 static VALUE window_buffer(VALUE self)
1056 win_T *win = get_win(self);
1058 return buffer_new(win->w_buffer);
1061 static VALUE window_height(VALUE self)
1063 win_T *win = get_win(self);
1065 return INT2NUM(win->w_height);
1068 static VALUE window_set_height(VALUE self, VALUE height)
1070 win_T *win = get_win(self);
1071 win_T *savewin = curwin;
1073 curwin = win;
1074 win_setheight(NUM2INT(height));
1075 curwin = savewin;
1076 return height;
1079 static VALUE window_width(VALUE self)
1081 win_T *win = get_win(self);
1083 return INT2NUM(win->w_width);
1086 static VALUE window_set_width(VALUE self, VALUE width)
1088 win_T *win = get_win(self);
1089 win_T *savewin = curwin;
1091 curwin = win;
1092 win_setwidth(NUM2INT(width));
1093 curwin = savewin;
1094 return width;
1097 static VALUE window_cursor(VALUE self)
1099 win_T *win = get_win(self);
1101 return rb_assoc_new(INT2NUM(win->w_cursor.lnum), INT2NUM(win->w_cursor.col));
1104 static VALUE window_set_cursor(VALUE self, VALUE pos)
1106 VALUE lnum, col;
1107 win_T *win = get_win(self);
1109 Check_Type(pos, T_ARRAY);
1110 if (RARRAY_LEN(pos) != 2)
1111 rb_raise(rb_eArgError, "array length must be 2");
1112 lnum = RARRAY_PTR(pos)[0];
1113 col = RARRAY_PTR(pos)[1];
1114 win->w_cursor.lnum = NUM2LONG(lnum);
1115 win->w_cursor.col = NUM2UINT(col);
1116 check_cursor(); /* put cursor on an existing line */
1117 update_screen(NOT_VALID);
1118 return Qnil;
1121 static VALUE f_p(int argc, VALUE *argv, VALUE self UNUSED)
1123 int i;
1124 VALUE str = rb_str_new("", 0);
1126 for (i = 0; i < argc; i++) {
1127 if (i > 0) rb_str_cat(str, ", ", 2);
1128 rb_str_concat(str, rb_inspect(argv[i]));
1130 MSG(RSTRING_PTR(str));
1131 return Qnil;
1134 static void ruby_io_init(void)
1136 #ifndef DYNAMIC_RUBY
1137 RUBYEXTERN VALUE rb_stdout;
1138 #endif
1140 rb_stdout = rb_obj_alloc(rb_cObject);
1141 rb_define_singleton_method(rb_stdout, "write", vim_message, 1);
1142 rb_define_global_function("p", f_p, -1);
1145 static void ruby_vim_init(void)
1147 objtbl = rb_hash_new();
1148 rb_global_variable(&objtbl);
1150 /* The Vim module used to be called "VIM", but "Vim" is better. Make an
1151 * alias "VIM" for backwards compatiblity. */
1152 mVIM = rb_define_module("Vim");
1153 rb_define_const(rb_cObject, "VIM", mVIM);
1154 rb_define_const(mVIM, "VERSION_MAJOR", INT2NUM(VIM_VERSION_MAJOR));
1155 rb_define_const(mVIM, "VERSION_MINOR", INT2NUM(VIM_VERSION_MINOR));
1156 rb_define_const(mVIM, "VERSION_BUILD", INT2NUM(VIM_VERSION_BUILD));
1157 rb_define_const(mVIM, "VERSION_PATCHLEVEL", INT2NUM(VIM_VERSION_PATCHLEVEL));
1158 rb_define_const(mVIM, "VERSION_SHORT", rb_str_new2(VIM_VERSION_SHORT));
1159 rb_define_const(mVIM, "VERSION_MEDIUM", rb_str_new2(VIM_VERSION_MEDIUM));
1160 rb_define_const(mVIM, "VERSION_LONG", rb_str_new2(VIM_VERSION_LONG));
1161 rb_define_const(mVIM, "VERSION_LONG_DATE", rb_str_new2(VIM_VERSION_LONG_DATE));
1162 rb_define_module_function(mVIM, "message", vim_message, 1);
1163 rb_define_module_function(mVIM, "set_option", vim_set_option, 1);
1164 rb_define_module_function(mVIM, "command", vim_command, 1);
1165 rb_define_module_function(mVIM, "evaluate", vim_evaluate, 1);
1167 eDeletedBufferError = rb_define_class_under(mVIM, "DeletedBufferError",
1168 rb_eStandardError);
1169 eDeletedWindowError = rb_define_class_under(mVIM, "DeletedWindowError",
1170 rb_eStandardError);
1172 cBuffer = rb_define_class_under(mVIM, "Buffer", rb_cObject);
1173 rb_define_singleton_method(cBuffer, "current", buffer_s_current, 0);
1174 rb_define_singleton_method(cBuffer, "count", buffer_s_count, 0);
1175 rb_define_singleton_method(cBuffer, "[]", buffer_s_aref, 1);
1176 rb_define_method(cBuffer, "name", buffer_name, 0);
1177 rb_define_method(cBuffer, "number", buffer_number, 0);
1178 rb_define_method(cBuffer, "count", buffer_count, 0);
1179 rb_define_method(cBuffer, "length", buffer_count, 0);
1180 rb_define_method(cBuffer, "[]", buffer_aref, 1);
1181 rb_define_method(cBuffer, "[]=", buffer_aset, 2);
1182 rb_define_method(cBuffer, "delete", buffer_delete, 1);
1183 rb_define_method(cBuffer, "append", buffer_append, 2);
1185 /* Added line manipulation functions
1186 * SegPhault - 03/07/05 */
1187 rb_define_method(cBuffer, "line_number", current_line_number, 0);
1188 rb_define_method(cBuffer, "line", line_s_current, 0);
1189 rb_define_method(cBuffer, "line=", set_current_line, 1);
1192 cVimWindow = rb_define_class_under(mVIM, "Window", rb_cObject);
1193 rb_define_singleton_method(cVimWindow, "current", window_s_current, 0);
1194 rb_define_singleton_method(cVimWindow, "count", window_s_count, 0);
1195 rb_define_singleton_method(cVimWindow, "[]", window_s_aref, 1);
1196 rb_define_method(cVimWindow, "buffer", window_buffer, 0);
1197 rb_define_method(cVimWindow, "height", window_height, 0);
1198 rb_define_method(cVimWindow, "height=", window_set_height, 1);
1199 rb_define_method(cVimWindow, "width", window_width, 0);
1200 rb_define_method(cVimWindow, "width=", window_set_width, 1);
1201 rb_define_method(cVimWindow, "cursor", window_cursor, 0);
1202 rb_define_method(cVimWindow, "cursor=", window_set_cursor, 1);
1204 rb_define_virtual_variable("$curbuf", buffer_s_current, 0);
1205 rb_define_virtual_variable("$curwin", window_s_current, 0);