xref: /vim-8.2.3635/src/if_ruby.c (revision 314dd79c)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Ruby interface by Shugo Maeda
6  *   with improvements by SegPhault (Ryan Paul)
7  *   with improvements by Jon Maken
8  *
9  * Do ":help uganda"  in Vim to read copying and usage conditions.
10  * Do ":help credits" in Vim to see a list of people who contributed.
11  * See README.txt for an overview of the Vim source code.
12  */
13 
14 #include "protodef.h"
15 #ifdef HAVE_CONFIG_H
16 # include "auto/config.h"
17 #endif
18 
19 #include <stdio.h>
20 #include <string.h>
21 
22 #ifdef _WIN32
23 # if !defined(DYNAMIC_RUBY_VER) || (DYNAMIC_RUBY_VER < 18)
24 #   define NT
25 # endif
26 # ifndef DYNAMIC_RUBY
27 #  define IMPORT /* For static dll usage __declspec(dllimport) */
28 #  define RUBYEXTERN __declspec(dllimport)
29 # endif
30 #endif
31 #ifndef RUBYEXTERN
32 # define RUBYEXTERN extern
33 #endif
34 
35 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 24
36 # define USE_RUBY_INTEGER
37 #endif
38 
39 #ifdef DYNAMIC_RUBY
40 /*
41  * This is tricky.  In ruby.h there is (inline) function rb_class_of()
42  * definition.  This function use these variables.  But we want function to
43  * use dll_* variables.
44  */
45 # define rb_cFalseClass		(*dll_rb_cFalseClass)
46 # define rb_cFixnum		(*dll_rb_cFixnum)
47 # if defined(USE_RUBY_INTEGER)
48 #  define rb_cInteger		(*dll_rb_cInteger)
49 # endif
50 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
51 #  define rb_cFloat		(*dll_rb_cFloat)
52 # endif
53 # define rb_cNilClass		(*dll_rb_cNilClass)
54 # define rb_cString		(*dll_rb_cString)
55 # define rb_cSymbol		(*dll_rb_cSymbol)
56 # define rb_cTrueClass		(*dll_rb_cTrueClass)
57 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
58 /*
59  * On ver 1.8, all Ruby functions are exported with "__declspec(dllimport)"
60  * in ruby.h.  But it causes trouble for these variables, because it is
61  * defined in this file.  When defined this RUBY_EXPORT it modified to
62  * "extern" and be able to avoid this problem.
63  */
64 #  define RUBY_EXPORT
65 # endif
66 
67 #if !(defined(WIN32) || defined(_WIN64))
68 # include <dlfcn.h>
69 # define HINSTANCE void*
70 # define RUBY_PROC void*
71 # define load_dll(n) dlopen((n), RTLD_LAZY|RTLD_GLOBAL)
72 # define symbol_from_dll dlsym
73 # define close_dll dlclose
74 #else
75 # define RUBY_PROC FARPROC
76 # define load_dll vimLoadLib
77 # define symbol_from_dll GetProcAddress
78 # define close_dll FreeLibrary
79 #endif
80 
81 #endif  /* ifdef DYNAMIC_RUBY */
82 
83 /* suggested by Ariya Mizutani */
84 #if (_MSC_VER == 1200)
85 # undef _WIN32_WINNT
86 #endif
87 
88 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 19) \
89     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19)
90 # define RUBY19_OR_LATER 1
91 #endif
92 
93 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 20) \
94     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20)
95 # define RUBY20_OR_LATER 1
96 #endif
97 
98 #if (defined(RUBY_VERSION) && RUBY_VERSION >= 21) \
99     || (defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 21)
100 # define RUBY21_OR_LATER 1
101 #endif
102 
103 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19
104 /* Ruby 1.9 defines a number of static functions which use rb_num2long and
105  * rb_int2big */
106 # define rb_num2long rb_num2long_stub
107 # define rb_int2big rb_int2big_stub
108 #endif
109 
110 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19 \
111 	&& VIM_SIZEOF_INT < VIM_SIZEOF_LONG
112 /* Ruby 1.9 defines a number of static functions which use rb_fix2int and
113  * rb_num2int if VIM_SIZEOF_INT < VIM_SIZEOF_LONG (64bit) */
114 # define rb_fix2int rb_fix2int_stub
115 # define rb_num2int rb_num2int_stub
116 #endif
117 
118 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
119 /* Ruby 2.1 adds new GC called RGenGC and RARRAY_PTR uses
120  * rb_gc_writebarrier_unprotect_promoted if USE_RGENGC  */
121 # define rb_gc_writebarrier_unprotect_promoted rb_gc_writebarrier_unprotect_promoted_stub
122 #endif
123 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
124 # define rb_gc_writebarrier_unprotect rb_gc_writebarrier_unprotect_stub
125 #endif
126 
127 #if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 26
128 # define rb_ary_detransient rb_ary_detransient_stub
129 #endif
130 
131 #include <ruby.h>
132 #ifdef RUBY19_OR_LATER
133 # include <ruby/encoding.h>
134 #endif
135 
136 #undef off_t	/* ruby defines off_t as _int64, Mingw uses long */
137 #undef EXTERN
138 #undef _
139 
140 /* T_DATA defined both by Ruby and Mac header files, hack around it... */
141 #if defined(MACOS_X)
142 # define __OPENTRANSPORT__
143 # define __OPENTRANSPORTPROTOCOL__
144 # define __OPENTRANSPORTPROVIDERS__
145 #endif
146 
147 /*
148  * The TypedData_XXX macro family can be used since Ruby 1.9.2 but
149  * rb_data_type_t changed in 1.9.3, therefore require at least 2.0.
150  * The old Data_XXX macro family was deprecated on Ruby 2.2.
151  * Use TypedData_XXX if available.
152  */
153 #if defined(TypedData_Wrap_Struct) && defined(RUBY20_OR_LATER)
154 # define USE_TYPEDDATA	1
155 #endif
156 
157 /*
158  * Backward compatibility for Ruby 1.8 and earlier.
159  * Ruby 1.9 does not provide STR2CSTR, instead StringValuePtr is provided.
160  * Ruby 1.9 does not provide RXXX(s)->len and RXXX(s)->ptr, instead
161  * RXXX_LEN(s) and RXXX_PTR(s) are provided.
162  */
163 #ifndef StringValuePtr
164 # define StringValuePtr(s) STR2CSTR(s)
165 #endif
166 #ifndef RARRAY_LEN
167 # define RARRAY_LEN(s) RARRAY(s)->len
168 #endif
169 #ifndef RARRAY_PTR
170 # define RARRAY_PTR(s) RARRAY(s)->ptr
171 #endif
172 #ifndef RSTRING_LEN
173 # define RSTRING_LEN(s) RSTRING(s)->len
174 #endif
175 #ifndef RSTRING_PTR
176 # define RSTRING_PTR(s) RSTRING(s)->ptr
177 #endif
178 
179 #ifdef HAVE_DUP
180 # undef HAVE_DUP
181 #endif
182 
183 #include "vim.h"
184 #include "version.h"
185 
186 #if defined(PROTO) && !defined(FEAT_RUBY)
187 /* Define these to be able to generate the function prototypes. */
188 # define VALUE int
189 # define RUBY_DATA_FUNC int
190 #endif
191 
192 static int ruby_initialized = 0;
193 static void *ruby_stack_start;
194 static VALUE objtbl;
195 
196 static VALUE mVIM;
197 static VALUE cBuffer;
198 static VALUE cVimWindow;
199 static VALUE eDeletedBufferError;
200 static VALUE eDeletedWindowError;
201 
202 static int ensure_ruby_initialized(void);
203 static void error_print(int);
204 static void ruby_io_init(void);
205 static void ruby_vim_init(void);
206 
207 #if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
208 # if defined(__ia64) && !defined(ruby_init_stack)
209 #  define ruby_init_stack(addr) ruby_init_stack((addr), rb_ia64_bsp())
210 # endif
211 #endif
212 
213 #if defined(DYNAMIC_RUBY) || defined(PROTO)
214 # if defined(PROTO) && !defined(HINSTANCE)
215 #  define HINSTANCE int		/* for generating prototypes */
216 # endif
217 
218 /*
219  * Wrapper defines
220  */
221 # define rb_assoc_new			dll_rb_assoc_new
222 # define rb_cObject			(*dll_rb_cObject)
223 # define rb_class_new_instance		dll_rb_class_new_instance
224 # define rb_check_type			dll_rb_check_type
225 # ifdef USE_TYPEDDATA
226 #  define rb_check_typeddata		dll_rb_check_typeddata
227 # endif
228 # define rb_class_path			dll_rb_class_path
229 # ifdef USE_TYPEDDATA
230 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
231 #   define rb_data_typed_object_wrap	dll_rb_data_typed_object_wrap
232 #  else
233 #   define rb_data_typed_object_alloc	dll_rb_data_typed_object_alloc
234 #  endif
235 # else
236 #  define rb_data_object_alloc		dll_rb_data_object_alloc
237 # endif
238 # define rb_define_class_under		dll_rb_define_class_under
239 # define rb_define_const			dll_rb_define_const
240 # define rb_define_global_function	dll_rb_define_global_function
241 # define rb_define_method		dll_rb_define_method
242 # define rb_define_module		dll_rb_define_module
243 # define rb_define_module_function	dll_rb_define_module_function
244 # define rb_define_singleton_method	dll_rb_define_singleton_method
245 # define rb_define_virtual_variable	dll_rb_define_virtual_variable
246 # define rb_stdout			(*dll_rb_stdout)
247 # define rb_stderr			(*dll_rb_stderr)
248 # define rb_eArgError			(*dll_rb_eArgError)
249 # define rb_eIndexError			(*dll_rb_eIndexError)
250 # define rb_eRuntimeError		(*dll_rb_eRuntimeError)
251 # define rb_eStandardError		(*dll_rb_eStandardError)
252 # define rb_eval_string_protect		dll_rb_eval_string_protect
253 # ifdef RUBY21_OR_LATER
254 #  define rb_funcallv			dll_rb_funcallv
255 # else
256 #  define rb_funcall2			dll_rb_funcall2
257 # endif
258 # define rb_global_variable		dll_rb_global_variable
259 # define rb_hash_aset			dll_rb_hash_aset
260 # define rb_hash_new			dll_rb_hash_new
261 # define rb_inspect			dll_rb_inspect
262 # define rb_int2inum			dll_rb_int2inum
263 
264 // ruby.h may redefine rb_intern to use RUBY_CONST_ID_CACHE(), but that won't
265 // work.  Not using the cache appears to be the best solution.
266 # undef rb_intern
267 # define rb_intern			dll_rb_intern
268 
269 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
270 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER <= 18
271 #   define rb_fix2int			dll_rb_fix2int
272 #   define rb_num2int			dll_rb_num2int
273 #  endif
274 #  define rb_num2uint			dll_rb_num2uint
275 # endif
276 # define rb_lastline_get			dll_rb_lastline_get
277 # define rb_lastline_set			dll_rb_lastline_set
278 # define rb_protect			dll_rb_protect
279 # define rb_load			dll_rb_load
280 # ifndef RUBY19_OR_LATER
281 #  define rb_num2long			dll_rb_num2long
282 # endif
283 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER <= 19
284 #  define rb_num2ulong			dll_rb_num2ulong
285 # endif
286 # define rb_obj_alloc			dll_rb_obj_alloc
287 # define rb_obj_as_string		dll_rb_obj_as_string
288 # define rb_obj_id			dll_rb_obj_id
289 # define rb_raise			dll_rb_raise
290 # define rb_str_cat			dll_rb_str_cat
291 # define rb_str_concat			dll_rb_str_concat
292 # undef rb_str_new
293 # define rb_str_new			dll_rb_str_new
294 # ifdef rb_str_new2
295 /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */
296 #  define need_rb_str_new_cstr 1
297 /* Ruby's headers #define rb_str_new_cstr to make use of GCC's
298  * __builtin_constant_p extension. */
299 #  undef rb_str_new_cstr
300 #  define rb_str_new_cstr		dll_rb_str_new_cstr
301 # else
302 #  define rb_str_new2			dll_rb_str_new2
303 # endif
304 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
305 #  define rb_string_value		dll_rb_string_value
306 #  define rb_string_value_ptr		dll_rb_string_value_ptr
307 #  define rb_float_new			dll_rb_float_new
308 #  define rb_ary_new			dll_rb_ary_new
309 #  ifdef rb_ary_new4
310 #    define RB_ARY_NEW4_MACRO 1
311 #    undef rb_ary_new4
312 #  endif
313 #  define rb_ary_new4			dll_rb_ary_new4
314 #  define rb_ary_push			dll_rb_ary_push
315 #  if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
316 #   ifdef __ia64
317 #    define rb_ia64_bsp			dll_rb_ia64_bsp
318 #    undef ruby_init_stack
319 #    define ruby_init_stack(addr)	dll_ruby_init_stack((addr), rb_ia64_bsp())
320 #   else
321 #    define ruby_init_stack		dll_ruby_init_stack
322 #   endif
323 #  endif
324 # else
325 #  define rb_str2cstr			dll_rb_str2cstr
326 # endif
327 # ifdef RUBY19_OR_LATER
328 #  define rb_errinfo			dll_rb_errinfo
329 # else
330 #  define ruby_errinfo			(*dll_ruby_errinfo)
331 # endif
332 # define ruby_init			dll_ruby_init
333 # define ruby_init_loadpath		dll_ruby_init_loadpath
334 # ifdef WIN3264
335 #  ifdef RUBY19_OR_LATER
336 #   define ruby_sysinit			dll_ruby_sysinit
337 #  else
338 #   define NtInitialize			dll_NtInitialize
339 #  endif
340 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
341 #   define rb_w32_snprintf		dll_rb_w32_snprintf
342 #  endif
343 # endif
344 
345 # ifdef RUBY19_OR_LATER
346 #  define ruby_script			dll_ruby_script
347 #  define rb_enc_find_index		dll_rb_enc_find_index
348 #  define rb_enc_find			dll_rb_enc_find
349 #  undef rb_enc_str_new
350 #  define rb_enc_str_new		dll_rb_enc_str_new
351 #  define rb_sprintf			dll_rb_sprintf
352 #  define rb_require			dll_rb_require
353 #  define ruby_options			dll_ruby_options
354 # endif
355 
356 /*
357  * Pointers for dynamic link
358  */
359 static VALUE (*dll_rb_assoc_new) (VALUE, VALUE);
360 VALUE *dll_rb_cFalseClass;
361 VALUE *dll_rb_cFixnum;
362 # if defined(USE_RUBY_INTEGER)
363 VALUE *dll_rb_cInteger;
364 # endif
365 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
366 VALUE *dll_rb_cFloat;
367 # endif
368 VALUE *dll_rb_cNilClass;
369 static VALUE *dll_rb_cObject;
370 VALUE *dll_rb_cString;
371 VALUE *dll_rb_cSymbol;
372 VALUE *dll_rb_cTrueClass;
373 static VALUE (*dll_rb_class_new_instance) (int,VALUE*,VALUE);
374 static void (*dll_rb_check_type) (VALUE,int);
375 # ifdef USE_TYPEDDATA
376 static void *(*dll_rb_check_typeddata) (VALUE,const rb_data_type_t *);
377 # endif
378 static VALUE (*dll_rb_class_path) (VALUE);
379 # ifdef USE_TYPEDDATA
380 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
381 static VALUE (*dll_rb_data_typed_object_wrap) (VALUE, void*, const rb_data_type_t *);
382 #  else
383 static VALUE (*dll_rb_data_typed_object_alloc) (VALUE, void*, const rb_data_type_t *);
384 #  endif
385 # else
386 static VALUE (*dll_rb_data_object_alloc) (VALUE, void*, RUBY_DATA_FUNC, RUBY_DATA_FUNC);
387 # endif
388 static VALUE (*dll_rb_define_class_under) (VALUE, const char*, VALUE);
389 static void (*dll_rb_define_const) (VALUE,const char*,VALUE);
390 static void (*dll_rb_define_global_function) (const char*,VALUE(*)(),int);
391 static void (*dll_rb_define_method) (VALUE,const char*,VALUE(*)(),int);
392 static VALUE (*dll_rb_define_module) (const char*);
393 static void (*dll_rb_define_module_function) (VALUE,const char*,VALUE(*)(),int);
394 static void (*dll_rb_define_singleton_method) (VALUE,const char*,VALUE(*)(),int);
395 static void (*dll_rb_define_virtual_variable) (const char*,VALUE(*)(),void(*)());
396 static VALUE *dll_rb_stdout;
397 static VALUE *dll_rb_stderr;
398 static VALUE *dll_rb_eArgError;
399 static VALUE *dll_rb_eIndexError;
400 static VALUE *dll_rb_eRuntimeError;
401 static VALUE *dll_rb_eStandardError;
402 static VALUE (*dll_rb_eval_string_protect) (const char*, int*);
403 # ifdef RUBY21_OR_LATER
404 static VALUE (*dll_rb_funcallv) (VALUE, ID, int, const VALUE*);
405 # else
406 static VALUE (*dll_rb_funcall2) (VALUE, ID, int, const VALUE*);
407 # endif
408 static void (*dll_rb_global_variable) (VALUE*);
409 static VALUE (*dll_rb_hash_aset) (VALUE, VALUE, VALUE);
410 static VALUE (*dll_rb_hash_new) (void);
411 static VALUE (*dll_rb_inspect) (VALUE);
412 static VALUE (*dll_rb_int2inum) (long);
413 static ID (*dll_rb_intern) (const char*);
414 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
415 static long (*dll_rb_fix2int) (VALUE);
416 static long (*dll_rb_num2int) (VALUE);
417 static unsigned long (*dll_rb_num2uint) (VALUE);
418 # endif
419 static VALUE (*dll_rb_lastline_get) (void);
420 static void (*dll_rb_lastline_set) (VALUE);
421 static VALUE (*dll_rb_protect) (VALUE (*)(VALUE), VALUE, int*);
422 static void (*dll_rb_load) (VALUE, int);
423 static long (*dll_rb_num2long) (VALUE);
424 static unsigned long (*dll_rb_num2ulong) (VALUE);
425 static VALUE (*dll_rb_obj_alloc) (VALUE);
426 static VALUE (*dll_rb_obj_as_string) (VALUE);
427 static VALUE (*dll_rb_obj_id) (VALUE);
428 static void (*dll_rb_raise) (VALUE, const char*, ...);
429 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
430 static VALUE (*dll_rb_string_value) (volatile VALUE*);
431 # else
432 static char *(*dll_rb_str2cstr) (VALUE,int*);
433 # endif
434 static VALUE (*dll_rb_str_cat) (VALUE, const char*, long);
435 static VALUE (*dll_rb_str_concat) (VALUE, VALUE);
436 static VALUE (*dll_rb_str_new) (const char*, long);
437 # ifdef need_rb_str_new_cstr
438 /* Ruby may #define rb_str_new2 to use rb_str_new_cstr. */
439 static VALUE (*dll_rb_str_new_cstr) (const char*);
440 # else
441 static VALUE (*dll_rb_str_new2) (const char*);
442 # endif
443 # ifdef RUBY19_OR_LATER
444 static VALUE (*dll_rb_errinfo) (void);
445 # else
446 static VALUE *dll_ruby_errinfo;
447 # endif
448 static void (*dll_ruby_init) (void);
449 static void (*dll_ruby_init_loadpath) (void);
450 # ifdef WIN3264
451 #  ifdef RUBY19_OR_LATER
452 static void (*dll_ruby_sysinit) (int*, char***);
453 #  else
454 static void (*dll_NtInitialize) (int*, char***);
455 #  endif
456 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
457 static int (*dll_rb_w32_snprintf)(char*, size_t, const char*, ...);
458 #  endif
459 # endif
460 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
461 static char * (*dll_rb_string_value_ptr) (volatile VALUE*);
462 static VALUE (*dll_rb_float_new) (double);
463 static VALUE (*dll_rb_ary_new) (void);
464 static VALUE (*dll_rb_ary_new4) (long n, const VALUE *elts);
465 static VALUE (*dll_rb_ary_push) (VALUE, VALUE);
466 #  if DYNAMIC_RUBY_VER >= 26
467 static void (*dll_rb_ary_detransient) (VALUE);
468 #  endif
469 #  if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
470 #   ifdef __ia64
471 static void * (*dll_rb_ia64_bsp) (void);
472 static void (*dll_ruby_init_stack)(VALUE*, void*);
473 #   else
474 static void (*dll_ruby_init_stack)(VALUE*);
475 #   endif
476 #  endif
477 # endif
478 # ifdef RUBY19_OR_LATER
479 static VALUE (*dll_rb_int2big)(SIGNED_VALUE);
480 # endif
481 
482 # ifdef RUBY19_OR_LATER
483 static void (*dll_ruby_script) (const char*);
484 static int (*dll_rb_enc_find_index) (const char*);
485 static rb_encoding* (*dll_rb_enc_find) (const char*);
486 static VALUE (*dll_rb_enc_str_new) (const char*, long, rb_encoding*);
487 static VALUE (*dll_rb_sprintf) (const char*, ...);
488 static VALUE (*dll_rb_require) (const char*);
489 static void* (*ruby_options)(int, char**);
490 # endif
491 
492 # if defined(USE_RGENGC) && USE_RGENGC
493 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
494 static void (*dll_rb_gc_writebarrier_unprotect_promoted)(VALUE);
495 #  else
496 static void (*dll_rb_gc_writebarrier_unprotect)(VALUE obj);
497 #  endif
498 # endif
499 
500 # if defined(RUBY19_OR_LATER) && !defined(PROTO)
501 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
502 long rb_num2long_stub(VALUE x)
503 #  else
504 SIGNED_VALUE rb_num2long_stub(VALUE x)
505 #  endif
506 {
507     return dll_rb_num2long(x);
508 }
509 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 26
510 VALUE rb_int2big_stub(intptr_t x)
511 #  else
512 VALUE rb_int2big_stub(SIGNED_VALUE x)
513 #  endif
514 {
515     return dll_rb_int2big(x);
516 }
517 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 19 \
518 	&& VIM_SIZEOF_INT < VIM_SIZEOF_LONG
519 long rb_fix2int_stub(VALUE x)
520 {
521     return dll_rb_fix2int(x);
522 }
523 long rb_num2int_stub(VALUE x)
524 {
525     return dll_rb_num2int(x);
526 }
527 #  endif
528 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
529 VALUE
530 rb_float_new_in_heap(double d)
531 {
532     return dll_rb_float_new(d);
533 }
534 #   if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 22
535 unsigned long rb_num2ulong(VALUE x)
536 #   else
537 VALUE rb_num2ulong(VALUE x)
538 #   endif
539 {
540     return (long)RSHIFT((SIGNED_VALUE)(x),1);
541 }
542 #  endif
543 # endif
544 
545    /* Do not generate a prototype here, VALUE isn't always defined. */
546 # if defined(USE_RGENGC) && USE_RGENGC && !defined(PROTO)
547 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
548 void rb_gc_writebarrier_unprotect_promoted_stub(VALUE obj)
549 {
550     dll_rb_gc_writebarrier_unprotect_promoted(obj);
551 }
552 #  else
553 void rb_gc_writebarrier_unprotect_stub(VALUE obj)
554 {
555     dll_rb_gc_writebarrier_unprotect(obj);
556 }
557 #  endif
558 # endif
559 
560 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 26
561 void rb_ary_detransient_stub(VALUE x)
562 {
563     dll_rb_ary_detransient(x);
564 }
565 # endif
566 
567 static HINSTANCE hinstRuby = NULL; /* Instance of ruby.dll */
568 
569 /*
570  * Table of name to function pointer of ruby.
571  */
572 static struct
573 {
574     char *name;
575     RUBY_PROC *ptr;
576 } ruby_funcname_table[] =
577 {
578     {"rb_assoc_new", (RUBY_PROC*)&dll_rb_assoc_new},
579     {"rb_cFalseClass", (RUBY_PROC*)&dll_rb_cFalseClass},
580 # if defined(USE_RUBY_INTEGER)
581     {"rb_cInteger", (RUBY_PROC*)&dll_rb_cInteger},
582 # else
583     {"rb_cFixnum", (RUBY_PROC*)&dll_rb_cFixnum},
584 # endif
585 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 20
586     {"rb_cFloat", (RUBY_PROC*)&dll_rb_cFloat},
587 # endif
588     {"rb_cNilClass", (RUBY_PROC*)&dll_rb_cNilClass},
589     {"rb_cObject", (RUBY_PROC*)&dll_rb_cObject},
590     {"rb_cString", (RUBY_PROC*)&dll_rb_cString},
591     {"rb_cSymbol", (RUBY_PROC*)&dll_rb_cSymbol},
592     {"rb_cTrueClass", (RUBY_PROC*)&dll_rb_cTrueClass},
593     {"rb_class_new_instance", (RUBY_PROC*)&dll_rb_class_new_instance},
594     {"rb_check_type", (RUBY_PROC*)&dll_rb_check_type},
595 # ifdef USE_TYPEDDATA
596     {"rb_check_typeddata", (RUBY_PROC*)&dll_rb_check_typeddata},
597 # endif
598     {"rb_class_path", (RUBY_PROC*)&dll_rb_class_path},
599 # ifdef USE_TYPEDDATA
600 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 23
601     {"rb_data_typed_object_wrap", (RUBY_PROC*)&dll_rb_data_typed_object_wrap},
602 #  else
603     {"rb_data_typed_object_alloc", (RUBY_PROC*)&dll_rb_data_typed_object_alloc},
604 #  endif
605 # else
606     {"rb_data_object_alloc", (RUBY_PROC*)&dll_rb_data_object_alloc},
607 # endif
608     {"rb_define_class_under", (RUBY_PROC*)&dll_rb_define_class_under},
609     {"rb_define_const", (RUBY_PROC*)&dll_rb_define_const},
610     {"rb_define_global_function", (RUBY_PROC*)&dll_rb_define_global_function},
611     {"rb_define_method", (RUBY_PROC*)&dll_rb_define_method},
612     {"rb_define_module", (RUBY_PROC*)&dll_rb_define_module},
613     {"rb_define_module_function", (RUBY_PROC*)&dll_rb_define_module_function},
614     {"rb_define_singleton_method", (RUBY_PROC*)&dll_rb_define_singleton_method},
615     {"rb_define_virtual_variable", (RUBY_PROC*)&dll_rb_define_virtual_variable},
616     {"rb_stdout", (RUBY_PROC*)&dll_rb_stdout},
617     {"rb_stderr", (RUBY_PROC*)&dll_rb_stderr},
618     {"rb_eArgError", (RUBY_PROC*)&dll_rb_eArgError},
619     {"rb_eIndexError", (RUBY_PROC*)&dll_rb_eIndexError},
620     {"rb_eRuntimeError", (RUBY_PROC*)&dll_rb_eRuntimeError},
621     {"rb_eStandardError", (RUBY_PROC*)&dll_rb_eStandardError},
622     {"rb_eval_string_protect", (RUBY_PROC*)&dll_rb_eval_string_protect},
623 # ifdef RUBY21_OR_LATER
624     {"rb_funcallv", (RUBY_PROC*)&dll_rb_funcallv},
625 # else
626     {"rb_funcall2", (RUBY_PROC*)&dll_rb_funcall2},
627 # endif
628     {"rb_global_variable", (RUBY_PROC*)&dll_rb_global_variable},
629     {"rb_hash_aset", (RUBY_PROC*)&dll_rb_hash_aset},
630     {"rb_hash_new", (RUBY_PROC*)&dll_rb_hash_new},
631     {"rb_inspect", (RUBY_PROC*)&dll_rb_inspect},
632     {"rb_int2inum", (RUBY_PROC*)&dll_rb_int2inum},
633     {"rb_intern", (RUBY_PROC*)&dll_rb_intern},
634 # if VIM_SIZEOF_INT < VIM_SIZEOF_LONG /* 64 bits only */
635     {"rb_fix2int", (RUBY_PROC*)&dll_rb_fix2int},
636     {"rb_num2int", (RUBY_PROC*)&dll_rb_num2int},
637     {"rb_num2uint", (RUBY_PROC*)&dll_rb_num2uint},
638 # endif
639     {"rb_lastline_get", (RUBY_PROC*)&dll_rb_lastline_get},
640     {"rb_lastline_set", (RUBY_PROC*)&dll_rb_lastline_set},
641     {"rb_protect", (RUBY_PROC*)&dll_rb_protect},
642     {"rb_load", (RUBY_PROC*)&dll_rb_load},
643     {"rb_num2long", (RUBY_PROC*)&dll_rb_num2long},
644     {"rb_num2ulong", (RUBY_PROC*)&dll_rb_num2ulong},
645     {"rb_obj_alloc", (RUBY_PROC*)&dll_rb_obj_alloc},
646     {"rb_obj_as_string", (RUBY_PROC*)&dll_rb_obj_as_string},
647     {"rb_obj_id", (RUBY_PROC*)&dll_rb_obj_id},
648     {"rb_raise", (RUBY_PROC*)&dll_rb_raise},
649 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
650     {"rb_string_value", (RUBY_PROC*)&dll_rb_string_value},
651 # else
652     {"rb_str2cstr", (RUBY_PROC*)&dll_rb_str2cstr},
653 # endif
654     {"rb_str_cat", (RUBY_PROC*)&dll_rb_str_cat},
655     {"rb_str_concat", (RUBY_PROC*)&dll_rb_str_concat},
656     {"rb_str_new", (RUBY_PROC*)&dll_rb_str_new},
657 # ifdef need_rb_str_new_cstr
658     {"rb_str_new_cstr", (RUBY_PROC*)&dll_rb_str_new_cstr},
659 # else
660     {"rb_str_new2", (RUBY_PROC*)&dll_rb_str_new2},
661 # endif
662 # ifdef RUBY19_OR_LATER
663     {"rb_errinfo", (RUBY_PROC*)&dll_rb_errinfo},
664 # else
665     {"ruby_errinfo", (RUBY_PROC*)&dll_ruby_errinfo},
666 # endif
667     {"ruby_init", (RUBY_PROC*)&dll_ruby_init},
668     {"ruby_init_loadpath", (RUBY_PROC*)&dll_ruby_init_loadpath},
669 # ifdef WIN3264
670 #  ifdef RUBY19_OR_LATER
671     {"ruby_sysinit", (RUBY_PROC*)&dll_ruby_sysinit},
672 #  else
673     {"NtInitialize", (RUBY_PROC*)&dll_NtInitialize},
674 #  endif
675 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
676     {"rb_w32_snprintf", (RUBY_PROC*)&dll_rb_w32_snprintf},
677 #  endif
678 # endif
679 # if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER >= 18
680     {"rb_string_value_ptr", (RUBY_PROC*)&dll_rb_string_value_ptr},
681 #  if DYNAMIC_RUBY_VER <= 19
682     {"rb_float_new", (RUBY_PROC*)&dll_rb_float_new},
683 #  else
684     {"rb_float_new_in_heap", (RUBY_PROC*)&dll_rb_float_new},
685 #  endif
686     {"rb_ary_new", (RUBY_PROC*)&dll_rb_ary_new},
687 #  ifdef RB_ARY_NEW4_MACRO
688     {"rb_ary_new_from_values", (RUBY_PROC*)&dll_rb_ary_new4},
689 #  else
690     {"rb_ary_new4", (RUBY_PROC*)&dll_rb_ary_new4},
691 #  endif
692     {"rb_ary_push", (RUBY_PROC*)&dll_rb_ary_push},
693 #  if DYNAMIC_RUBY_VER >= 26
694     {"rb_ary_detransient", (RUBY_PROC*)&dll_rb_ary_detransient},
695 #  endif
696 # endif
697 # ifdef RUBY19_OR_LATER
698     {"rb_int2big", (RUBY_PROC*)&dll_rb_int2big},
699     {"ruby_script", (RUBY_PROC*)&dll_ruby_script},
700     {"rb_enc_find_index", (RUBY_PROC*)&dll_rb_enc_find_index},
701     {"rb_enc_find", (RUBY_PROC*)&dll_rb_enc_find},
702     {"rb_enc_str_new", (RUBY_PROC*)&dll_rb_enc_str_new},
703     {"rb_sprintf", (RUBY_PROC*)&dll_rb_sprintf},
704     {"rb_require", (RUBY_PROC*)&dll_rb_require},
705     {"ruby_options", (RUBY_PROC*)&dll_ruby_options},
706 # endif
707 # if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
708 #  ifdef __ia64
709     {"rb_ia64_bsp", (RUBY_PROC*)&dll_rb_ia64_bsp},
710 #  endif
711     {"ruby_init_stack", (RUBY_PROC*)&dll_ruby_init_stack},
712 # endif
713 # if defined(USE_RGENGC) && USE_RGENGC
714 #  if defined(DYNAMIC_RUBY_VER) && DYNAMIC_RUBY_VER == 21
715     {"rb_gc_writebarrier_unprotect_promoted", (RUBY_PROC*)&dll_rb_gc_writebarrier_unprotect_promoted},
716 #  else
717     {"rb_gc_writebarrier_unprotect", (RUBY_PROC*)&dll_rb_gc_writebarrier_unprotect},
718 #  endif
719 # endif
720     {"", NULL},
721 };
722 
723 /*
724  * Free ruby.dll
725  */
726     static void
727 end_dynamic_ruby(void)
728 {
729     if (hinstRuby)
730     {
731 	close_dll(hinstRuby);
732 	hinstRuby = NULL;
733     }
734 }
735 
736 /*
737  * Load library and get all pointers.
738  * Parameter 'libname' provides name of DLL.
739  * Return OK or FAIL.
740  */
741     static int
742 ruby_runtime_link_init(char *libname, int verbose)
743 {
744     int i;
745 
746     if (hinstRuby)
747 	return OK;
748     hinstRuby = load_dll(libname);
749     if (!hinstRuby)
750     {
751 	if (verbose)
752 	    semsg(_(e_loadlib), libname);
753 	return FAIL;
754     }
755 
756     for (i = 0; ruby_funcname_table[i].ptr; ++i)
757     {
758 	if (!(*ruby_funcname_table[i].ptr = symbol_from_dll(hinstRuby,
759 			ruby_funcname_table[i].name)))
760 	{
761 	    close_dll(hinstRuby);
762 	    hinstRuby = NULL;
763 	    if (verbose)
764 		semsg(_(e_loadfunc), ruby_funcname_table[i].name);
765 	    return FAIL;
766 	}
767     }
768     return OK;
769 }
770 
771 /*
772  * If ruby is enabled (there is installed ruby on Windows system) return TRUE,
773  * else FALSE.
774  */
775     int
776 ruby_enabled(int verbose)
777 {
778     return ruby_runtime_link_init((char *)p_rubydll, verbose) == OK;
779 }
780 #endif /* defined(DYNAMIC_RUBY) || defined(PROTO) */
781 
782     void
783 ruby_end(void)
784 {
785 #ifdef DYNAMIC_RUBY
786     end_dynamic_ruby();
787 #endif
788 }
789 
790 void ex_ruby(exarg_T *eap)
791 {
792     int state;
793     char *script = NULL;
794 
795     script = (char *)script_get(eap, eap->arg);
796     if (!eap->skip && ensure_ruby_initialized())
797     {
798 	if (script == NULL)
799 	    rb_eval_string_protect((char *)eap->arg, &state);
800 	else
801 	    rb_eval_string_protect(script, &state);
802 	if (state)
803 	    error_print(state);
804     }
805     vim_free(script);
806 }
807 
808 /*
809  *  In Ruby 1.9 or later, ruby String object has encoding.
810  *  conversion buffer string of vim to ruby String object using
811  *  VIM encoding option.
812  */
813     static VALUE
814 vim_str2rb_enc_str(const char *s)
815 {
816 #ifdef RUBY19_OR_LATER
817     int isnum;
818     long lval;
819     char_u *sval;
820     rb_encoding *enc;
821 
822     isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
823     if (isnum == 0)
824     {
825 	enc = rb_enc_find((char *)sval);
826 	vim_free(sval);
827 	if (enc)
828 	{
829 	    return rb_enc_str_new(s, (long)strlen(s), enc);
830 	}
831     }
832 #endif
833     return rb_str_new2(s);
834 }
835 
836     static VALUE
837 eval_enc_string_protect(const char *str, int *state)
838 {
839 #ifdef RUBY19_OR_LATER
840     int isnum;
841     long lval;
842     char_u *sval;
843     rb_encoding *enc;
844     VALUE v;
845 
846     isnum = get_option_value((char_u *)"enc", &lval, &sval, 0);
847     if (isnum == 0)
848     {
849 	enc = rb_enc_find((char *)sval);
850 	vim_free(sval);
851 	if (enc)
852 	{
853 	    v = rb_sprintf("#-*- coding:%s -*-\n%s", rb_enc_name(enc), str);
854 	    return rb_eval_string_protect(StringValuePtr(v), state);
855 	}
856     }
857 #endif
858     return rb_eval_string_protect(str, state);
859 }
860 
861 void ex_rubydo(exarg_T *eap)
862 {
863     int state;
864     linenr_T i;
865     buf_T   *was_curbuf = curbuf;
866 
867     if (ensure_ruby_initialized())
868     {
869 	if (u_save(eap->line1 - 1, eap->line2 + 1) != OK)
870 	    return;
871 	for (i = eap->line1; i <= eap->line2; i++)
872 	{
873 	    VALUE line;
874 
875 	    if (i > curbuf->b_ml.ml_line_count)
876 		break;
877 	    line = vim_str2rb_enc_str((char *)ml_get(i));
878 	    rb_lastline_set(line);
879 	    eval_enc_string_protect((char *) eap->arg, &state);
880 	    if (state)
881 	    {
882 		error_print(state);
883 		break;
884 	    }
885 	    if (was_curbuf != curbuf)
886 		break;
887 	    line = rb_lastline_get();
888 	    if (!NIL_P(line))
889 	    {
890 		if (TYPE(line) != T_STRING)
891 		{
892 		    emsg(_("E265: $_ must be an instance of String"));
893 		    return;
894 		}
895 		ml_replace(i, (char_u *) StringValuePtr(line), 1);
896 		changed();
897 #ifdef SYNTAX_HL
898 		syn_changed(i); /* recompute syntax hl. for this line */
899 #endif
900 	    }
901 	}
902 	check_cursor();
903 	update_curbuf(NOT_VALID);
904     }
905 }
906 
907 static VALUE rb_load_wrap(VALUE file_to_load)
908 {
909     rb_load(file_to_load, 0);
910     return Qnil;
911 }
912 
913 void ex_rubyfile(exarg_T *eap)
914 {
915     int state;
916 
917     if (ensure_ruby_initialized())
918     {
919 	VALUE file_to_load = rb_str_new2((const char *)eap->arg);
920 	rb_protect(rb_load_wrap, file_to_load, &state);
921 	if (state)
922 	    error_print(state);
923     }
924 }
925 
926 void ruby_buffer_free(buf_T *buf)
927 {
928     if (buf->b_ruby_ref)
929     {
930 	rb_hash_aset(objtbl, rb_obj_id((VALUE) buf->b_ruby_ref), Qnil);
931 	RDATA(buf->b_ruby_ref)->data = NULL;
932     }
933 }
934 
935 void ruby_window_free(win_T *win)
936 {
937     if (win->w_ruby_ref)
938     {
939 	rb_hash_aset(objtbl, rb_obj_id((VALUE) win->w_ruby_ref), Qnil);
940 	RDATA(win->w_ruby_ref)->data = NULL;
941     }
942 }
943 
944 static int ensure_ruby_initialized(void)
945 {
946     if (!ruby_initialized)
947     {
948 #ifdef DYNAMIC_RUBY
949 	if (ruby_enabled(TRUE))
950 	{
951 #endif
952 #ifdef _WIN32
953 	    /* suggested by Ariya Mizutani */
954 	    int argc = 1;
955 	    char *argv[] = {"gvim.exe"};
956 	    char **argvp = argv;
957 # ifdef RUBY19_OR_LATER
958 	    ruby_sysinit(&argc, &argvp);
959 # else
960 	    NtInitialize(&argc, &argvp);
961 # endif
962 #endif
963 	    {
964 #if defined(RUBY19_OR_LATER) || defined(RUBY_INIT_STACK)
965 		ruby_init_stack(ruby_stack_start);
966 #endif
967 		ruby_init();
968 	    }
969 #ifdef RUBY19_OR_LATER
970 	    {
971 		int dummy_argc = 2;
972 		char *dummy_argv[] = {"vim-ruby", "-e_=0"};
973 		ruby_options(dummy_argc, dummy_argv);
974 	    }
975 	    ruby_script("vim-ruby");
976 #else
977 	    ruby_init_loadpath();
978 #endif
979 	    ruby_io_init();
980 	    ruby_vim_init();
981 	    ruby_initialized = 1;
982 #ifdef DYNAMIC_RUBY
983 	}
984 	else
985 	{
986 	    emsg(_("E266: Sorry, this command is disabled, the Ruby library could not be loaded."));
987 	    return 0;
988 	}
989 #endif
990     }
991     return ruby_initialized;
992 }
993 
994 static void error_print(int state)
995 {
996 #if !defined(DYNAMIC_RUBY) && !defined(RUBY19_OR_LATER)
997     RUBYEXTERN VALUE ruby_errinfo;
998 #endif
999     VALUE error;
1000     VALUE eclass;
1001     VALUE einfo;
1002     VALUE bt;
1003     int attr;
1004     char buff[BUFSIZ];
1005     long i;
1006 
1007 #define TAG_RETURN	0x1
1008 #define TAG_BREAK	0x2
1009 #define TAG_NEXT	0x3
1010 #define TAG_RETRY	0x4
1011 #define TAG_REDO	0x5
1012 #define TAG_RAISE	0x6
1013 #define TAG_THROW	0x7
1014 #define TAG_FATAL	0x8
1015 #define TAG_MASK	0xf
1016 
1017     switch (state)
1018     {
1019     case TAG_RETURN:
1020 	emsg(_("E267: unexpected return"));
1021 	break;
1022     case TAG_NEXT:
1023 	emsg(_("E268: unexpected next"));
1024 	break;
1025     case TAG_BREAK:
1026 	emsg(_("E269: unexpected break"));
1027 	break;
1028     case TAG_REDO:
1029 	emsg(_("E270: unexpected redo"));
1030 	break;
1031     case TAG_RETRY:
1032 	emsg(_("E271: retry outside of rescue clause"));
1033 	break;
1034     case TAG_RAISE:
1035     case TAG_FATAL:
1036 #ifdef RUBY19_OR_LATER
1037 	error = rb_errinfo();
1038 #else
1039 	error = ruby_errinfo;
1040 #endif
1041 	eclass = CLASS_OF(error);
1042 	einfo = rb_obj_as_string(error);
1043 	if (eclass == rb_eRuntimeError && RSTRING_LEN(einfo) == 0)
1044 	{
1045 	    emsg(_("E272: unhandled exception"));
1046 	}
1047 	else
1048 	{
1049 	    VALUE epath;
1050 	    char *p;
1051 
1052 	    epath = rb_class_path(eclass);
1053 	    vim_snprintf(buff, BUFSIZ, "%s: %s",
1054 		     RSTRING_PTR(epath), RSTRING_PTR(einfo));
1055 	    p = strchr(buff, '\n');
1056 	    if (p) *p = '\0';
1057 	    emsg(buff);
1058 	}
1059 
1060 	attr = syn_name2attr((char_u *)"Error");
1061 # ifdef RUBY21_OR_LATER
1062 	bt = rb_funcallv(error, rb_intern("backtrace"), 0, 0);
1063 	for (i = 0; i < RARRAY_LEN(bt); i++)
1064 	    msg_attr(RSTRING_PTR(RARRAY_AREF(bt, i)), attr);
1065 # else
1066 	bt = rb_funcall2(error, rb_intern("backtrace"), 0, 0);
1067 	for (i = 0; i < RARRAY_LEN(bt); i++)
1068 	    msg_attr(RSTRING_PTR(RARRAY_PTR(bt)[i]), attr);
1069 # endif
1070 	break;
1071     default:
1072 	vim_snprintf(buff, BUFSIZ, _("E273: unknown longjmp status %d"), state);
1073 	emsg(buff);
1074 	break;
1075     }
1076 }
1077 
1078 static VALUE vim_message(VALUE self UNUSED, VALUE str)
1079 {
1080     char *buff, *p;
1081 
1082     str = rb_obj_as_string(str);
1083     if (RSTRING_LEN(str) > 0)
1084     {
1085 	/* Only do this when the string isn't empty, alloc(0) causes trouble. */
1086 	buff = ALLOCA_N(char, RSTRING_LEN(str) + 1);
1087 	strcpy(buff, RSTRING_PTR(str));
1088 	p = strchr(buff, '\n');
1089 	if (p) *p = '\0';
1090 	msg(buff);
1091     }
1092     else
1093     {
1094 	msg("");
1095     }
1096     return Qnil;
1097 }
1098 
1099 static VALUE vim_set_option(VALUE self UNUSED, VALUE str)
1100 {
1101     do_set((char_u *)StringValuePtr(str), 0);
1102     update_screen(NOT_VALID);
1103     return Qnil;
1104 }
1105 
1106 static VALUE vim_command(VALUE self UNUSED, VALUE str)
1107 {
1108     do_cmdline_cmd((char_u *)StringValuePtr(str));
1109     return Qnil;
1110 }
1111 
1112 #ifdef FEAT_EVAL
1113 static VALUE vim_to_ruby(typval_T *tv)
1114 {
1115     VALUE result = Qnil;
1116 
1117     if (tv->v_type == VAR_STRING)
1118     {
1119 	result = rb_str_new2(tv->vval.v_string == NULL
1120 					  ? "" : (char *)(tv->vval.v_string));
1121     }
1122     else if (tv->v_type == VAR_NUMBER)
1123     {
1124 	result = INT2NUM(tv->vval.v_number);
1125     }
1126 # ifdef FEAT_FLOAT
1127     else if (tv->v_type == VAR_FLOAT)
1128     {
1129 	result = rb_float_new(tv->vval.v_float);
1130     }
1131 # endif
1132     else if (tv->v_type == VAR_LIST)
1133     {
1134 	list_T      *list = tv->vval.v_list;
1135 	listitem_T  *curr;
1136 
1137 	result = rb_ary_new();
1138 
1139 	if (list != NULL)
1140 	{
1141 	    for (curr = list->lv_first; curr != NULL; curr = curr->li_next)
1142 	    {
1143 		rb_ary_push(result, vim_to_ruby(&curr->li_tv));
1144 	    }
1145 	}
1146     }
1147     else if (tv->v_type == VAR_DICT)
1148     {
1149 	result = rb_hash_new();
1150 
1151 	if (tv->vval.v_dict != NULL)
1152 	{
1153 	    hashtab_T   *ht = &tv->vval.v_dict->dv_hashtab;
1154 	    long_u      todo = ht->ht_used;
1155 	    hashitem_T  *hi;
1156 	    dictitem_T  *di;
1157 
1158 	    for (hi = ht->ht_array; todo > 0; ++hi)
1159 	    {
1160 		if (!HASHITEM_EMPTY(hi))
1161 		{
1162 		    --todo;
1163 
1164 		    di = dict_lookup(hi);
1165 		    rb_hash_aset(result, rb_str_new2((char *)hi->hi_key),
1166 						     vim_to_ruby(&di->di_tv));
1167 		}
1168 	    }
1169 	}
1170     }
1171     else if (tv->v_type == VAR_SPECIAL)
1172     {
1173 	if (tv->vval.v_number == VVAL_TRUE)
1174 	    result = Qtrue;
1175 	else if (tv->vval.v_number == VVAL_FALSE)
1176 	    result = Qfalse;
1177     }
1178     else if (tv->v_type == VAR_BLOB)
1179     {
1180 	result = rb_str_new(tv->vval.v_blob->bv_ga.ga_data,
1181 		tv->vval.v_blob->bv_ga.ga_len);
1182     }
1183     /* else return Qnil; */
1184 
1185     return result;
1186 }
1187 #endif
1188 
1189 static VALUE vim_evaluate(VALUE self UNUSED, VALUE str)
1190 {
1191 #ifdef FEAT_EVAL
1192     typval_T    *tv;
1193     VALUE       result;
1194 
1195     tv = eval_expr((char_u *)StringValuePtr(str), NULL);
1196     if (tv == NULL)
1197     {
1198 	return Qnil;
1199     }
1200     result = vim_to_ruby(tv);
1201 
1202     free_tv(tv);
1203 
1204     return result;
1205 #else
1206     return Qnil;
1207 #endif
1208 }
1209 
1210 #ifdef USE_TYPEDDATA
1211 static size_t buffer_dsize(const void *buf);
1212 
1213 static const rb_data_type_t buffer_type = {
1214     "vim_buffer",
1215     {0, 0, buffer_dsize, {0, 0}},
1216     0, 0,
1217 # ifdef RUBY_TYPED_FREE_IMMEDIATELY
1218     0,
1219 # endif
1220 };
1221 
1222 static size_t buffer_dsize(const void *buf UNUSED)
1223 {
1224     return sizeof(buf_T);
1225 }
1226 #endif
1227 
1228 static VALUE buffer_new(buf_T *buf)
1229 {
1230     if (buf->b_ruby_ref)
1231     {
1232 	return (VALUE) buf->b_ruby_ref;
1233     }
1234     else
1235     {
1236 #ifdef USE_TYPEDDATA
1237 	VALUE obj = TypedData_Wrap_Struct(cBuffer, &buffer_type, buf);
1238 #else
1239 	VALUE obj = Data_Wrap_Struct(cBuffer, 0, 0, buf);
1240 #endif
1241 	buf->b_ruby_ref = (void *) obj;
1242 	rb_hash_aset(objtbl, rb_obj_id(obj), obj);
1243 	return obj;
1244     }
1245 }
1246 
1247 static buf_T *get_buf(VALUE obj)
1248 {
1249     buf_T *buf;
1250 
1251 #ifdef USE_TYPEDDATA
1252     TypedData_Get_Struct(obj, buf_T, &buffer_type, buf);
1253 #else
1254     Data_Get_Struct(obj, buf_T, buf);
1255 #endif
1256     if (buf == NULL)
1257 	rb_raise(eDeletedBufferError, "attempt to refer to deleted buffer");
1258     return buf;
1259 }
1260 
1261 static VALUE vim_blob(VALUE self UNUSED, VALUE str)
1262 {
1263     VALUE result = rb_str_new("0z", 2);
1264     char    buf[4];
1265     int	i;
1266     for (i = 0; i < RSTRING_LEN(str); i++)
1267     {
1268 	sprintf(buf, "%02X", RSTRING_PTR(str)[i]);
1269 	rb_str_concat(result, rb_str_new2(buf));
1270     }
1271     return result;
1272 }
1273 
1274 static VALUE buffer_s_current(void)
1275 {
1276     return buffer_new(curbuf);
1277 }
1278 
1279 static VALUE buffer_s_count(void)
1280 {
1281     buf_T *b;
1282     int n = 0;
1283 
1284     FOR_ALL_BUFFERS(b)
1285     {
1286 	/*  Deleted buffers should not be counted
1287 	 *    SegPhault - 01/07/05 */
1288 	if (b->b_p_bl)
1289 	    n++;
1290     }
1291 
1292     return INT2NUM(n);
1293 }
1294 
1295 static VALUE buffer_s_aref(VALUE self UNUSED, VALUE num)
1296 {
1297     buf_T *b;
1298     int n = NUM2INT(num);
1299 
1300     FOR_ALL_BUFFERS(b)
1301     {
1302 	/*  Deleted buffers should not be counted
1303 	 *    SegPhault - 01/07/05 */
1304 	if (!b->b_p_bl)
1305 	    continue;
1306 
1307 	if (n == 0)
1308 	    return buffer_new(b);
1309 
1310 	n--;
1311     }
1312     return Qnil;
1313 }
1314 
1315 static VALUE buffer_name(VALUE self)
1316 {
1317     buf_T *buf = get_buf(self);
1318 
1319     return buf->b_ffname ? rb_str_new2((char *)buf->b_ffname) : Qnil;
1320 }
1321 
1322 static VALUE buffer_number(VALUE self)
1323 {
1324     buf_T *buf = get_buf(self);
1325 
1326     return INT2NUM(buf->b_fnum);
1327 }
1328 
1329 static VALUE buffer_count(VALUE self)
1330 {
1331     buf_T *buf = get_buf(self);
1332 
1333     return INT2NUM(buf->b_ml.ml_line_count);
1334 }
1335 
1336 static VALUE get_buffer_line(buf_T *buf, linenr_T n)
1337 {
1338     if (n <= 0 || n > buf->b_ml.ml_line_count)
1339 	rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
1340     return vim_str2rb_enc_str((char *)ml_get_buf(buf, n, FALSE));
1341 }
1342 
1343 static VALUE buffer_aref(VALUE self, VALUE num)
1344 {
1345     buf_T *buf = get_buf(self);
1346 
1347     if (buf != NULL)
1348 	return get_buffer_line(buf, (linenr_T)NUM2LONG(num));
1349     return Qnil; /* For stop warning */
1350 }
1351 
1352 static VALUE set_buffer_line(buf_T *buf, linenr_T n, VALUE str)
1353 {
1354     char	*line = StringValuePtr(str);
1355     aco_save_T	aco;
1356 
1357     if (n > 0 && n <= buf->b_ml.ml_line_count && line != NULL)
1358     {
1359 	/* set curwin/curbuf for "buf" and save some things */
1360 	aucmd_prepbuf(&aco, buf);
1361 
1362 	if (u_savesub(n) == OK)
1363 	{
1364 	    ml_replace(n, (char_u *)line, TRUE);
1365 	    changed();
1366 #ifdef SYNTAX_HL
1367 	    syn_changed(n); /* recompute syntax hl. for this line */
1368 #endif
1369 	}
1370 
1371 	/* restore curwin/curbuf and a few other things */
1372 	aucmd_restbuf(&aco);
1373 	/* Careful: autocommands may have made "buf" invalid! */
1374 
1375 	update_curbuf(NOT_VALID);
1376     }
1377     else
1378     {
1379 	rb_raise(rb_eIndexError, "line number %ld out of range", (long)n);
1380     }
1381     return str;
1382 }
1383 
1384 static VALUE buffer_aset(VALUE self, VALUE num, VALUE str)
1385 {
1386     buf_T *buf = get_buf(self);
1387 
1388     if (buf != NULL)
1389 	return set_buffer_line(buf, (linenr_T)NUM2LONG(num), str);
1390     return str;
1391 }
1392 
1393 static VALUE buffer_delete(VALUE self, VALUE num)
1394 {
1395     buf_T	*buf = get_buf(self);
1396     long	n = NUM2LONG(num);
1397     aco_save_T	aco;
1398 
1399     if (n > 0 && n <= buf->b_ml.ml_line_count)
1400     {
1401 	/* set curwin/curbuf for "buf" and save some things */
1402 	aucmd_prepbuf(&aco, buf);
1403 
1404 	if (u_savedel(n, 1) == OK)
1405 	{
1406 	    ml_delete(n, 0);
1407 
1408 	    /* Changes to non-active buffers should properly refresh
1409 	     *   SegPhault - 01/09/05 */
1410 	    deleted_lines_mark(n, 1L);
1411 
1412 	    changed();
1413 	}
1414 
1415 	/* restore curwin/curbuf and a few other things */
1416 	aucmd_restbuf(&aco);
1417 	/* Careful: autocommands may have made "buf" invalid! */
1418 
1419 	update_curbuf(NOT_VALID);
1420     }
1421     else
1422     {
1423 	rb_raise(rb_eIndexError, "line number %ld out of range", n);
1424     }
1425     return Qnil;
1426 }
1427 
1428 static VALUE buffer_append(VALUE self, VALUE num, VALUE str)
1429 {
1430     buf_T	*buf = get_buf(self);
1431     char	*line = StringValuePtr(str);
1432     long	n = NUM2LONG(num);
1433     aco_save_T	aco;
1434 
1435     if (line == NULL)
1436     {
1437 	rb_raise(rb_eIndexError, "NULL line");
1438     }
1439     else if (n >= 0 && n <= buf->b_ml.ml_line_count)
1440     {
1441 	/* set curwin/curbuf for "buf" and save some things */
1442 	aucmd_prepbuf(&aco, buf);
1443 
1444 	if (u_inssub(n + 1) == OK)
1445 	{
1446 	    ml_append(n, (char_u *) line, (colnr_T) 0, FALSE);
1447 
1448 	    /*  Changes to non-active buffers should properly refresh screen
1449 	     *    SegPhault - 12/20/04 */
1450 	    appended_lines_mark(n, 1L);
1451 
1452 	    changed();
1453 	}
1454 
1455 	/* restore curwin/curbuf and a few other things */
1456 	aucmd_restbuf(&aco);
1457 	/* Careful: autocommands may have made "buf" invalid! */
1458 
1459 	update_curbuf(NOT_VALID);
1460     }
1461     else
1462     {
1463 	rb_raise(rb_eIndexError, "line number %ld out of range", n);
1464     }
1465     return str;
1466 }
1467 
1468 #ifdef USE_TYPEDDATA
1469 static size_t window_dsize(const void *buf);
1470 
1471 static const rb_data_type_t window_type = {
1472     "vim_window",
1473     {0, 0, window_dsize, {0, 0}},
1474     0, 0,
1475 # ifdef RUBY_TYPED_FREE_IMMEDIATELY
1476     0,
1477 # endif
1478 };
1479 
1480 static size_t window_dsize(const void *win UNUSED)
1481 {
1482     return sizeof(win_T);
1483 }
1484 #endif
1485 
1486 static VALUE window_new(win_T *win)
1487 {
1488     if (win->w_ruby_ref)
1489     {
1490 	return (VALUE) win->w_ruby_ref;
1491     }
1492     else
1493     {
1494 #ifdef USE_TYPEDDATA
1495 	VALUE obj = TypedData_Wrap_Struct(cVimWindow, &window_type, win);
1496 #else
1497 	VALUE obj = Data_Wrap_Struct(cVimWindow, 0, 0, win);
1498 #endif
1499 	win->w_ruby_ref = (void *) obj;
1500 	rb_hash_aset(objtbl, rb_obj_id(obj), obj);
1501 	return obj;
1502     }
1503 }
1504 
1505 static win_T *get_win(VALUE obj)
1506 {
1507     win_T *win;
1508 
1509 #ifdef USE_TYPEDDATA
1510     TypedData_Get_Struct(obj, win_T, &window_type, win);
1511 #else
1512     Data_Get_Struct(obj, win_T, win);
1513 #endif
1514     if (win == NULL)
1515 	rb_raise(eDeletedWindowError, "attempt to refer to deleted window");
1516     return win;
1517 }
1518 
1519 static VALUE window_s_current(void)
1520 {
1521     return window_new(curwin);
1522 }
1523 
1524 /*
1525  * Added line manipulation functions
1526  *    SegPhault - 03/07/05
1527  */
1528 static VALUE line_s_current(void)
1529 {
1530     return get_buffer_line(curbuf, curwin->w_cursor.lnum);
1531 }
1532 
1533 static VALUE set_current_line(VALUE self UNUSED, VALUE str)
1534 {
1535     return set_buffer_line(curbuf, curwin->w_cursor.lnum, str);
1536 }
1537 
1538 static VALUE current_line_number(void)
1539 {
1540     return INT2FIX((int)curwin->w_cursor.lnum);
1541 }
1542 
1543 
1544 
1545 static VALUE window_s_count(void)
1546 {
1547     win_T	*w;
1548     int n = 0;
1549 
1550     FOR_ALL_WINDOWS(w)
1551 	n++;
1552     return INT2NUM(n);
1553 }
1554 
1555 static VALUE window_s_aref(VALUE self UNUSED, VALUE num)
1556 {
1557     win_T *w;
1558     int n = NUM2INT(num);
1559 
1560     for (w = firstwin; w != NULL; w = w->w_next, --n)
1561 	if (n == 0)
1562 	    return window_new(w);
1563     return Qnil;
1564 }
1565 
1566 static VALUE window_buffer(VALUE self)
1567 {
1568     win_T *win = get_win(self);
1569 
1570     return buffer_new(win->w_buffer);
1571 }
1572 
1573 static VALUE window_height(VALUE self)
1574 {
1575     win_T *win = get_win(self);
1576 
1577     return INT2NUM(win->w_height);
1578 }
1579 
1580 static VALUE window_set_height(VALUE self, VALUE height)
1581 {
1582     win_T *win = get_win(self);
1583     win_T *savewin = curwin;
1584 
1585     curwin = win;
1586     win_setheight(NUM2INT(height));
1587     curwin = savewin;
1588     return height;
1589 }
1590 
1591 static VALUE window_width(VALUE self UNUSED)
1592 {
1593     return INT2NUM(get_win(self)->w_width);
1594 }
1595 
1596 static VALUE window_set_width(VALUE self UNUSED, VALUE width)
1597 {
1598     win_T *win = get_win(self);
1599     win_T *savewin = curwin;
1600 
1601     curwin = win;
1602     win_setwidth(NUM2INT(width));
1603     curwin = savewin;
1604     return width;
1605 }
1606 
1607 static VALUE window_cursor(VALUE self)
1608 {
1609     win_T *win = get_win(self);
1610 
1611     return rb_assoc_new(INT2NUM(win->w_cursor.lnum), INT2NUM(win->w_cursor.col));
1612 }
1613 
1614 static VALUE window_set_cursor(VALUE self, VALUE pos)
1615 {
1616     VALUE lnum, col;
1617     win_T *win = get_win(self);
1618 
1619     Check_Type(pos, T_ARRAY);
1620     if (RARRAY_LEN(pos) != 2)
1621 	rb_raise(rb_eArgError, "array length must be 2");
1622     lnum = RARRAY_PTR(pos)[0];
1623     col = RARRAY_PTR(pos)[1];
1624     win->w_cursor.lnum = NUM2LONG(lnum);
1625     win->w_cursor.col = NUM2UINT(col);
1626     win->w_set_curswant = TRUE;
1627     check_cursor();		    /* put cursor on an existing line */
1628     update_screen(NOT_VALID);
1629     return Qnil;
1630 }
1631 
1632 static VALUE f_nop(VALUE self UNUSED)
1633 {
1634     return Qnil;
1635 }
1636 
1637 static VALUE f_p(int argc, VALUE *argv, VALUE self UNUSED)
1638 {
1639     int i;
1640     VALUE str = rb_str_new("", 0);
1641     VALUE ret = Qnil;
1642 
1643     for (i = 0; i < argc; i++)
1644     {
1645 	if (i > 0) rb_str_cat(str, ", ", 2);
1646 	rb_str_concat(str, rb_inspect(argv[i]));
1647     }
1648     msg(RSTRING_PTR(str));
1649 
1650     if (argc == 1)
1651 	ret = argv[0];
1652     else if (argc > 1)
1653 	ret = rb_ary_new4(argc, argv);
1654     return ret;
1655 }
1656 
1657 static void ruby_io_init(void)
1658 {
1659 #ifndef DYNAMIC_RUBY
1660     RUBYEXTERN VALUE rb_stdout;
1661     RUBYEXTERN VALUE rb_stderr;
1662 #endif
1663 
1664     rb_stdout = rb_obj_alloc(rb_cObject);
1665     rb_stderr = rb_obj_alloc(rb_cObject);
1666     rb_define_singleton_method(rb_stdout, "write", vim_message, 1);
1667     rb_define_singleton_method(rb_stdout, "flush", f_nop, 0);
1668     rb_define_singleton_method(rb_stderr, "write", vim_message, 1);
1669     rb_define_singleton_method(rb_stderr, "flush", f_nop, 0);
1670     rb_define_global_function("p", f_p, -1);
1671 }
1672 
1673 static void ruby_vim_init(void)
1674 {
1675     objtbl = rb_hash_new();
1676     rb_global_variable(&objtbl);
1677 
1678     /* The Vim module used to be called "VIM", but "Vim" is better.  Make an
1679      * alias "VIM" for backwards compatibility. */
1680     mVIM = rb_define_module("Vim");
1681     rb_define_const(rb_cObject, "VIM", mVIM);
1682     rb_define_const(mVIM, "VERSION_MAJOR", INT2NUM(VIM_VERSION_MAJOR));
1683     rb_define_const(mVIM, "VERSION_MINOR", INT2NUM(VIM_VERSION_MINOR));
1684     rb_define_const(mVIM, "VERSION_BUILD", INT2NUM(VIM_VERSION_BUILD));
1685     rb_define_const(mVIM, "VERSION_PATCHLEVEL", INT2NUM(VIM_VERSION_PATCHLEVEL));
1686     rb_define_const(mVIM, "VERSION_SHORT", rb_str_new2(VIM_VERSION_SHORT));
1687     rb_define_const(mVIM, "VERSION_MEDIUM", rb_str_new2(VIM_VERSION_MEDIUM));
1688     rb_define_const(mVIM, "VERSION_LONG", rb_str_new2(VIM_VERSION_LONG));
1689     rb_define_const(mVIM, "VERSION_LONG_DATE", rb_str_new2(VIM_VERSION_LONG_DATE));
1690     rb_define_module_function(mVIM, "message", vim_message, 1);
1691     rb_define_module_function(mVIM, "set_option", vim_set_option, 1);
1692     rb_define_module_function(mVIM, "command", vim_command, 1);
1693     rb_define_module_function(mVIM, "evaluate", vim_evaluate, 1);
1694     rb_define_module_function(mVIM, "blob", vim_blob, 1);
1695 
1696     eDeletedBufferError = rb_define_class_under(mVIM, "DeletedBufferError",
1697 						rb_eStandardError);
1698     eDeletedWindowError = rb_define_class_under(mVIM, "DeletedWindowError",
1699 						rb_eStandardError);
1700 
1701     cBuffer = rb_define_class_under(mVIM, "Buffer", rb_cObject);
1702     rb_define_singleton_method(cBuffer, "current", buffer_s_current, 0);
1703     rb_define_singleton_method(cBuffer, "count", buffer_s_count, 0);
1704     rb_define_singleton_method(cBuffer, "[]", buffer_s_aref, 1);
1705     rb_define_method(cBuffer, "name", buffer_name, 0);
1706     rb_define_method(cBuffer, "number", buffer_number, 0);
1707     rb_define_method(cBuffer, "count", buffer_count, 0);
1708     rb_define_method(cBuffer, "length", buffer_count, 0);
1709     rb_define_method(cBuffer, "[]", buffer_aref, 1);
1710     rb_define_method(cBuffer, "[]=", buffer_aset, 2);
1711     rb_define_method(cBuffer, "delete", buffer_delete, 1);
1712     rb_define_method(cBuffer, "append", buffer_append, 2);
1713 
1714     /* Added line manipulation functions
1715      *   SegPhault - 03/07/05 */
1716     rb_define_method(cBuffer, "line_number", current_line_number, 0);
1717     rb_define_method(cBuffer, "line", line_s_current, 0);
1718     rb_define_method(cBuffer, "line=", set_current_line, 1);
1719 
1720 
1721     cVimWindow = rb_define_class_under(mVIM, "Window", rb_cObject);
1722     rb_define_singleton_method(cVimWindow, "current", window_s_current, 0);
1723     rb_define_singleton_method(cVimWindow, "count", window_s_count, 0);
1724     rb_define_singleton_method(cVimWindow, "[]", window_s_aref, 1);
1725     rb_define_method(cVimWindow, "buffer", window_buffer, 0);
1726     rb_define_method(cVimWindow, "height", window_height, 0);
1727     rb_define_method(cVimWindow, "height=", window_set_height, 1);
1728     rb_define_method(cVimWindow, "width", window_width, 0);
1729     rb_define_method(cVimWindow, "width=", window_set_width, 1);
1730     rb_define_method(cVimWindow, "cursor", window_cursor, 0);
1731     rb_define_method(cVimWindow, "cursor=", window_set_cursor, 1);
1732 
1733     rb_define_virtual_variable("$curbuf", buffer_s_current, 0);
1734     rb_define_virtual_variable("$curwin", window_s_current, 0);
1735 }
1736 
1737 void vim_ruby_init(void *stack_start)
1738 {
1739     /* should get machine stack start address early in main function */
1740     ruby_stack_start = stack_start;
1741 }
1742