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