Update runtime files
[MacVim.git] / src / if_mzsch.c
blob28bf53def880f7603e94658c1f3fba554cdbecf1
1 /* vi:set ts=8 sts=4 sw=4:
3 * MzScheme interface by Sergey Khorev <sergey.khorev@gmail.com>
4 * Original work by Brent Fulgham <bfulgham@debian.org>
5 * (Based on lots of help from Matthew Flatt)
7 * This consists of six parts:
8 * 1. MzScheme interpreter main program
9 * 2. Routines that handle the external interface between MzScheme and
10 * Vim.
11 * 3. MzScheme input/output handlers: writes output via [e]msg().
12 * 4. Implementation of the Vim Features for MzScheme
13 * 5. Vim Window-related Manipulation Functions.
14 * 6. Vim Buffer-related Manipulation Functions
16 * NOTES
17 * 1. Memory, allocated with scheme_malloc*, need not to be freed explicitly,
18 * garbage collector will do it self
19 * 2. Requires at least NORMAL features. I can't imagine why one may want
20 * to build with SMALL or TINY features but with MzScheme interface.
21 * 3. I don't use K&R-style functions. Anyway, MzScheme headers are ANSI.
24 #include "vim.h"
26 #include "if_mzsch.h"
28 /* Only do the following when the feature is enabled. Needed for "make
29 * depend". */
30 #if defined(FEAT_MZSCHEME) || defined(PROTO)
32 /* Base data structures */
33 #define SCHEME_VIMBUFFERP(obj) SAME_TYPE(SCHEME_TYPE(obj), mz_buffer_type)
34 #define SCHEME_VIMWINDOWP(obj) SAME_TYPE(SCHEME_TYPE(obj), mz_window_type)
36 typedef struct
38 Scheme_Type tag;
39 Scheme_Env *env;
40 buf_T *buf;
41 } vim_mz_buffer;
43 #define INVALID_BUFFER_VALUE ((buf_T *)(-1))
45 typedef struct
47 Scheme_Type tag;
48 win_T *win;
49 } vim_mz_window;
51 #define INVALID_WINDOW_VALUE ((win_T *)(-1))
54 * Prims that form MzScheme Vim interface
56 typedef struct
58 Scheme_Closed_Prim *prim;
59 char *name;
60 int mina; /* arity information */
61 int maxa;
62 } Vim_Prim;
64 typedef struct
66 char *name;
67 Scheme_Object *port;
68 } Port_Info;
70 /* info for closed prim */
72 * data have different means:
73 * for do_eval it is char*
74 * for do_apply is Apply_Onfo*
75 * for do_load is Port_Info*
77 typedef struct
79 void *data;
80 Scheme_Env *env;
81 } Cmd_Info;
83 /* info for do_apply */
84 typedef struct
86 Scheme_Object *proc;
87 int argc;
88 Scheme_Object **argv;
89 } Apply_Info;
92 *========================================================================
93 * Vim-Control Commands
94 *========================================================================
97 *========================================================================
98 * Utility functions for the vim/mzscheme interface
99 *========================================================================
101 #ifdef HAVE_SANDBOX
102 static Scheme_Object *sandbox_file_guard(int, Scheme_Object **);
103 static Scheme_Object *sandbox_network_guard(int, Scheme_Object **);
104 static void sandbox_check(void);
105 #endif
106 /* Buffer-related commands */
107 static Scheme_Object *buffer_new(buf_T *buf);
108 static Scheme_Object *get_buffer_by_name(void *, int, Scheme_Object **);
109 static Scheme_Object *get_buffer_by_num(void *, int, Scheme_Object **);
110 static Scheme_Object *get_buffer_count(void *, int, Scheme_Object **);
111 static Scheme_Object *get_buffer_line(void *, int, Scheme_Object **);
112 static Scheme_Object *get_buffer_line_list(void *, int, Scheme_Object **);
113 static Scheme_Object *get_buffer_name(void *, int, Scheme_Object **);
114 static Scheme_Object *get_buffer_num(void *, int, Scheme_Object **);
115 static Scheme_Object *get_buffer_size(void *, int, Scheme_Object **);
116 static Scheme_Object *get_curr_buffer(void *, int, Scheme_Object **);
117 static Scheme_Object *get_next_buffer(void *, int, Scheme_Object **);
118 static Scheme_Object *get_prev_buffer(void *, int, Scheme_Object **);
119 static Scheme_Object *mzscheme_open_buffer(void *, int, Scheme_Object **);
120 static Scheme_Object *set_buffer_line(void *, int, Scheme_Object **);
121 static Scheme_Object *set_buffer_line_list(void *, int, Scheme_Object **);
122 static Scheme_Object *insert_buffer_line_list(void *, int, Scheme_Object **);
123 static Scheme_Object *get_range_start(void *, int, Scheme_Object **);
124 static Scheme_Object *get_range_end(void *, int, Scheme_Object **);
125 static Scheme_Object *get_buffer_namespace(void *, int, Scheme_Object **);
126 static vim_mz_buffer *get_vim_curr_buffer(void);
128 /* Window-related commands */
129 static Scheme_Object *window_new(win_T *win);
130 static Scheme_Object *get_curr_win(void *, int, Scheme_Object **);
131 static Scheme_Object *get_window_count(void *, int, Scheme_Object **);
132 static Scheme_Object *get_window_by_num(void *, int, Scheme_Object **);
133 static Scheme_Object *get_window_num(void *, int, Scheme_Object **);
134 static Scheme_Object *get_window_buffer(void *, int, Scheme_Object **);
135 static Scheme_Object *get_window_height(void *, int, Scheme_Object **);
136 static Scheme_Object *set_window_height(void *, int, Scheme_Object **);
137 #ifdef FEAT_VERTSPLIT
138 static Scheme_Object *get_window_width(void *, int, Scheme_Object **);
139 static Scheme_Object *set_window_width(void *, int, Scheme_Object **);
140 #endif
141 static Scheme_Object *get_cursor(void *, int, Scheme_Object **);
142 static Scheme_Object *set_cursor(void *, int, Scheme_Object **);
143 static Scheme_Object *get_window_list(void *, int, Scheme_Object **);
144 static vim_mz_window *get_vim_curr_window(void);
146 /* Vim-related commands */
147 static Scheme_Object *mzscheme_beep(void *, int, Scheme_Object **);
148 static Scheme_Object *get_option(void *, int, Scheme_Object **);
149 static Scheme_Object *set_option(void *, int, Scheme_Object **);
150 static Scheme_Object *vim_command(void *, int, Scheme_Object **);
151 static Scheme_Object *vim_eval(void *, int, Scheme_Object **);
152 static Scheme_Object *vim_bufferp(void *data, int, Scheme_Object **);
153 static Scheme_Object *vim_windowp(void *data, int, Scheme_Object **);
154 static Scheme_Object *vim_buffer_validp(void *data, int, Scheme_Object **);
155 static Scheme_Object *vim_window_validp(void *data, int, Scheme_Object **);
158 *========================================================================
159 * Internal Function Prototypes
160 *========================================================================
162 static int vim_error_check(void);
163 static int do_mzscheme_command(exarg_T *, void *, Scheme_Closed_Prim *what);
164 static void startup_mzscheme(void);
165 static char *string_to_line(Scheme_Object *obj);
166 static int mzscheme_io_init(void);
167 static void mzscheme_interface_init(vim_mz_buffer *self);
168 static void do_output(char *mesg, long len);
169 static void do_printf(char *format, ...);
170 static void do_flush(void);
171 static Scheme_Object *_apply_thunk_catch_exceptions(
172 Scheme_Object *, Scheme_Object **);
173 static Scheme_Object *extract_exn_message(Scheme_Object *v);
174 static Scheme_Object *do_eval(void *, int noargc, Scheme_Object **noargv);
175 static Scheme_Object *do_load(void *, int noargc, Scheme_Object **noargv);
176 static Scheme_Object *do_apply(void *, int noargc, Scheme_Object **noargv);
177 static void register_vim_exn(Scheme_Env *env);
178 static vim_mz_buffer *get_buffer_arg(const char *fname, int argnum,
179 int argc, Scheme_Object **argv);
180 static vim_mz_window *get_window_arg(const char *fname, int argnum,
181 int argc, Scheme_Object **argv);
182 static void add_vim_exn(Scheme_Env *env);
183 static int line_in_range(linenr_T, buf_T *);
184 static void check_line_range(linenr_T, buf_T *);
185 static void mz_fix_cursor(int lo, int hi, int extra);
187 static int eval_in_namespace(void *, Scheme_Closed_Prim *, Scheme_Env *,
188 Scheme_Object **ret);
189 static void make_modules(Scheme_Env *);
191 #ifdef DYNAMIC_MZSCHEME
193 static Scheme_Object *dll_scheme_eof;
194 static Scheme_Object *dll_scheme_false;
195 static Scheme_Object *dll_scheme_void;
196 static Scheme_Object *dll_scheme_null;
197 static Scheme_Object *dll_scheme_true;
199 static Scheme_Thread **dll_scheme_current_thread_ptr;
201 static void (**dll_scheme_console_printf_ptr)(char *str, ...);
202 static void (**dll_scheme_console_output_ptr)(char *str, long len);
203 static void (**dll_scheme_notify_multithread_ptr)(int on);
205 static void *(*dll_GC_malloc)(size_t size_in_bytes);
206 static void *(*dll_GC_malloc_atomic)(size_t size_in_bytes);
207 static Scheme_Env *(*dll_scheme_basic_env)(void);
208 static void (*dll_scheme_check_threads)(void);
209 static void (*dll_scheme_register_static)(void *ptr, long size);
210 static void (*dll_scheme_set_stack_base)(void *base, int no_auto_statics);
211 static void (*dll_scheme_add_global)(const char *name, Scheme_Object *val,
212 Scheme_Env *env);
213 static void (*dll_scheme_add_global_symbol)(Scheme_Object *name,
214 Scheme_Object *val, Scheme_Env *env);
215 static Scheme_Object *(*dll_scheme_apply)(Scheme_Object *rator, int num_rands,
216 Scheme_Object **rands);
217 static Scheme_Object *(*dll_scheme_builtin_value)(const char *name);
218 # if MZSCHEME_VERSION_MAJOR >= 299
219 static Scheme_Object *(*dll_scheme_byte_string_to_char_string)(Scheme_Object *s);
220 # endif
221 static void (*dll_scheme_close_input_port)(Scheme_Object *port);
222 static void (*dll_scheme_count_lines)(Scheme_Object *port);
223 #if MZSCHEME_VERSION_MAJOR < 360
224 static Scheme_Object *(*dll_scheme_current_continuation_marks)(void);
225 #else
226 static Scheme_Object *(*dll_scheme_current_continuation_marks)(Scheme_Object *prompt_tag);
227 #endif
228 static void (*dll_scheme_display)(Scheme_Object *obj, Scheme_Object *port);
229 static char *(*dll_scheme_display_to_string)(Scheme_Object *obj, long *len);
230 static int (*dll_scheme_eq)(Scheme_Object *obj1, Scheme_Object *obj2);
231 static Scheme_Object *(*dll_scheme_do_eval)(Scheme_Object *obj,
232 int _num_rands, Scheme_Object **rands, int val);
233 static void (*dll_scheme_dont_gc_ptr)(void *p);
234 static Scheme_Object *(*dll_scheme_eval)(Scheme_Object *obj, Scheme_Env *env);
235 static Scheme_Object *(*dll_scheme_eval_string)(const char *str,
236 Scheme_Env *env);
237 static Scheme_Object *(*dll_scheme_eval_string_all)(const char *str,
238 Scheme_Env *env, int all);
239 static void (*dll_scheme_finish_primitive_module)(Scheme_Env *env);
240 # if MZSCHEME_VERSION_MAJOR < 299
241 static char *(*dll_scheme_format)(char *format, int flen, int argc,
242 Scheme_Object **argv, long *rlen);
243 # else
244 static char *(*dll_scheme_format_utf8)(char *format, int flen, int argc,
245 Scheme_Object **argv, long *rlen);
246 static Scheme_Object *(*dll_scheme_get_param)(Scheme_Config *c, int pos);
247 # endif
248 static void (*dll_scheme_gc_ptr_ok)(void *p);
249 # if MZSCHEME_VERSION_MAJOR < 299
250 static char *(*dll_scheme_get_sized_string_output)(Scheme_Object *,
251 long *len);
252 # else
253 static char *(*dll_scheme_get_sized_byte_string_output)(Scheme_Object *,
254 long *len);
255 # endif
256 static Scheme_Object *(*dll_scheme_intern_symbol)(const char *name);
257 static Scheme_Object *(*dll_scheme_lookup_global)(Scheme_Object *symbol,
258 Scheme_Env *env);
259 static Scheme_Object *(*dll_scheme_make_closed_prim_w_arity)
260 (Scheme_Closed_Prim *prim, void *data, const char *name, mzshort mina,
261 mzshort maxa);
262 static Scheme_Object *(*dll_scheme_make_integer_value)(long i);
263 static Scheme_Object *(*dll_scheme_make_namespace)(int argc,
264 Scheme_Object *argv[]);
265 static Scheme_Object *(*dll_scheme_make_pair)(Scheme_Object *car,
266 Scheme_Object *cdr);
267 static Scheme_Object *(*dll_scheme_make_prim_w_arity)(Scheme_Prim *prim,
268 const char *name, mzshort mina, mzshort maxa);
269 # if MZSCHEME_VERSION_MAJOR < 299
270 static Scheme_Object *(*dll_scheme_make_string)(const char *chars);
271 static Scheme_Object *(*dll_scheme_make_string_output_port)();
272 # else
273 static Scheme_Object *(*dll_scheme_make_byte_string)(const char *chars);
274 static Scheme_Object *(*dll_scheme_make_byte_string_output_port)();
275 # endif
276 static Scheme_Object *(*dll_scheme_make_struct_instance)(Scheme_Object *stype,
277 int argc, Scheme_Object **argv);
278 static Scheme_Object **(*dll_scheme_make_struct_names)(Scheme_Object *base,
279 Scheme_Object *field_names, int flags, int *count_out);
280 static Scheme_Object *(*dll_scheme_make_struct_type)(Scheme_Object *base,
281 Scheme_Object *parent, Scheme_Object *inspector, int num_fields,
282 int num_uninit_fields, Scheme_Object *uninit_val,
283 Scheme_Object *properties
284 # if MZSCHEME_VERSION_MAJOR >= 299
285 , Scheme_Object *guard
286 # endif
288 static Scheme_Object **(*dll_scheme_make_struct_values)(
289 Scheme_Object *struct_type, Scheme_Object **names, int count,
290 int flags);
291 static Scheme_Type (*dll_scheme_make_type)(const char *name);
292 static Scheme_Object *(*dll_scheme_make_vector)(int size,
293 Scheme_Object *fill);
294 static void *(*dll_scheme_malloc_fail_ok)(void *(*f)(size_t), size_t);
295 static Scheme_Object *(*dll_scheme_open_input_file)(const char *name,
296 const char *who);
297 static Scheme_Env *(*dll_scheme_primitive_module)(Scheme_Object *name,
298 Scheme_Env *for_env);
299 static int (*dll_scheme_proper_list_length)(Scheme_Object *list);
300 static void (*dll_scheme_raise)(Scheme_Object *exn);
301 static Scheme_Object *(*dll_scheme_read)(Scheme_Object *port);
302 static void (*dll_scheme_signal_error)(const char *msg, ...);
303 static void (*dll_scheme_wrong_type)(const char *name, const char *expected,
304 int which, int argc, Scheme_Object **argv);
305 # if MZSCHEME_VERSION_MAJOR >= 299
306 static void (*dll_scheme_set_param)(Scheme_Config *c, int pos,
307 Scheme_Object *o);
308 static Scheme_Config *(*dll_scheme_current_config)(void);
309 static Scheme_Object *(*dll_scheme_char_string_to_byte_string)
310 (Scheme_Object *s);
311 static Scheme_Object *(*dll_scheme_char_string_to_path)
312 (Scheme_Object *s);
313 # endif
315 /* arrays are imported directly */
316 # define scheme_eof dll_scheme_eof
317 # define scheme_false dll_scheme_false
318 # define scheme_void dll_scheme_void
319 # define scheme_null dll_scheme_null
320 # define scheme_true dll_scheme_true
322 /* pointers are GetProceAddress'ed as pointers to pointer */
323 # define scheme_current_thread (*dll_scheme_current_thread_ptr)
324 # define scheme_console_printf (*dll_scheme_console_printf_ptr)
325 # define scheme_console_output (*dll_scheme_console_output_ptr)
326 # define scheme_notify_multithread (*dll_scheme_notify_multithread_ptr)
328 /* and functions in a usual way */
329 # define GC_malloc dll_GC_malloc
330 # define GC_malloc_atomic dll_GC_malloc_atomic
332 # define scheme_add_global dll_scheme_add_global
333 # define scheme_add_global_symbol dll_scheme_add_global_symbol
334 # define scheme_apply dll_scheme_apply
335 # define scheme_basic_env dll_scheme_basic_env
336 # define scheme_builtin_value dll_scheme_builtin_value
337 # if MZSCHEME_VERSION_MAJOR >= 299
338 # define scheme_byte_string_to_char_string dll_scheme_byte_string_to_char_string
339 # endif
340 # define scheme_check_threads dll_scheme_check_threads
341 # define scheme_close_input_port dll_scheme_close_input_port
342 # define scheme_count_lines dll_scheme_count_lines
343 # define scheme_current_continuation_marks \
344 dll_scheme_current_continuation_marks
345 # define scheme_display dll_scheme_display
346 # define scheme_display_to_string dll_scheme_display_to_string
347 # define scheme_do_eval dll_scheme_do_eval
348 # define scheme_dont_gc_ptr dll_scheme_dont_gc_ptr
349 # define scheme_eq dll_scheme_eq
350 # define scheme_eval dll_scheme_eval
351 # define scheme_eval_string dll_scheme_eval_string
352 # define scheme_eval_string_all dll_scheme_eval_string_all
353 # define scheme_finish_primitive_module dll_scheme_finish_primitive_module
354 # if MZSCHEME_VERSION_MAJOR < 299
355 # define scheme_format dll_scheme_format
356 # else
357 # define scheme_format_utf8 dll_scheme_format_utf8
358 # endif
359 # define scheme_gc_ptr_ok dll_scheme_gc_ptr_ok
360 # if MZSCHEME_VERSION_MAJOR < 299
361 # define scheme_get_sized_string_output dll_scheme_get_sized_string_output
362 # else
363 # define scheme_get_sized_byte_string_output \
364 dll_scheme_get_sized_byte_string_output
365 # define scheme_get_param dll_scheme_get_param
366 # endif
367 # define scheme_intern_symbol dll_scheme_intern_symbol
368 # define scheme_lookup_global dll_scheme_lookup_global
369 # define scheme_make_closed_prim_w_arity dll_scheme_make_closed_prim_w_arity
370 # define scheme_make_integer_value dll_scheme_make_integer_value
371 # define scheme_make_namespace dll_scheme_make_namespace
372 # define scheme_make_pair dll_scheme_make_pair
373 # define scheme_make_prim_w_arity dll_scheme_make_prim_w_arity
374 # if MZSCHEME_VERSION_MAJOR < 299
375 # define scheme_make_string dll_scheme_make_string
376 # define scheme_make_string_output_port dll_scheme_make_string_output_port
377 # else
378 # define scheme_make_byte_string dll_scheme_make_byte_string
379 # define scheme_make_byte_string_output_port \
380 dll_scheme_make_byte_string_output_port
381 # endif
382 # define scheme_make_struct_instance dll_scheme_make_struct_instance
383 # define scheme_make_struct_names dll_scheme_make_struct_names
384 # define scheme_make_struct_type dll_scheme_make_struct_type
385 # define scheme_make_struct_values dll_scheme_make_struct_values
386 # define scheme_make_type dll_scheme_make_type
387 # define scheme_make_vector dll_scheme_make_vector
388 # define scheme_malloc_fail_ok dll_scheme_malloc_fail_ok
389 # define scheme_open_input_file dll_scheme_open_input_file
390 # define scheme_primitive_module dll_scheme_primitive_module
391 # define scheme_proper_list_length dll_scheme_proper_list_length
392 # define scheme_raise dll_scheme_raise
393 # define scheme_read dll_scheme_read
394 # define scheme_register_static dll_scheme_register_static
395 # define scheme_set_stack_base dll_scheme_set_stack_base
396 # define scheme_signal_error dll_scheme_signal_error
397 # define scheme_wrong_type dll_scheme_wrong_type
398 # if MZSCHEME_VERSION_MAJOR >= 299
399 # define scheme_set_param dll_scheme_set_param
400 # define scheme_current_config dll_scheme_current_config
401 # define scheme_char_string_to_byte_string \
402 dll_scheme_char_string_to_byte_string
403 # define scheme_char_string_to_path \
404 dll_scheme_char_string_to_path
405 # endif
407 typedef struct
409 char *name;
410 void **ptr;
411 } Thunk_Info;
413 static Thunk_Info mzgc_imports[] = {
414 {"GC_malloc", (void **)&dll_GC_malloc},
415 {"GC_malloc_atomic", (void **)&dll_GC_malloc_atomic},
416 {NULL, NULL}};
418 static Thunk_Info mzsch_imports[] = {
419 {"scheme_eof", (void **)&dll_scheme_eof},
420 {"scheme_false", (void **)&dll_scheme_false},
421 {"scheme_void", (void **)&dll_scheme_void},
422 {"scheme_null", (void **)&dll_scheme_null},
423 {"scheme_true", (void **)&dll_scheme_true},
424 {"scheme_current_thread", (void **)&dll_scheme_current_thread_ptr},
425 {"scheme_console_printf", (void **)&dll_scheme_console_printf_ptr},
426 {"scheme_console_output", (void **)&dll_scheme_console_output_ptr},
427 {"scheme_notify_multithread",
428 (void **)&dll_scheme_notify_multithread_ptr},
429 {"scheme_add_global", (void **)&dll_scheme_add_global},
430 {"scheme_add_global_symbol", (void **)&dll_scheme_add_global_symbol},
431 {"scheme_apply", (void **)&dll_scheme_apply},
432 {"scheme_basic_env", (void **)&dll_scheme_basic_env},
433 # if MZSCHEME_VERSION_MAJOR >= 299
434 {"scheme_byte_string_to_char_string", (void **)&dll_scheme_byte_string_to_char_string},
435 # endif
436 {"scheme_builtin_value", (void **)&dll_scheme_builtin_value},
437 {"scheme_check_threads", (void **)&dll_scheme_check_threads},
438 {"scheme_close_input_port", (void **)&dll_scheme_close_input_port},
439 {"scheme_count_lines", (void **)&dll_scheme_count_lines},
440 {"scheme_current_continuation_marks",
441 (void **)&dll_scheme_current_continuation_marks},
442 {"scheme_display", (void **)&dll_scheme_display},
443 {"scheme_display_to_string", (void **)&dll_scheme_display_to_string},
444 {"scheme_do_eval", (void **)&dll_scheme_do_eval},
445 {"scheme_dont_gc_ptr", (void **)&dll_scheme_dont_gc_ptr},
446 {"scheme_eq", (void **)&dll_scheme_eq},
447 {"scheme_eval", (void **)&dll_scheme_eval},
448 {"scheme_eval_string", (void **)&dll_scheme_eval_string},
449 {"scheme_eval_string_all", (void **)&dll_scheme_eval_string_all},
450 {"scheme_finish_primitive_module",
451 (void **)&dll_scheme_finish_primitive_module},
452 # if MZSCHEME_VERSION_MAJOR < 299
453 {"scheme_format", (void **)&dll_scheme_format},
454 # else
455 {"scheme_format_utf8", (void **)&dll_scheme_format_utf8},
456 {"scheme_get_param", (void **)&dll_scheme_get_param},
457 #endif
458 {"scheme_gc_ptr_ok", (void **)&dll_scheme_gc_ptr_ok},
459 # if MZSCHEME_VERSION_MAJOR < 299
460 {"scheme_get_sized_string_output",
461 (void **)&dll_scheme_get_sized_string_output},
462 # else
463 {"scheme_get_sized_byte_string_output",
464 (void **)&dll_scheme_get_sized_byte_string_output},
465 #endif
466 {"scheme_intern_symbol", (void **)&dll_scheme_intern_symbol},
467 {"scheme_lookup_global", (void **)&dll_scheme_lookup_global},
468 {"scheme_make_closed_prim_w_arity",
469 (void **)&dll_scheme_make_closed_prim_w_arity},
470 {"scheme_make_integer_value", (void **)&dll_scheme_make_integer_value},
471 {"scheme_make_namespace", (void **)&dll_scheme_make_namespace},
472 {"scheme_make_pair", (void **)&dll_scheme_make_pair},
473 {"scheme_make_prim_w_arity", (void **)&dll_scheme_make_prim_w_arity},
474 # if MZSCHEME_VERSION_MAJOR < 299
475 {"scheme_make_string", (void **)&dll_scheme_make_string},
476 {"scheme_make_string_output_port",
477 (void **)&dll_scheme_make_string_output_port},
478 # else
479 {"scheme_make_byte_string", (void **)&dll_scheme_make_byte_string},
480 {"scheme_make_byte_string_output_port",
481 (void **)&dll_scheme_make_byte_string_output_port},
482 # endif
483 {"scheme_make_struct_instance",
484 (void **)&dll_scheme_make_struct_instance},
485 {"scheme_make_struct_names", (void **)&dll_scheme_make_struct_names},
486 {"scheme_make_struct_type", (void **)&dll_scheme_make_struct_type},
487 {"scheme_make_struct_values", (void **)&dll_scheme_make_struct_values},
488 {"scheme_make_type", (void **)&dll_scheme_make_type},
489 {"scheme_make_vector", (void **)&dll_scheme_make_vector},
490 {"scheme_malloc_fail_ok", (void **)&dll_scheme_malloc_fail_ok},
491 {"scheme_open_input_file", (void **)&dll_scheme_open_input_file},
492 {"scheme_primitive_module", (void **)&dll_scheme_primitive_module},
493 {"scheme_proper_list_length", (void **)&dll_scheme_proper_list_length},
494 {"scheme_raise", (void **)&dll_scheme_raise},
495 {"scheme_read", (void **)&dll_scheme_read},
496 {"scheme_register_static", (void **)&dll_scheme_register_static},
497 {"scheme_set_stack_base", (void **)&dll_scheme_set_stack_base},
498 {"scheme_signal_error", (void **)&dll_scheme_signal_error},
499 {"scheme_wrong_type", (void **)&dll_scheme_wrong_type},
500 # if MZSCHEME_VERSION_MAJOR >= 299
501 {"scheme_set_param", (void **)&dll_scheme_set_param},
502 {"scheme_current_config", (void **)&dll_scheme_current_config},
503 {"scheme_char_string_to_byte_string",
504 (void **)&dll_scheme_char_string_to_byte_string},
505 {"scheme_char_string_to_path",
506 (void **)&dll_scheme_char_string_to_path},
507 # endif
508 {NULL, NULL}};
510 static HINSTANCE hMzGC = 0;
511 static HINSTANCE hMzSch = 0;
513 static void dynamic_mzscheme_end(void);
514 static int mzscheme_runtime_link_init(char *sch_dll, char *gc_dll,
515 int verbose);
517 static int
518 mzscheme_runtime_link_init(char *sch_dll, char *gc_dll, int verbose)
520 Thunk_Info *thunk = NULL;
522 if (hMzGC && hMzSch)
523 return OK;
524 hMzSch = LoadLibrary(sch_dll);
525 hMzGC = LoadLibrary(gc_dll);
527 if (!hMzSch)
529 if (verbose)
530 EMSG2(_(e_loadlib), sch_dll);
531 return FAIL;
534 if (!hMzGC)
536 if (verbose)
537 EMSG2(_(e_loadlib), gc_dll);
538 return FAIL;
541 for (thunk = mzsch_imports; thunk->name; thunk++)
543 if ((*thunk->ptr =
544 (void *)GetProcAddress(hMzSch, thunk->name)) == NULL)
546 FreeLibrary(hMzSch);
547 hMzSch = 0;
548 FreeLibrary(hMzGC);
549 hMzGC = 0;
550 if (verbose)
551 EMSG2(_(e_loadfunc), thunk->name);
552 return FAIL;
555 for (thunk = mzgc_imports; thunk->name; thunk++)
557 if ((*thunk->ptr =
558 (void *)GetProcAddress(hMzGC, thunk->name)) == NULL)
560 FreeLibrary(hMzSch);
561 hMzSch = 0;
562 FreeLibrary(hMzGC);
563 hMzGC = 0;
564 if (verbose)
565 EMSG2(_(e_loadfunc), thunk->name);
566 return FAIL;
569 return OK;
573 mzscheme_enabled(int verbose)
575 return mzscheme_runtime_link_init(
576 DYNAMIC_MZSCH_DLL, DYNAMIC_MZGC_DLL, verbose) == OK;
579 static void
580 dynamic_mzscheme_end(void)
582 if (hMzSch)
584 FreeLibrary(hMzSch);
585 hMzSch = 0;
587 if (hMzGC)
589 FreeLibrary(hMzGC);
590 hMzGC = 0;
593 #endif /* DYNAMIC_MZSCHEME */
596 *========================================================================
597 * 1. MzScheme interpreter startup
598 *========================================================================
601 static Scheme_Type mz_buffer_type;
602 static Scheme_Type mz_window_type;
604 static int initialized = 0;
606 /* global environment */
607 static Scheme_Env *environment = NULL;
608 /* output/error handlers */
609 static Scheme_Object *curout = NULL;
610 static Scheme_Object *curerr = NULL;
611 /* vim:exn exception */
612 static Scheme_Object *exn_catching_apply = NULL;
613 static Scheme_Object *exn_p = NULL;
614 static Scheme_Object *exn_message = NULL;
615 static Scheme_Object *vim_exn = NULL; /* Vim Error exception */
616 /* values for exn:vim - constructor, predicate, accessors etc */
617 static Scheme_Object *vim_exn_names = NULL;
618 static Scheme_Object *vim_exn_values = NULL;
620 static long range_start;
621 static long range_end;
623 /* MzScheme threads scheduling stuff */
624 static int mz_threads_allow = 0;
626 #if defined(FEAT_GUI_W32)
627 static void CALLBACK timer_proc(HWND, UINT, UINT, DWORD);
628 static UINT timer_id = 0;
629 #elif defined(FEAT_GUI_GTK)
630 static gint timer_proc(gpointer);
631 static guint timer_id = 0;
632 #elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
633 static void timer_proc(XtPointer, XtIntervalId *);
634 static XtIntervalId timer_id = (XtIntervalId)0;
635 #elif defined(FEAT_GUI_MAC)
636 pascal void timer_proc(EventLoopTimerRef, void *);
637 static EventLoopTimerRef timer_id = NULL;
638 static EventLoopTimerUPP timerUPP;
639 #endif
641 #ifndef FEAT_GUI_W32 /* Win32 console and Unix */
642 void
643 mzvim_check_threads(void)
645 /* Last time MzScheme threads were scheduled */
646 static time_t mz_last_time = 0;
648 if (mz_threads_allow && p_mzq > 0)
650 time_t now = time(NULL);
652 if ((now - mz_last_time) * 1000 > p_mzq)
654 mz_last_time = now;
655 scheme_check_threads();
659 #endif
661 #ifdef MZSCHEME_GUI_THREADS
662 static void setup_timer(void);
663 static void remove_timer(void);
665 /* timers are presented in GUI only */
666 # if defined(FEAT_GUI_W32)
667 static void CALLBACK
668 timer_proc(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)
669 # elif defined(FEAT_GUI_GTK)
670 /*ARGSUSED*/
671 static gint
672 timer_proc(gpointer data)
673 # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
674 /* ARGSUSED */
675 static void
676 timer_proc(XtPointer timed_out, XtIntervalId *interval_id)
677 # elif defined(FEAT_GUI_MAC)
678 pascal void
679 timer_proc(EventLoopTimerRef theTimer, void *userData)
680 # endif
682 scheme_check_threads();
683 # if defined(FEAT_GUI_GTK)
684 return TRUE; /* continue receiving notifications */
685 # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
686 /* renew timeout */
687 if (mz_threads_allow && p_mzq > 0)
688 timer_id = XtAppAddTimeOut(app_context, p_mzq,
689 timer_proc, NULL);
690 # endif
693 static void
694 setup_timer(void)
696 # if defined(FEAT_GUI_W32)
697 timer_id = SetTimer(NULL, 0, p_mzq, timer_proc);
698 # elif defined(FEAT_GUI_GTK)
699 timer_id = gtk_timeout_add((guint32)p_mzq, (GtkFunction)timer_proc, NULL);
700 # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
701 timer_id = XtAppAddTimeOut(app_context, p_mzq, timer_proc, NULL);
702 # elif defined(FEAT_GUI_MAC)
703 timerUPP = NewEventLoopTimerUPP(timer_proc);
704 InstallEventLoopTimer(GetMainEventLoop(), p_mzq * kEventDurationMillisecond,
705 p_mzq * kEventDurationMillisecond, timerUPP, NULL, &timer_id);
706 # endif
709 static void
710 remove_timer(void)
712 # if defined(FEAT_GUI_W32)
713 KillTimer(NULL, timer_id);
714 # elif defined(FEAT_GUI_GTK)
715 gtk_timeout_remove(timer_id);
716 # elif defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)
717 XtRemoveTimeOut(timer_id);
718 # elif defined(FEAT_GUI_MAC)
719 RemoveEventLoopTimer(timer_id);
720 DisposeEventLoopTimerUPP(timerUPP);
721 # endif
722 timer_id = 0;
725 void
726 mzvim_reset_timer(void)
728 if (timer_id != 0)
729 remove_timer();
730 if (mz_threads_allow && p_mzq > 0 && gui.in_use)
731 setup_timer();
734 #endif /* MZSCHEME_GUI_THREADS */
736 static void
737 notify_multithread(int on)
739 mz_threads_allow = on;
740 #ifdef MZSCHEME_GUI_THREADS
741 if (on && timer_id == 0 && p_mzq > 0 && gui.in_use)
742 setup_timer();
743 if (!on && timer_id != 0)
744 remove_timer();
745 #endif
748 void
749 mzscheme_end(void)
751 #ifdef DYNAMIC_MZSCHEME
752 dynamic_mzscheme_end();
753 #endif
756 static void
757 startup_mzscheme(void)
759 Scheme_Object *proc_make_security_guard;
761 scheme_set_stack_base(NULL, 1);
763 MZ_REGISTER_STATIC(environment);
764 MZ_REGISTER_STATIC(curout);
765 MZ_REGISTER_STATIC(curerr);
766 MZ_REGISTER_STATIC(exn_catching_apply);
767 MZ_REGISTER_STATIC(exn_p);
768 MZ_REGISTER_STATIC(exn_message);
769 MZ_REGISTER_STATIC(vim_exn);
770 MZ_REGISTER_STATIC(vim_exn_names);
771 MZ_REGISTER_STATIC(vim_exn_values);
773 environment = scheme_basic_env();
775 /* redirect output */
776 scheme_console_output = do_output;
777 scheme_console_printf = do_printf;
779 #ifdef MZSCHEME_COLLECTS
780 /* setup 'current-library-collection-paths' parameter */
781 scheme_set_param(scheme_config, MZCONFIG_COLLECTION_PATHS,
782 scheme_make_pair(
783 # if MZSCHEME_VERSION_MAJOR >= 299
784 scheme_char_string_to_path(
785 scheme_byte_string_to_char_string(
786 scheme_make_byte_string(MZSCHEME_COLLECTS))),
787 # else
788 scheme_make_string(MZSCHEME_COLLECTS),
789 # endif
790 scheme_null));
791 #endif
792 #ifdef HAVE_SANDBOX
793 /* setup sandbox guards */
794 proc_make_security_guard = scheme_lookup_global(
795 scheme_intern_symbol("make-security-guard"),
796 environment);
797 if (proc_make_security_guard != NULL)
799 Scheme_Object *args[3];
800 Scheme_Object *guard;
801 args[0] = scheme_get_param(scheme_config, MZCONFIG_SECURITY_GUARD);
802 args[1] = scheme_make_prim_w_arity(sandbox_file_guard,
803 "sandbox-file-guard", 3, 3);
804 args[2] = scheme_make_prim_w_arity(sandbox_network_guard,
805 "sandbox-network-guard", 4, 4);
806 guard = scheme_apply(proc_make_security_guard, 3, args);
807 scheme_set_param(scheme_config, MZCONFIG_SECURITY_GUARD, guard);
809 #endif
810 /* Create buffer and window types for use in Scheme code */
811 mz_buffer_type = scheme_make_type("<vim-buffer>");
812 mz_window_type = scheme_make_type("<vim-window>");
814 register_vim_exn(environment);
815 make_modules(environment);
818 * setup callback to receive notifications
819 * whether thread scheduling is (or not) required
821 scheme_notify_multithread = notify_multithread;
822 initialized = 1;
826 * This routine is called for each new invocation of MzScheme
827 * to make sure things are properly initialized.
829 static int
830 mzscheme_init(void)
832 int do_require = FALSE;
834 if (!initialized)
836 do_require = TRUE;
837 #ifdef DYNAMIC_MZSCHEME
838 if (!mzscheme_enabled(TRUE))
840 EMSG(_("???: Sorry, this command is disabled, the MzScheme library could not be loaded."));
841 return -1;
843 #endif
844 startup_mzscheme();
846 if (mzscheme_io_init())
847 return -1;
850 /* recreate ports each call effectivelly clearing these ones */
851 curout = scheme_make_string_output_port();
852 curerr = scheme_make_string_output_port();
853 scheme_set_param(scheme_config, MZCONFIG_OUTPUT_PORT, curout);
854 scheme_set_param(scheme_config, MZCONFIG_ERROR_PORT, curerr);
856 if (do_require)
858 /* auto-instantiate in basic env */
859 eval_in_namespace("(require (prefix vimext: vimext))", do_eval,
860 environment, NULL);
863 return 0;
867 * This routine fills the namespace with various important routines that can
868 * be used within MzScheme.
870 static void
871 mzscheme_interface_init(vim_mz_buffer *mzbuff)
873 Scheme_Object *attach;
875 mzbuff->env = (Scheme_Env *)scheme_make_namespace(0, NULL);
878 * attach instantiated modules from global namespace
879 * so they can be easily instantiated in the buffer namespace
881 attach = scheme_lookup_global(
882 scheme_intern_symbol("namespace-attach-module"),
883 environment);
885 if (attach != NULL)
887 Scheme_Object *ret;
888 Scheme_Object *args[2];
890 args[0] = (Scheme_Object *)environment;
891 args[1] = scheme_intern_symbol("vimext");
893 ret = (Scheme_Object *)mzvim_apply(attach, 2, args);
896 add_vim_exn(mzbuff->env);
900 *========================================================================
901 * 2. External Interface
902 *========================================================================
906 * Evaluate command in namespace with exception handling
908 static int
909 eval_in_namespace(void *data, Scheme_Closed_Prim *what, Scheme_Env *env,
910 Scheme_Object **ret)
912 Scheme_Object *value;
913 Scheme_Object *exn;
914 Cmd_Info info; /* closure info */
916 info.data = data;
917 info.env = env;
919 scheme_set_param(scheme_config, MZCONFIG_ENV,
920 (Scheme_Object *) env);
922 * ensure all evaluations will be in current buffer namespace,
923 * the second argument to scheme_eval_string isn't enough!
925 value = _apply_thunk_catch_exceptions(
926 scheme_make_closed_prim_w_arity(what, &info, "mzvim", 0, 0),
927 &exn);
929 if (!value)
931 value = extract_exn_message(exn);
932 /* Got an exn? */
933 if (value)
935 scheme_display(value, curerr); /* Send to stderr-vim */
936 do_flush();
938 /* `raise' was called on some arbitrary value */
939 return FAIL;
942 if (ret != NULL) /* if pointer to retval supported give it up */
943 *ret = value;
944 /* Print any result, as long as it's not a void */
945 else if (!SCHEME_VOIDP(value))
946 scheme_display(value, curout); /* Send to stdout-vim */
948 do_flush();
949 return OK;
952 /* :mzscheme */
953 static int
954 do_mzscheme_command(exarg_T *eap, void *data, Scheme_Closed_Prim *what)
956 if (mzscheme_init())
957 return FAIL;
959 range_start = eap->line1;
960 range_end = eap->line2;
962 return eval_in_namespace(data, what, get_vim_curr_buffer()->env, NULL);
966 * Routine called by VIM when deleting a buffer
968 void
969 mzscheme_buffer_free(buf_T *buf)
971 if (buf->b_mzscheme_ref)
973 vim_mz_buffer *bp;
975 bp = buf->b_mzscheme_ref;
976 bp->buf = INVALID_BUFFER_VALUE;
977 buf->b_mzscheme_ref = NULL;
978 scheme_gc_ptr_ok(bp);
983 * Routine called by VIM when deleting a Window
985 void
986 mzscheme_window_free(win_T *win)
988 if (win->w_mzscheme_ref)
990 vim_mz_window *wp;
991 wp = win->w_mzscheme_ref;
992 wp->win = INVALID_WINDOW_VALUE;
993 win->w_mzscheme_ref = NULL;
994 scheme_gc_ptr_ok(wp);
999 * ":mzscheme" (or ":mz")
1001 void
1002 ex_mzscheme(exarg_T *eap)
1004 char_u *script;
1006 script = script_get(eap, eap->arg);
1007 if (!eap->skip)
1009 if (script == NULL)
1010 do_mzscheme_command(eap, eap->arg, do_eval);
1011 else
1013 do_mzscheme_command(eap, script, do_eval);
1014 vim_free(script);
1019 /* eval MzScheme string */
1020 void *
1021 mzvim_eval_string(char_u *str)
1023 Scheme_Object *ret = NULL;
1024 if (mzscheme_init())
1025 return FAIL;
1027 eval_in_namespace(str, do_eval, get_vim_curr_buffer()->env, &ret);
1028 return ret;
1032 * apply MzScheme procedure with arguments,
1033 * handling errors
1035 Scheme_Object *
1036 mzvim_apply(Scheme_Object *proc, int argc, Scheme_Object **argv)
1038 Apply_Info data;
1039 Scheme_Object *ret = NULL;
1041 if (mzscheme_init())
1042 return FAIL;
1044 data.proc = proc;
1045 data.argc = argc;
1046 data.argv = argv;
1048 eval_in_namespace(&data, do_apply, get_vim_curr_buffer()->env, &ret);
1049 return ret;
1052 static Scheme_Object *
1053 do_load(void *data, int noargc, Scheme_Object **noargv)
1055 Cmd_Info *info = (Cmd_Info *)data;
1056 Scheme_Object *result = scheme_void;
1057 Scheme_Object *expr;
1058 char_u *file = scheme_malloc_fail_ok(
1059 scheme_malloc_atomic, MAXPATHL + 1);
1060 Port_Info *pinfo = (Port_Info *)(info->data);
1062 /* make Vim expansion */
1063 expand_env((char_u *)pinfo->name, file, MAXPATHL);
1064 /* scheme_load looks strange working with namespaces and error handling*/
1065 pinfo->port = scheme_open_input_file(file, "mzfile");
1066 scheme_count_lines(pinfo->port); /* to get accurate read error location*/
1068 /* Like REPL but print only last result */
1069 while (!SCHEME_EOFP(expr = scheme_read(pinfo->port)))
1070 result = scheme_eval(expr, info->env);
1072 /* errors will be caught in do_mzscheme_comamnd and ex_mzfile */
1073 scheme_close_input_port(pinfo->port);
1074 pinfo->port = NULL;
1075 return result;
1078 /* :mzfile */
1079 void
1080 ex_mzfile(exarg_T *eap)
1082 Port_Info pinfo;
1084 pinfo.name = (char *)eap->arg;
1085 pinfo.port = NULL;
1086 if (do_mzscheme_command(eap, &pinfo, do_load) != OK
1087 && pinfo.port != NULL) /* looks like port was not closed */
1088 scheme_close_input_port(pinfo.port);
1093 *========================================================================
1094 * Exception handling code -- cribbed form the MzScheme sources and
1095 * Matthew Flatt's "Inside PLT MzScheme" document.
1096 *========================================================================
1098 static void
1099 init_exn_catching_apply(void)
1101 if (!exn_catching_apply)
1103 char *e =
1104 "(lambda (thunk) "
1105 "(with-handlers ([void (lambda (exn) (cons #f exn))]) "
1106 "(cons #t (thunk))))";
1108 /* make sure we have a namespace with the standard syntax: */
1109 Scheme_Env *env = (Scheme_Env *)scheme_make_namespace(0, NULL);
1110 add_vim_exn(env);
1112 exn_catching_apply = scheme_eval_string(e, env);
1113 exn_p = scheme_lookup_global(scheme_intern_symbol("exn?"), env);
1114 exn_message = scheme_lookup_global(
1115 scheme_intern_symbol("exn-message"), env);
1120 * This function applies a thunk, returning the Scheme value if there's
1121 * no exception, otherwise returning NULL and setting *exn to the raised
1122 * value (usually an exn structure).
1124 static Scheme_Object *
1125 _apply_thunk_catch_exceptions(Scheme_Object *f, Scheme_Object **exn)
1127 Scheme_Object *v;
1129 init_exn_catching_apply();
1131 v = _scheme_apply(exn_catching_apply, 1, &f);
1132 /* v is a pair: (cons #t value) or (cons #f exn) */
1134 if (SCHEME_TRUEP(SCHEME_CAR(v)))
1135 return SCHEME_CDR(v);
1136 else
1138 *exn = SCHEME_CDR(v);
1139 return NULL;
1143 static Scheme_Object *
1144 extract_exn_message(Scheme_Object *v)
1146 init_exn_catching_apply();
1148 if (SCHEME_TRUEP(_scheme_apply(exn_p, 1, &v)))
1149 return _scheme_apply(exn_message, 1, &v);
1150 else
1151 return NULL; /* Not an exn structure */
1154 static Scheme_Object *
1155 do_eval(void *s, int noargc, Scheme_Object **noargv)
1157 Cmd_Info *info = (Cmd_Info *)s;
1159 return scheme_eval_string_all((char *)(info->data), info->env, TRUE);
1162 static Scheme_Object *
1163 do_apply(void *a, int noargc, Scheme_Object **noargv)
1165 Apply_Info *info = (Apply_Info *)(((Cmd_Info *)a)->data);
1167 return scheme_apply(info->proc, info->argc, info->argv);
1171 *========================================================================
1172 * 3. MzScheme I/O Handlers
1173 *========================================================================
1175 static void
1176 do_intrnl_output(char *mesg, long len, int error)
1178 char *p, *prev;
1180 prev = mesg;
1181 p = strchr(prev, '\n');
1182 while (p)
1184 *p = '\0';
1185 if (error)
1186 EMSG(prev);
1187 else
1188 MSG(prev);
1189 prev = p + 1;
1190 p = strchr(prev, '\n');
1193 if (error)
1194 EMSG(prev);
1195 else
1196 MSG(prev);
1199 static void
1200 do_output(char *mesg, long len)
1202 do_intrnl_output(mesg, len, 0);
1205 static void
1206 do_err_output(char *mesg, long len)
1208 do_intrnl_output(mesg, len, 1);
1211 static void
1212 do_printf(char *format, ...)
1214 do_intrnl_output(format, STRLEN(format), 1);
1217 static void
1218 do_flush(void)
1220 char *buff;
1221 long length;
1223 buff = scheme_get_sized_string_output(curerr, &length);
1224 if (length)
1226 do_err_output(buff, length);
1227 return;
1230 buff = scheme_get_sized_string_output(curout, &length);
1231 if (length)
1232 do_output(buff, length);
1235 static int
1236 mzscheme_io_init(void)
1238 /* Nothing needed so far... */
1239 return 0;
1243 *========================================================================
1244 * 4. Implementation of the Vim Features for MzScheme
1245 *========================================================================
1248 /* (command {command-string}) */
1249 static Scheme_Object *
1250 vim_command(void *data, int argc, Scheme_Object **argv)
1252 Vim_Prim *prim = (Vim_Prim *)data;
1253 char *cmd = SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0));
1255 /* may be use do_cmdline_cmd? */
1256 do_cmdline((char_u *)cmd, NULL, NULL, DOCMD_NOWAIT|DOCMD_VERBOSE);
1257 update_screen(VALID);
1259 raise_if_error();
1260 return scheme_void;
1263 /* (eval {expr-string}) */
1264 static Scheme_Object *
1265 vim_eval(void *data, int argc, Scheme_Object **argv)
1267 #ifdef FEAT_EVAL
1268 Vim_Prim *prim = (Vim_Prim *)data;
1269 char *expr;
1270 char *str;
1271 Scheme_Object *result;
1273 expr = SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0));
1275 str = (char *)eval_to_string((char_u *)expr, NULL, TRUE);
1277 if (str == NULL)
1278 raise_vim_exn(_("invalid expression"));
1280 result = scheme_make_string(str);
1282 vim_free(str);
1284 return result;
1285 #else
1286 raise_vim_exn(_("expressions disabled at compile time"));
1287 /* unreachable */
1288 return scheme_false;
1289 #endif
1292 /* (range-start) */
1293 static Scheme_Object *
1294 get_range_start(void *data, int argc, Scheme_Object **argv)
1296 return scheme_make_integer(range_start);
1299 /* (range-end) */
1300 static Scheme_Object *
1301 get_range_end(void *data, int argc, Scheme_Object **argv)
1303 return scheme_make_integer(range_end);
1306 /* (beep) */
1307 static Scheme_Object *
1308 mzscheme_beep(void *data, int argc, Scheme_Object **argv)
1310 vim_beep();
1311 return scheme_void;
1314 static Scheme_Object *M_global = NULL;
1316 /* (get-option {option-name}) [buffer/window] */
1317 static Scheme_Object *
1318 get_option(void *data, int argc, Scheme_Object **argv)
1320 Vim_Prim *prim = (Vim_Prim *)data;
1321 char_u *name;
1322 long value;
1323 char_u *strval;
1324 int rc;
1325 Scheme_Object *rval;
1326 int opt_flags = 0;
1327 buf_T *save_curb = curbuf;
1328 win_T *save_curw = curwin;
1330 name = (char_u *)SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0));
1332 if (argc > 1)
1334 if (M_global == NULL)
1336 MZ_REGISTER_STATIC(M_global);
1337 M_global = scheme_intern_symbol("global");
1340 if (argv[1] == M_global)
1341 opt_flags = OPT_GLOBAL;
1342 else if (SCHEME_VIMBUFFERP(argv[1]))
1344 curbuf = get_valid_buffer(argv[1]);
1345 opt_flags = OPT_LOCAL;
1347 else if (SCHEME_VIMWINDOWP(argv[1]))
1349 win_T *win = get_valid_window(argv[1]);
1351 curwin = win;
1352 curbuf = win->w_buffer;
1353 opt_flags = OPT_LOCAL;
1355 else
1356 scheme_wrong_type(prim->name, "vim-buffer/window", 1, argc, argv);
1359 rc = get_option_value(name, &value, &strval, opt_flags);
1360 curbuf = save_curb;
1361 curwin = save_curw;
1363 switch (rc)
1365 case 1:
1366 return scheme_make_integer_value(value);
1367 case 0:
1368 rval = scheme_make_string(strval);
1369 vim_free(strval);
1370 return rval;
1371 case -1:
1372 case -2:
1373 raise_vim_exn(_("hidden option"));
1374 case -3:
1375 raise_vim_exn(_("unknown option"));
1377 /* unreachable */
1378 return scheme_void;
1381 /* (set-option {option-changing-string} [buffer/window]) */
1382 static Scheme_Object *
1383 set_option(void *data, int argc, Scheme_Object **argv)
1385 char_u *cmd;
1386 int opt_flags = 0;
1387 buf_T *save_curb = curbuf;
1388 win_T *save_curw = curwin;
1389 Vim_Prim *prim = (Vim_Prim *)data;
1391 GUARANTEE_STRING(prim->name, 0);
1392 if (argc > 1)
1394 if (M_global == NULL)
1396 MZ_REGISTER_STATIC(M_global);
1397 M_global = scheme_intern_symbol("global");
1400 if (argv[1] == M_global)
1401 opt_flags = OPT_GLOBAL;
1402 else if (SCHEME_VIMBUFFERP(argv[1]))
1404 curbuf = get_valid_buffer(argv[1]);
1405 opt_flags = OPT_LOCAL;
1407 else if (SCHEME_VIMWINDOWP(argv[1]))
1409 win_T *win = get_valid_window(argv[1]);
1410 curwin = win;
1411 curbuf = win->w_buffer;
1412 opt_flags = OPT_LOCAL;
1414 else
1415 scheme_wrong_type(prim->name, "vim-buffer/window", 1, argc, argv);
1418 /* do_set can modify cmd, make copy */
1419 cmd = vim_strsave((char_u *)SCHEME_STR_VAL(argv[0]));
1420 do_set(cmd, opt_flags);
1421 vim_free(cmd);
1422 update_screen(NOT_VALID);
1423 curbuf = save_curb;
1424 curwin = save_curw;
1425 raise_if_error();
1426 return scheme_void;
1430 *===========================================================================
1431 * 5. Vim Window-related Manipulation Functions
1432 *===========================================================================
1435 /* (curr-win) */
1436 static Scheme_Object *
1437 get_curr_win(void *data, int argc, Scheme_Object **argv)
1439 return (Scheme_Object *)get_vim_curr_window();
1442 /* (win-count) */
1443 static Scheme_Object *
1444 get_window_count(void *data, int argc, Scheme_Object **argv)
1446 win_T *w;
1447 int n = 0;
1449 for (w = firstwin; w != NULL; w = w->w_next)
1450 ++n;
1451 return scheme_make_integer(n);
1454 /* (get-win-list [buffer]) */
1455 static Scheme_Object *
1456 get_window_list(void *data, int argc, Scheme_Object **argv)
1458 Vim_Prim *prim = (Vim_Prim *)data;
1459 vim_mz_buffer *buf;
1460 Scheme_Object *list;
1461 win_T *w;
1463 buf = get_buffer_arg(prim->name, 0, argc, argv);
1464 list = scheme_null;
1466 for (w = firstwin; w != NULL; w = w->w_next)
1467 if (w->w_buffer == buf->buf)
1468 list = scheme_make_pair(window_new(w), list);
1470 return list;
1473 static Scheme_Object *
1474 window_new(win_T *win)
1476 vim_mz_window *self;
1478 /* We need to handle deletion of windows underneath us.
1479 * If we add a "w_mzscheme_ref" field to the win_T structure,
1480 * then we can get at it in win_free() in vim.
1482 * On a win_free() we set the Scheme object's win_T *field
1483 * to an invalid value. We trap all uses of a window
1484 * object, and reject them if the win_T *field is invalid.
1486 if (win->w_mzscheme_ref != NULL)
1487 return win->w_mzscheme_ref;
1489 self = scheme_malloc_fail_ok(scheme_malloc, sizeof(vim_mz_window));
1491 vim_memset(self, 0, sizeof(vim_mz_window));
1492 scheme_dont_gc_ptr(self); /* because win isn't visible to GC */
1493 win->w_mzscheme_ref = self;
1494 self->win = win;
1495 self->tag = mz_window_type;
1497 return (Scheme_Object *)(self);
1500 /* (get-win-num [window]) */
1501 static Scheme_Object *
1502 get_window_num(void *data, int argc, Scheme_Object **argv)
1504 Vim_Prim *prim = (Vim_Prim *)data;
1505 win_T *win = get_window_arg(prim->name, 0, argc, argv)->win;
1506 int nr = 1;
1507 win_T *wp;
1509 for (wp = firstwin; wp != win; wp = wp->w_next)
1510 ++nr;
1512 return scheme_make_integer(nr);
1515 /* (get-win-by-num {windownum}) */
1516 static Scheme_Object *
1517 get_window_by_num(void *data, int argc, Scheme_Object **argv)
1519 Vim_Prim *prim = (Vim_Prim *)data;
1520 win_T *win;
1521 int fnum;
1523 fnum = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
1524 if (fnum < 1)
1525 scheme_signal_error(_("window index is out of range"));
1527 for (win = firstwin; win != NULL; win = win->w_next, --fnum)
1528 if (fnum == 1) /* to be 1-based */
1529 return window_new(win);
1531 return scheme_false;
1534 /* (get-win-buffer [window]) */
1535 static Scheme_Object *
1536 get_window_buffer(void *data, int argc, Scheme_Object **argv)
1538 Vim_Prim *prim = (Vim_Prim *)data;
1539 vim_mz_window *win = get_window_arg(prim->name, 0, argc, argv);
1541 return buffer_new(win->win->w_buffer);
1544 /* (get-win-height [window]) */
1545 static Scheme_Object *
1546 get_window_height(void *data, int argc, Scheme_Object **argv)
1548 Vim_Prim *prim = (Vim_Prim *)data;
1549 vim_mz_window *win = get_window_arg(prim->name, 0, argc, argv);
1551 return scheme_make_integer(win->win->w_height);
1554 /* (set-win-height {height} [window]) */
1555 static Scheme_Object *
1556 set_window_height(void *data, int argc, Scheme_Object **argv)
1558 Vim_Prim *prim = (Vim_Prim *)data;
1559 vim_mz_window *win;
1560 win_T *savewin;
1561 int height;
1563 win = get_window_arg(prim->name, 1, argc, argv);
1564 height = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
1566 #ifdef FEAT_GUI
1567 need_mouse_correct = TRUE;
1568 #endif
1570 savewin = curwin;
1571 curwin = win->win;
1572 win_setheight(height);
1573 curwin = savewin;
1575 raise_if_error();
1576 return scheme_void;
1579 #ifdef FEAT_VERTSPLIT
1580 /* (get-win-width [window]) */
1581 static Scheme_Object *
1582 get_window_width(void *data, int argc, Scheme_Object **argv)
1584 Vim_Prim *prim = (Vim_Prim *)data;
1585 vim_mz_window *win = get_window_arg(prim->name, 0, argc, argv);
1587 return scheme_make_integer(W_WIDTH(win->win));
1590 /* (set-win-width {width} [window]) */
1591 static Scheme_Object *
1592 set_window_width(void *data, int argc, Scheme_Object **argv)
1594 Vim_Prim *prim = (Vim_Prim *)data;
1595 vim_mz_window *win;
1596 win_T *savewin;
1597 int width = 0;
1599 win = get_window_arg(prim->name, 1, argc, argv);
1600 width = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
1602 # ifdef FEAT_GUI
1603 need_mouse_correct = TRUE;
1604 # endif
1606 savewin = curwin;
1607 curwin = win->win;
1608 win_setwidth(width);
1609 curwin = savewin;
1611 raise_if_error();
1612 return scheme_void;
1614 #endif
1616 /* (get-cursor [window]) -> (line . col) */
1617 static Scheme_Object *
1618 get_cursor(void *data, int argc, Scheme_Object **argv)
1620 Vim_Prim *prim = (Vim_Prim *)data;
1621 vim_mz_window *win;
1622 pos_T pos;
1624 win = get_window_arg(prim->name, 0, argc, argv);
1625 pos = win->win->w_cursor;
1626 return scheme_make_pair(scheme_make_integer_value((long)pos.lnum),
1627 scheme_make_integer_value((long)pos.col + 1));
1630 /* (set-cursor (line . col) [window]) */
1631 static Scheme_Object *
1632 set_cursor(void *data, int argc, Scheme_Object **argv)
1634 Vim_Prim *prim = (Vim_Prim *)data;
1635 vim_mz_window *win;
1636 long lnum = 0;
1637 long col = 0;
1639 #ifdef HAVE_SANDBOX
1640 sandbox_check();
1641 #endif
1642 win = get_window_arg(prim->name, 1, argc, argv);
1643 GUARANTEE_PAIR(prim->name, 0);
1645 if (!SCHEME_INTP(SCHEME_CAR(argv[0]))
1646 || !SCHEME_INTP(SCHEME_CDR(argv[0])))
1647 scheme_wrong_type(prim->name, "integer pair", 0, argc, argv);
1649 lnum = SCHEME_INT_VAL(SCHEME_CAR(argv[0]));
1650 col = SCHEME_INT_VAL(SCHEME_CDR(argv[0])) - 1;
1652 check_line_range(lnum, win->win->w_buffer);
1653 /* don't know how to catch invalid column value */
1655 win->win->w_cursor.lnum = lnum;
1656 win->win->w_cursor.col = col;
1657 update_screen(VALID);
1659 raise_if_error();
1660 return scheme_void;
1663 *===========================================================================
1664 * 6. Vim Buffer-related Manipulation Functions
1665 * Note that each buffer should have its own private namespace.
1666 *===========================================================================
1669 /* (open-buff {filename}) */
1670 static Scheme_Object *
1671 mzscheme_open_buffer(void *data, int argc, Scheme_Object **argv)
1673 Vim_Prim *prim = (Vim_Prim *)data;
1674 char *fname;
1675 int num = 0;
1676 Scheme_Object *onum;
1678 #ifdef HAVE_SANDBOX
1679 sandbox_check();
1680 #endif
1681 fname = SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0));
1682 /* TODO make open existing file */
1683 num = buflist_add(fname, BLN_LISTED | BLN_CURBUF);
1685 if (num == 0)
1686 raise_vim_exn(_("couldn't open buffer"));
1688 onum = scheme_make_integer(num);
1689 return get_buffer_by_num(data, 1, &onum);
1692 /* (get-buff-by-num {buffernum}) */
1693 static Scheme_Object *
1694 get_buffer_by_num(void *data, int argc, Scheme_Object **argv)
1696 Vim_Prim *prim = (Vim_Prim *)data;
1697 buf_T *buf;
1698 int fnum;
1700 fnum = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
1702 for (buf = firstbuf; buf; buf = buf->b_next)
1703 if (buf->b_fnum == fnum)
1704 return buffer_new(buf);
1706 return scheme_false;
1709 /* (get-buff-by-name {buffername}) */
1710 static Scheme_Object *
1711 get_buffer_by_name(void *data, int argc, Scheme_Object **argv)
1713 Vim_Prim *prim = (Vim_Prim *)data;
1714 buf_T *buf;
1715 char_u *fname;
1717 fname = SCHEME_STR_VAL(GUARANTEE_STRING(prim->name, 0));
1719 for (buf = firstbuf; buf; buf = buf->b_next)
1720 if (buf->b_ffname == NULL || buf->b_sfname == NULL)
1721 /* empty string */
1723 if (fname[0] == NUL)
1724 return buffer_new(buf);
1726 else if (!fnamecmp(buf->b_ffname, fname)
1727 || !fnamecmp(buf->b_sfname, fname))
1728 /* either short or long filename matches */
1729 return buffer_new(buf);
1731 return scheme_false;
1734 /* (get-next-buff [buffer]) */
1735 static Scheme_Object *
1736 get_next_buffer(void *data, int argc, Scheme_Object **argv)
1738 Vim_Prim *prim = (Vim_Prim *)data;
1739 buf_T *buf = get_buffer_arg(prim->name, 0, argc, argv)->buf;
1741 if (buf->b_next == NULL)
1742 return scheme_false;
1743 else
1744 return buffer_new(buf->b_next);
1747 /* (get-prev-buff [buffer]) */
1748 static Scheme_Object *
1749 get_prev_buffer(void *data, int argc, Scheme_Object **argv)
1751 Vim_Prim *prim = (Vim_Prim *)data;
1752 buf_T *buf = get_buffer_arg(prim->name, 0, argc, argv)->buf;
1754 if (buf->b_prev == NULL)
1755 return scheme_false;
1756 else
1757 return buffer_new(buf->b_prev);
1760 /* (get-buff-num [buffer]) */
1761 static Scheme_Object *
1762 get_buffer_num(void *data, int argc, Scheme_Object **argv)
1764 Vim_Prim *prim = (Vim_Prim *)data;
1765 vim_mz_buffer *buf = get_buffer_arg(prim->name, 0, argc, argv);
1767 return scheme_make_integer(buf->buf->b_fnum);
1770 /* (buff-count) */
1771 static Scheme_Object *
1772 get_buffer_count(void *data, int argc, Scheme_Object **argv)
1774 buf_T *b;
1775 int n = 0;
1777 for (b = firstbuf; b; b = b->b_next) ++n;
1778 return scheme_make_integer(n);
1781 /* (get-buff-name [buffer]) */
1782 static Scheme_Object *
1783 get_buffer_name(void *data, int argc, Scheme_Object **argv)
1785 Vim_Prim *prim = (Vim_Prim *)data;
1786 vim_mz_buffer *buf = get_buffer_arg(prim->name, 0, argc, argv);
1788 return scheme_make_string(buf->buf->b_ffname);
1791 /* (curr-buff) */
1792 static Scheme_Object *
1793 get_curr_buffer(void *data, int argc, Scheme_Object **argv)
1795 return (Scheme_Object *)get_vim_curr_buffer();
1798 static Scheme_Object *
1799 buffer_new(buf_T *buf)
1801 vim_mz_buffer *self;
1803 /* We need to handle deletion of buffers underneath us.
1804 * If we add a "b_mzscheme_ref" field to the buf_T structure,
1805 * then we can get at it in buf_freeall() in vim.
1807 if (buf->b_mzscheme_ref)
1808 return buf->b_mzscheme_ref;
1810 self = scheme_malloc_fail_ok(scheme_malloc, sizeof(vim_mz_buffer));
1812 vim_memset(self, 0, sizeof(vim_mz_buffer));
1813 scheme_dont_gc_ptr(self); /* because buf isn't visible to GC */
1814 buf->b_mzscheme_ref = self;
1815 self->buf = buf;
1816 self->tag = mz_buffer_type;
1818 mzscheme_interface_init(self); /* Set up namespace */
1820 return (Scheme_Object *)(self);
1824 * (get-buff-size [buffer])
1826 * Get the size (number of lines) in the current buffer.
1828 static Scheme_Object *
1829 get_buffer_size(void *data, int argc, Scheme_Object **argv)
1831 Vim_Prim *prim = (Vim_Prim *)data;
1832 vim_mz_buffer *buf = get_buffer_arg(prim->name, 0, argc, argv);
1834 return scheme_make_integer(buf->buf->b_ml.ml_line_count);
1838 * (get-buff-line {linenr} [buffer])
1840 * Get a line from the specified buffer. The line number is
1841 * in Vim format (1-based). The line is returned as a MzScheme
1842 * string object.
1844 static Scheme_Object *
1845 get_buffer_line(void *data, int argc, Scheme_Object **argv)
1847 Vim_Prim *prim = (Vim_Prim *)data;
1848 vim_mz_buffer *buf;
1849 int linenr;
1850 char *line;
1852 buf = get_buffer_arg(prim->name, 1, argc, argv);
1853 linenr = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
1854 line = ml_get_buf(buf->buf, (linenr_T)linenr, FALSE);
1856 raise_if_error();
1857 return scheme_make_string(line);
1862 * (get-buff-line-list {start} {end} [buffer])
1864 * Get a list of lines from the specified buffer. The line numbers
1865 * are in Vim format (1-based). The range is from lo up to, but not
1866 * including, hi. The list is returned as a list of string objects.
1868 static Scheme_Object *
1869 get_buffer_line_list(void *data, int argc, Scheme_Object **argv)
1871 Vim_Prim *prim = (Vim_Prim *)data;
1872 vim_mz_buffer *buf;
1873 int i, hi, lo, n;
1874 Scheme_Object *list;
1876 buf = get_buffer_arg(prim->name, 2, argc, argv);
1877 list = scheme_null;
1878 hi = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 1));
1879 lo = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
1882 * Handle some error conditions
1884 if (lo < 0)
1885 lo = 0;
1887 if (hi < 0)
1888 hi = 0;
1889 if (hi < lo)
1890 hi = lo;
1892 n = hi - lo;
1894 for (i = n; i >= 0; --i)
1896 Scheme_Object *str = scheme_make_string(
1897 (char *)ml_get_buf(buf->buf, (linenr_T)(lo+i), FALSE));
1898 raise_if_error();
1900 /* Set the list item */
1901 list = scheme_make_pair(str, list);
1904 return list;
1908 * (set-buff-line {linenr} {string/#f} [buffer])
1910 * Replace a line in the specified buffer. The line number is
1911 * in Vim format (1-based). The replacement line is given as
1912 * an MzScheme string object. The object is checked for validity
1913 * and correct format. An exception is thrown if the values are not
1914 * the correct format.
1916 * It returns a Scheme Object that indicates the length of the
1917 * string changed.
1919 static Scheme_Object *
1920 set_buffer_line(void *data, int argc, Scheme_Object **argv)
1922 /* First of all, we check the the of the supplied MzScheme object.
1923 * There are three cases:
1924 * 1. #f - this is a deletion.
1925 * 2. A string - this is a replacement.
1926 * 3. Anything else - this is an error.
1928 Vim_Prim *prim = (Vim_Prim *)data;
1929 vim_mz_buffer *buf;
1930 Scheme_Object *line;
1931 char *save;
1932 buf_T *savebuf;
1933 int n;
1935 #ifdef HAVE_SANDBOX
1936 sandbox_check();
1937 #endif
1938 n = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
1939 if (!SCHEME_STRINGP(argv[1]) && !SCHEME_FALSEP(argv[1]))
1940 scheme_wrong_type(prim->name, "string or #f", 1, argc, argv);
1941 line = argv[1];
1942 buf = get_buffer_arg(prim->name, 2, argc, argv);
1944 check_line_range(n, buf->buf);
1946 if (SCHEME_FALSEP(line))
1948 savebuf = curbuf;
1949 curbuf = buf->buf;
1951 if (u_savedel((linenr_T)n, 1L) == FAIL)
1953 curbuf = savebuf;
1954 raise_vim_exn(_("cannot save undo information"));
1956 else if (ml_delete((linenr_T)n, FALSE) == FAIL)
1958 curbuf = savebuf;
1959 raise_vim_exn(_("cannot delete line"));
1961 deleted_lines_mark((linenr_T)n, 1L);
1962 if (buf->buf == curwin->w_buffer)
1963 mz_fix_cursor(n, n + 1, -1);
1965 curbuf = savebuf;
1967 raise_if_error();
1968 return scheme_void;
1971 /* Otherwise it's a line */
1972 save = string_to_line(line);
1973 savebuf = curbuf;
1975 curbuf = buf->buf;
1977 if (u_savesub((linenr_T)n) == FAIL)
1979 curbuf = savebuf;
1980 raise_vim_exn(_("cannot save undo information"));
1982 else if (ml_replace((linenr_T)n, (char_u *)save, TRUE) == FAIL)
1984 curbuf = savebuf;
1985 raise_vim_exn(_("cannot replace line"));
1987 else
1988 changed_bytes((linenr_T)n, 0);
1990 curbuf = savebuf;
1992 raise_if_error();
1993 return scheme_void;
1997 * (set-buff-line-list {start} {end} {string-list/#f/null} [buffer])
1999 * Replace a range of lines in the specified buffer. The line numbers are in
2000 * Vim format (1-based). The range is from lo up to, but not including, hi.
2001 * The replacement lines are given as a Scheme list of string objects. The
2002 * list is checked for validity and correct format.
2004 * Errors are returned as a value of FAIL. The return value is OK on success.
2005 * If OK is returned and len_change is not NULL, *len_change is set to the
2006 * change in the buffer length.
2008 static Scheme_Object *
2009 set_buffer_line_list(void *data, int argc, Scheme_Object **argv)
2011 /* First of all, we check the type of the supplied MzScheme object.
2012 * There are three cases:
2013 * 1. #f - this is a deletion.
2014 * 2. A list - this is a replacement.
2015 * 3. Anything else - this is an error.
2017 Vim_Prim *prim = (Vim_Prim *)data;
2018 vim_mz_buffer *buf;
2019 Scheme_Object *line_list;
2020 Scheme_Object *line;
2021 Scheme_Object *rest;
2022 char **array;
2023 buf_T *savebuf;
2024 int i, old_len, new_len, hi, lo;
2025 long extra;
2027 #ifdef HAVE_SANDBOX
2028 sandbox_check();
2029 #endif
2030 lo = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
2031 hi = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 1));
2032 if (!SCHEME_PAIRP(argv[2])
2033 && !SCHEME_FALSEP(argv[2]) && !SCHEME_NULLP(argv[2]))
2034 scheme_wrong_type(prim->name, "list or #f", 2, argc, argv);
2035 line_list = argv[2];
2036 buf = get_buffer_arg(prim->name, 3, argc, argv);
2037 old_len = hi - lo;
2038 if (old_len < 0) /* process inverse values wisely */
2040 i = lo;
2041 lo = hi;
2042 hi = i;
2043 old_len = -old_len;
2045 extra = 0;
2047 check_line_range(lo, buf->buf); /* inclusive */
2048 check_line_range(hi - 1, buf->buf); /* exclusive */
2050 if (SCHEME_FALSEP(line_list) || SCHEME_NULLP(line_list))
2052 savebuf = curbuf;
2053 curbuf = buf->buf;
2055 if (u_savedel((linenr_T)lo, (long)old_len) == FAIL)
2057 curbuf = savebuf;
2058 raise_vim_exn(_("cannot save undo information"));
2060 else
2062 for (i = 0; i < old_len; i++)
2063 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2065 curbuf = savebuf;
2066 raise_vim_exn(_("cannot delete line"));
2068 deleted_lines_mark((linenr_T)lo, (long)old_len);
2069 if (buf->buf == curwin->w_buffer)
2070 mz_fix_cursor(lo, hi, -old_len);
2073 curbuf = savebuf;
2075 raise_if_error();
2076 return scheme_void;
2079 /* List */
2080 new_len = scheme_proper_list_length(line_list);
2081 if (new_len < 0) /* improper or cyclic list */
2082 scheme_wrong_type(prim->name, "proper list",
2083 2, argc, argv);
2085 /* Using MzScheme allocator, so we don't need to free this and
2086 * can safely keep pointers to GC collected strings
2088 array = (char **)scheme_malloc_fail_ok(scheme_malloc,
2089 (unsigned)(new_len * sizeof(char *)));
2091 rest = line_list;
2092 for (i = 0; i < new_len; ++i)
2094 line = SCHEME_CAR(rest);
2095 rest = SCHEME_CDR(rest);
2096 if (!SCHEME_STRINGP(line))
2097 scheme_wrong_type(prim->name, "string-list", 2, argc, argv);
2098 array[i] = string_to_line(line);
2101 savebuf = curbuf;
2102 curbuf = buf->buf;
2104 if (u_save((linenr_T)(lo-1), (linenr_T)hi) == FAIL)
2106 curbuf = savebuf;
2107 raise_vim_exn(_("cannot save undo information"));
2111 * If the size of the range is reducing (ie, new_len < old_len) we
2112 * need to delete some old_len. We do this at the start, by
2113 * repeatedly deleting line "lo".
2115 for (i = 0; i < old_len - new_len; ++i)
2117 if (ml_delete((linenr_T)lo, FALSE) == FAIL)
2119 curbuf = savebuf;
2120 raise_vim_exn(_("cannot delete line"));
2122 extra--;
2126 * For as long as possible, replace the existing old_len with the
2127 * new old_len. This is a more efficient operation, as it requires
2128 * less memory allocation and freeing.
2130 for (i = 0; i < old_len && i < new_len; i++)
2131 if (ml_replace((linenr_T)(lo+i), (char_u *)array[i], TRUE) == FAIL)
2133 curbuf = savebuf;
2134 raise_vim_exn(_("cannot replace line"));
2138 * Now we may need to insert the remaining new_len. We don't need to
2139 * free the string passed back because MzScheme has control of that
2140 * memory.
2142 while (i < new_len)
2144 if (ml_append((linenr_T)(lo + i - 1),
2145 (char_u *)array[i], 0, FALSE) == FAIL)
2147 curbuf = savebuf;
2148 raise_vim_exn(_("cannot insert line"));
2150 ++i;
2151 ++extra;
2155 * Adjust marks. Invalidate any which lie in the
2156 * changed range, and move any in the remainder of the buffer.
2158 mark_adjust((linenr_T)lo, (linenr_T)(hi - 1), (long)MAXLNUM, (long)extra);
2159 changed_lines((linenr_T)lo, 0, (linenr_T)hi, (long)extra);
2161 if (buf->buf == curwin->w_buffer)
2162 mz_fix_cursor(lo, hi, extra);
2163 curbuf = savebuf;
2165 raise_if_error();
2166 return scheme_void;
2170 * (insert-buff-line-list {linenr} {string/string-list} [buffer])
2172 * Insert a number of lines into the specified buffer after the specifed line.
2173 * The line number is in Vim format (1-based). The lines to be inserted are
2174 * given as an MzScheme list of string objects or as a single string. The lines
2175 * to be added are checked for validity and correct format. Errors are
2176 * returned as a value of FAIL. The return value is OK on success.
2177 * If OK is returned and len_change is not NULL, *len_change
2178 * is set to the change in the buffer length.
2180 static Scheme_Object *
2181 insert_buffer_line_list(void *data, int argc, Scheme_Object **argv)
2183 Vim_Prim *prim = (Vim_Prim *)data;
2184 vim_mz_buffer *buf;
2185 Scheme_Object *list;
2186 Scheme_Object *line;
2187 Scheme_Object *rest;
2188 char **array;
2189 char *str;
2190 buf_T *savebuf;
2191 int i, n, size;
2193 #ifdef HAVE_SANDBOX
2194 sandbox_check();
2195 #endif
2197 * First of all, we check the type of the supplied MzScheme object.
2198 * It must be a string or a list, or the call is in error.
2200 n = SCHEME_INT_VAL(GUARANTEE_INTEGER(prim->name, 0));
2201 list = argv[1];
2203 if (!SCHEME_STRINGP(list) && !SCHEME_PAIRP(list))
2204 scheme_wrong_type(prim->name, "string or list", 1, argc, argv);
2205 buf = get_buffer_arg(prim->name, 2, argc, argv);
2207 if (n != 0) /* 0 can be used in insert */
2208 check_line_range(n, buf->buf);
2209 if (SCHEME_STRINGP(list))
2211 str = string_to_line(list);
2213 savebuf = curbuf;
2214 curbuf = buf->buf;
2216 if (u_save((linenr_T)n, (linenr_T)(n+1)) == FAIL)
2218 curbuf = savebuf;
2219 raise_vim_exn(_("cannot save undo information"));
2221 else if (ml_append((linenr_T)n, (char_u *)str, 0, FALSE) == FAIL)
2223 curbuf = savebuf;
2224 raise_vim_exn(_("cannot insert line"));
2226 else
2227 appended_lines_mark((linenr_T)n, 1L);
2229 curbuf = savebuf;
2230 update_screen(VALID);
2232 raise_if_error();
2233 return scheme_void;
2236 /* List */
2237 size = scheme_proper_list_length(list);
2238 if (size < 0) /* improper or cyclic list */
2239 scheme_wrong_type(prim->name, "proper list",
2240 2, argc, argv);
2242 /* Using MzScheme allocator, so we don't need to free this and
2243 * can safely keep pointers to GC collected strings
2245 array = (char **)scheme_malloc_fail_ok(
2246 scheme_malloc, (unsigned)(size * sizeof(char *)));
2248 rest = list;
2249 for (i = 0; i < size; ++i)
2251 line = SCHEME_CAR(rest);
2252 rest = SCHEME_CDR(rest);
2253 array[i] = string_to_line(line);
2256 savebuf = curbuf;
2257 curbuf = buf->buf;
2259 if (u_save((linenr_T)n, (linenr_T)(n + 1)) == FAIL)
2261 curbuf = savebuf;
2262 raise_vim_exn(_("cannot save undo information"));
2264 else
2266 for (i = 0; i < size; ++i)
2267 if (ml_append((linenr_T)(n + i), (char_u *)array[i],
2268 0, FALSE) == FAIL)
2270 curbuf = savebuf;
2271 raise_vim_exn(_("cannot insert line"));
2274 if (i > 0)
2275 appended_lines_mark((linenr_T)n, (long)i);
2278 curbuf = savebuf;
2279 update_screen(VALID);
2281 raise_if_error();
2282 return scheme_void;
2285 /* (get-buff-namespace [buffer]) */
2286 static Scheme_Object *
2287 get_buffer_namespace(void *data, int argc, Scheme_Object **argv)
2289 Vim_Prim *prim = (Vim_Prim *)data;
2291 return (Scheme_Object *)get_buffer_arg(prim->name, 0, argc, argv)->env;
2295 * Predicates
2297 /* (buff? obj) */
2298 static Scheme_Object *
2299 vim_bufferp(void *data, int argc, Scheme_Object **argv)
2301 if (SCHEME_VIMBUFFERP(argv[0]))
2302 return scheme_true;
2303 else
2304 return scheme_false;
2307 /* (win? obj) */
2308 static Scheme_Object *
2309 vim_windowp(void *data, int argc, Scheme_Object **argv)
2311 if (SCHEME_VIMWINDOWP(argv[0]))
2312 return scheme_true;
2313 else
2314 return scheme_false;
2317 /* (buff-valid? obj) */
2318 static Scheme_Object *
2319 vim_buffer_validp(void *data, int argc, Scheme_Object **argv)
2321 if (SCHEME_VIMBUFFERP(argv[0])
2322 && ((vim_mz_buffer *)argv[0])->buf != INVALID_BUFFER_VALUE)
2323 return scheme_true;
2324 else
2325 return scheme_false;
2328 /* (win-valid? obj) */
2329 static Scheme_Object *
2330 vim_window_validp(void *data, int argc, Scheme_Object **argv)
2332 if (SCHEME_VIMWINDOWP(argv[0])
2333 && ((vim_mz_window *)argv[0])->win != INVALID_WINDOW_VALUE)
2334 return scheme_true;
2335 else
2336 return scheme_false;
2340 *===========================================================================
2341 * Utilities
2342 *===========================================================================
2346 * Convert an MzScheme string into a Vim line.
2348 * The result is in allocated memory. All internal nulls are replaced by
2349 * newline characters. It is an error for the string to contain newline
2350 * characters.
2353 static char *
2354 string_to_line(Scheme_Object *obj)
2356 char *str;
2357 long len;
2358 int i;
2360 str = scheme_display_to_string(obj, &len);
2362 /* Error checking: String must not contain newlines, as we
2363 * are replacing a single line, and we must replace it with
2364 * a single line.
2366 if (memchr(str, '\n', len))
2367 scheme_signal_error(_("string cannot contain newlines"));
2369 /* Create a copy of the string, with internal nulls replaced by
2370 * newline characters, as is the vim convention.
2372 for (i = 0; i < len; ++i)
2374 if (str[i] == '\0')
2375 str[i] = '\n';
2378 str[i] = '\0';
2380 return str;
2384 * Check to see whether a Vim error has been reported, or a keyboard
2385 * interrupt (from vim --> got_int) has been detected.
2387 static int
2388 vim_error_check(void)
2390 return (got_int || did_emsg);
2394 * register Scheme exn:vim
2396 static void
2397 register_vim_exn(Scheme_Env *env)
2399 Scheme_Object *exn_name = scheme_intern_symbol("exn:vim");
2401 if (vim_exn == NULL)
2402 vim_exn = scheme_make_struct_type(exn_name,
2403 scheme_builtin_value("struct:exn"), NULL, 0, 0, NULL, NULL
2404 #if MZSCHEME_VERSION_MAJOR >= 299
2405 , NULL
2406 #endif
2409 if (vim_exn_values == NULL)
2411 int nc = 0;
2413 Scheme_Object **exn_names = scheme_make_struct_names(
2414 exn_name, scheme_null, 0, &nc);
2415 Scheme_Object **exn_values = scheme_make_struct_values(
2416 vim_exn, exn_names, nc, 0);
2418 vim_exn_names = scheme_make_vector(nc, scheme_false);
2419 vim_exn_values = scheme_make_vector(nc, scheme_false);
2420 /* remember names and values */
2421 mch_memmove(SCHEME_VEC_ELS(vim_exn_names), exn_names,
2422 nc * sizeof(Scheme_Object *));
2423 mch_memmove(SCHEME_VEC_ELS(vim_exn_values), exn_values,
2424 nc * sizeof(Scheme_Object *));
2427 add_vim_exn(env);
2431 * Add stuff of exn:vim to env
2433 static void
2434 add_vim_exn(Scheme_Env *env)
2436 int i;
2438 for (i = 0; i < SCHEME_VEC_SIZE(vim_exn_values); i++)
2439 scheme_add_global_symbol(SCHEME_VEC_ELS(vim_exn_names)[i],
2440 SCHEME_VEC_ELS(vim_exn_values)[i], env);
2444 * raise exn:vim, may be with additional info string
2446 void
2447 raise_vim_exn(const char *add_info)
2449 Scheme_Object *argv[2];
2450 char_u *fmt = _("Vim error: ~a");
2452 if (add_info != NULL)
2454 Scheme_Object *info = scheme_make_string(add_info);
2455 argv[0] = scheme_byte_string_to_char_string(scheme_make_string(
2456 scheme_format(fmt, strlen(fmt), 1, &info, NULL)));
2457 SCHEME_SET_IMMUTABLE(argv[0]);
2459 else
2460 argv[0] = scheme_make_string(_("Vim error"));
2462 #if MZSCHEME_VERSION_MAJOR < 360
2463 argv[1] = scheme_current_continuation_marks();
2464 #else
2465 argv[1] = scheme_current_continuation_marks(NULL);
2466 #endif
2468 scheme_raise(scheme_make_struct_instance(vim_exn, 2, argv));
2471 void
2472 raise_if_error(void)
2474 if (vim_error_check())
2475 raise_vim_exn(NULL);
2478 /* get buffer:
2479 * either current
2480 * or passed as argv[argnum] with checks
2482 static vim_mz_buffer *
2483 get_buffer_arg(const char *fname, int argnum, int argc, Scheme_Object **argv)
2485 vim_mz_buffer *b;
2487 if (argc < argnum + 1)
2488 return get_vim_curr_buffer();
2489 if (!SCHEME_VIMBUFFERP(argv[argnum]))
2490 scheme_wrong_type(fname, "vim-buffer", argnum, argc, argv);
2491 b = (vim_mz_buffer *)argv[argnum];
2492 (void)get_valid_buffer(argv[argnum]);
2493 return b;
2496 /* get window:
2497 * either current
2498 * or passed as argv[argnum] with checks
2500 static vim_mz_window *
2501 get_window_arg(const char *fname, int argnum, int argc, Scheme_Object **argv)
2503 vim_mz_window *w;
2505 if (argc < argnum + 1)
2506 return get_vim_curr_window();
2507 w = (vim_mz_window *)argv[argnum];
2508 if (!SCHEME_VIMWINDOWP(argv[argnum]))
2509 scheme_wrong_type(fname, "vim-window", argnum, argc, argv);
2510 (void)get_valid_window(argv[argnum]);
2511 return w;
2514 /* get valid Vim buffer from Scheme_Object* */
2515 buf_T *get_valid_buffer(void *obj)
2517 buf_T *buf = ((vim_mz_buffer *)obj)->buf;
2519 if (buf == INVALID_BUFFER_VALUE)
2520 scheme_signal_error(_("buffer is invalid"));
2521 return buf;
2524 /* get valid Vim window from Scheme_Object* */
2525 win_T *get_valid_window(void *obj)
2527 win_T *win = ((vim_mz_window *)obj)->win;
2528 if (win == INVALID_WINDOW_VALUE)
2529 scheme_signal_error(_("window is invalid"));
2530 return win;
2534 mzthreads_allowed(void)
2536 return mz_threads_allow;
2539 static int
2540 line_in_range(linenr_T lnum, buf_T *buf)
2542 return (lnum > 0 && lnum <= buf->b_ml.ml_line_count);
2545 static void
2546 check_line_range(linenr_T lnum, buf_T *buf)
2548 if (!line_in_range(lnum, buf))
2549 scheme_signal_error(_("linenr out of range"));
2553 * Check if deleting lines made the cursor position invalid
2554 * (or you'll get msg from Vim about invalid linenr).
2555 * Changed the lines from "lo" to "hi" and added "extra" lines (negative if
2556 * deleted). Got from if_python.c
2558 static void
2559 mz_fix_cursor(int lo, int hi, int extra)
2561 if (curwin->w_cursor.lnum >= lo)
2563 /* Adjust the cursor position if it's in/after the changed
2564 * lines. */
2565 if (curwin->w_cursor.lnum >= hi)
2567 curwin->w_cursor.lnum += extra;
2568 check_cursor_col();
2570 else if (extra < 0)
2572 curwin->w_cursor.lnum = lo;
2573 check_cursor();
2575 changed_cline_bef_curs();
2577 invalidate_botline();
2580 static Vim_Prim prims[]=
2583 * Buffer-related commands
2585 {get_buffer_line, "get-buff-line", 1, 2},
2586 {set_buffer_line, "set-buff-line", 2, 3},
2587 {get_buffer_line_list, "get-buff-line-list", 2, 3},
2588 {get_buffer_name, "get-buff-name", 0, 1},
2589 {get_buffer_num, "get-buff-num", 0, 1},
2590 {get_buffer_size, "get-buff-size", 0, 1},
2591 {set_buffer_line_list, "set-buff-line-list", 3, 4},
2592 {insert_buffer_line_list, "insert-buff-line-list", 2, 3},
2593 {get_curr_buffer, "curr-buff", 0, 0},
2594 {get_buffer_count, "buff-count", 0, 0},
2595 {get_next_buffer, "get-next-buff", 0, 1},
2596 {get_prev_buffer, "get-prev-buff", 0, 1},
2597 {mzscheme_open_buffer, "open-buff", 1, 1},
2598 {get_buffer_by_name, "get-buff-by-name", 1, 1},
2599 {get_buffer_by_num, "get-buff-by-num", 1, 1},
2600 {get_buffer_namespace, "get-buff-namespace", 0, 1},
2602 * Window-related commands
2604 {get_curr_win, "curr-win", 0, 0},
2605 {get_window_count, "win-count", 0, 0},
2606 {get_window_by_num, "get-win-by-num", 1, 1},
2607 {get_window_num, "get-win-num", 0, 1},
2608 {get_window_buffer, "get-win-buffer", 0, 1},
2609 {get_window_height, "get-win-height", 0, 1},
2610 {set_window_height, "set-win-height", 1, 2},
2611 #ifdef FEAT_VERTSPLIT
2612 {get_window_width, "get-win-width", 0, 1},
2613 {set_window_width, "set-win-width", 1, 2},
2614 #endif
2615 {get_cursor, "get-cursor", 0, 1},
2616 {set_cursor, "set-cursor", 1, 2},
2617 {get_window_list, "get-win-list", 0, 1},
2619 * Vim-related commands
2621 {vim_command, "command", 1, 1},
2622 {vim_eval, "eval", 1, 1},
2623 {get_range_start, "range-start", 0, 0},
2624 {get_range_end, "range-end", 0, 0},
2625 {mzscheme_beep, "beep", 0, 0},
2626 {get_option, "get-option", 1, 2},
2627 {set_option, "set-option", 1, 2},
2629 * small utilities
2631 {vim_bufferp, "buff?", 1, 1},
2632 {vim_windowp, "win?", 1, 1},
2633 {vim_buffer_validp, "buff-valid?", 1, 1},
2634 {vim_window_validp, "win-valid?", 1, 1}
2637 /* return MzScheme wrapper for curbuf */
2638 static vim_mz_buffer *
2639 get_vim_curr_buffer(void)
2641 if (curbuf->b_mzscheme_ref == NULL)
2642 return (vim_mz_buffer *)buffer_new(curbuf);
2643 else
2644 return (vim_mz_buffer *)curbuf->b_mzscheme_ref;
2647 /* return MzScheme wrapper for curwin */
2648 static vim_mz_window *
2649 get_vim_curr_window(void)
2651 if (curwin->w_mzscheme_ref == NULL)
2652 return (vim_mz_window *)window_new(curwin);
2653 else
2654 return (vim_mz_window *)curwin->w_mzscheme_ref;
2657 static void
2658 make_modules(Scheme_Env *env)
2660 int i;
2661 Scheme_Env *mod;
2663 mod = scheme_primitive_module(scheme_intern_symbol("vimext"), env);
2664 /* all prims made closed so they can access their own names */
2665 for (i = 0; i < sizeof(prims)/sizeof(prims[0]); i++)
2667 Vim_Prim *prim = prims + i;
2668 scheme_add_global(prim->name,
2669 scheme_make_closed_prim_w_arity(prim->prim, prim, prim->name,
2670 prim->mina, prim->maxa),
2671 mod);
2673 scheme_add_global("global-namespace", (Scheme_Object *)environment, mod);
2674 scheme_finish_primitive_module(mod);
2677 #ifdef HAVE_SANDBOX
2678 static Scheme_Object *M_write = NULL;
2679 static Scheme_Object *M_read = NULL;
2680 static Scheme_Object *M_execute = NULL;
2681 static Scheme_Object *M_delete = NULL;
2683 static void
2684 sandbox_check(void)
2686 if (sandbox)
2687 raise_vim_exn(_("not allowed in the Vim sandbox"));
2690 /* security guards to force Vim's sandbox restrictions on MzScheme level */
2691 static Scheme_Object *
2692 sandbox_file_guard(int argc, Scheme_Object **argv)
2694 if (sandbox)
2696 Scheme_Object *requested_access = argv[2];
2698 if (M_write == NULL)
2700 MZ_REGISTER_STATIC(M_write);
2701 M_write = scheme_intern_symbol("write");
2703 if (M_read == NULL)
2705 MZ_REGISTER_STATIC(M_read);
2706 M_read = scheme_intern_symbol("read");
2708 if (M_execute == NULL)
2710 MZ_REGISTER_STATIC(M_execute);
2711 M_execute = scheme_intern_symbol("execute");
2713 if (M_delete == NULL)
2715 MZ_REGISTER_STATIC(M_delete);
2716 M_delete = scheme_intern_symbol("delete");
2719 while (!SCHEME_NULLP(requested_access))
2721 Scheme_Object *item = SCHEME_CAR(requested_access);
2722 if (scheme_eq(item, M_write) || scheme_eq(item, M_read)
2723 || scheme_eq(item, M_execute) || scheme_eq(item, M_delete))
2725 raise_vim_exn(_("not allowed in the Vim sandbox"));
2727 requested_access = SCHEME_CDR(requested_access);
2730 return scheme_void;
2733 static Scheme_Object *
2734 sandbox_network_guard(int argc, Scheme_Object **argv)
2736 return scheme_void;
2738 #endif
2740 #endif