]> git.donarmstrong.com Git - lilypond.git/blob - lily/general-scheme.cc
Merge with master
[lilypond.git] / lily / general-scheme.cc
1 /*
2   lily-guile.cc -- implement assorted Guile bindings
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1998--2007 Jan Nieuwenhuizen <janneke@gnu.org>
7   Han-Wen Nienhuys <hanwen@xs4all.nl>
8 */
9
10 #include "config.hh"
11
12 #include <cstdio>
13 #include <ctype.h>
14 #include <cstring>  /* memset */
15 using namespace std;
16
17 #include "international.hh"
18 #include "libc-extension.hh"
19 #include "lily-guile.hh"
20 #include "misc.hh"
21 #include "warn.hh"
22 #include "version.hh"
23 #include "dimensions.hh"
24 #include "main.hh"
25 #include "file-path.hh"
26 #include "relocate.hh"
27 #include "file-name.hh"
28 #include "string-convert.hh"
29
30 LY_DEFINE (ly_find_file, "ly:find-file",
31            1, 0, 0, (SCM name),
32            "Return the absolute file name of @var{name}, "
33            "or @code{#f} if not found.")
34 {
35   LY_ASSERT_TYPE (scm_is_string, name, 1);
36
37   string nm = ly_scm2string (name);
38   string file_name = global_path.find (nm);
39   if (file_name.empty ())
40     return SCM_BOOL_F;
41
42   return ly_string2scm (file_name);
43 }
44
45 /*
46   Ugh. Gulped file is copied twice. (maybe thrice if you count stdio
47   buffering.)
48 */
49 LY_DEFINE (ly_gulp_file, "ly:gulp-file",
50            1, 1, 0, (SCM name, SCM size),
51            "Read the file @var{name}, and return its contents in a string.  "
52            "The file is looked up using the search path. ")
53 {
54   LY_ASSERT_TYPE (scm_is_string, name, 1);
55   int sz = INT_MAX;
56   if (size != SCM_UNDEFINED)
57     {
58       LY_ASSERT_TYPE(scm_is_number,size, 2);
59       sz = scm_to_int (size);
60     }
61   
62   string contents = gulp_file_to_string (ly_scm2string (name), true, sz);
63   return scm_from_locale_stringn (contents.c_str (), contents.length ());
64 }
65
66 LY_DEFINE (ly_error, "ly:error",
67            1, 0, 1, (SCM str, SCM rest),
68            "Scheme callable function to issue the error @code{msg}. "
69            "The error is formatted with @code{format} and @code{rest}.")
70 {
71   LY_ASSERT_TYPE (scm_is_string, str, 1);
72   str = scm_simple_format (SCM_BOOL_F, str, rest);
73   error (ly_scm2string (str));
74   return SCM_UNSPECIFIED;
75 }
76
77 LY_DEFINE (ly_message, "ly:message",
78            1, 0, 1, (SCM str, SCM rest),
79            "Scheme callable function to issue the message @code{msg}. "
80            "The message is formatted with @code{format} and @code{rest}.")
81 {
82   LY_ASSERT_TYPE (scm_is_string, str, 1);
83   str = scm_simple_format (SCM_BOOL_F, str, rest);
84   message (ly_scm2string (str));
85   return SCM_UNSPECIFIED;
86 }
87
88 LY_DEFINE (ly_progress, "ly:progress",
89            1, 0, 1, (SCM str, SCM rest),
90            "Scheme callable function to print progress @code{str}. "
91            "The message is formatted with @code{format} and @code{rest}.")
92 {
93   LY_ASSERT_TYPE (scm_is_string, str, 1);
94   str = scm_simple_format (SCM_BOOL_F, str, rest);
95   progress_indication (ly_scm2string (str));
96   return SCM_UNSPECIFIED;
97 }
98
99 LY_DEFINE (ly_programming_error, "ly:programming-error",
100            1, 0, 1, (SCM str, SCM rest),
101            "Scheme callable function to issue the warning @code{msg}. "
102            "The message is formatted with @code{format} and @code{rest}.")
103 {
104   LY_ASSERT_TYPE (scm_is_string, str, 1);
105   str = scm_simple_format (SCM_BOOL_F, str, rest);
106   programming_error (ly_scm2string (str));
107   return SCM_UNSPECIFIED;
108 }
109
110 LY_DEFINE (ly_warning, "ly:warning",
111            1, 0, 1, (SCM str, SCM rest),
112            "Scheme callable function to issue the warning @code{str}. "
113            "The message is formatted with @code{format} and @code{rest}.")
114 {
115   LY_ASSERT_TYPE (scm_is_string, str, 1);
116   str = scm_simple_format (SCM_BOOL_F, str, rest);
117   warning (ly_scm2string (str));
118   return SCM_UNSPECIFIED;
119 }
120
121 LY_DEFINE (ly_dir_p, "ly:dir?",
122            1, 0, 0, (SCM s),
123            "type predicate. A direction is @code{-1}, @code{0} or "
124            "@code{1}, where @code{-1} represents "
125            "left or down and @code{1} represents right or up.")
126 {
127   if (scm_is_number (s))
128     {
129       int i = scm_to_int (s);
130       return (i >= -1 && i <= 1) ? SCM_BOOL_T : SCM_BOOL_F;
131     }
132   return SCM_BOOL_F;
133 }
134
135 LY_DEFINE (ly_assoc_get, "ly:assoc-get",
136            2, 1, 0,
137            (SCM key, SCM alist, SCM default_value),
138            "Return value if KEY in ALIST, else DEFAULT-VALUE "
139            "(or #f if not specified).")
140 {
141   SCM handle = scm_assoc (key, alist);
142   if (scm_is_pair (handle))
143     return scm_cdr (handle);
144   
145   if (default_value == SCM_UNDEFINED)
146     default_value = SCM_BOOL_F;
147
148   return default_value;
149 }
150
151 LY_DEFINE (ly_string_substitute, "ly:string-substitute",
152            3, 0, 0, (SCM a, SCM b, SCM s),
153            "Replace @var{a} by @var{b} in @var{s}.")
154 {
155   LY_ASSERT_TYPE (scm_is_string, s, 1);
156   LY_ASSERT_TYPE(scm_is_string,b, 2);
157   LY_ASSERT_TYPE(scm_is_string,s, 3);
158
159   string ss = ly_scm2string (s);
160   replace_all (ss, string (scm_i_string_chars (a)),
161                    string (scm_i_string_chars (b)));
162   return ly_string2scm (ss);
163 }
164   
165 LY_DEFINE (ly_number_2_string, "ly:number->string",
166            1, 0, 0, (SCM s),
167            "Convert @var{num} to a string without generating many decimals.")
168 {
169   LY_ASSERT_TYPE (scm_is_number, s, 1);
170
171   char str[400];                        // ugh.
172
173   if (scm_exact_p (s) == SCM_BOOL_F)
174     {
175       Real r (scm_to_double (s));
176         if (isinf (r) || isnan (r))
177           {
178             programming_error (_ ("infinity or NaN encountered while converting Real number"));
179             programming_error (_ ("setting to zero"));
180
181             r = 0.0;
182           }
183
184       snprintf (str, sizeof (str), "%.4f", r);
185     }
186   else
187     snprintf (str, sizeof (str), "%d", int (scm_to_int (s)));
188
189   return scm_from_locale_string (str);
190 }
191
192 LY_DEFINE (ly_version, "ly:version", 0, 0, 0, (),
193            "Return the current lilypond version as a list, e.g. @code{(1 3 127 uu1)}. ")
194 {
195   char const *vs = "\'(" MAJOR_VERSION " " MINOR_VERSION " " PATCH_LEVEL " " MY_PATCH_LEVEL ")";
196
197   return scm_c_eval_string ((char *)vs);
198 }
199
200 LY_DEFINE (ly_unit, "ly:unit", 0, 0, 0, (),
201            "Return the unit used for lengths as a string.")
202 {
203   return scm_from_locale_string (INTERNAL_UNIT);
204 }
205
206 LY_DEFINE (ly_dimension_p, "ly:dimension?", 1, 0, 0, (SCM d),
207            "Return @var{d} is a number. Used to distinguish length "
208            "variables from normal numbers.")
209 {
210   return scm_number_p (d);
211 }
212
213 /*
214   Debugging mem leaks:
215 */
216 LY_DEFINE (ly_protects, "ly:protects",
217            0, 0, 0, (),
218            "Return hash of protected objects.")
219 {
220   return scm_protects;
221 }
222
223 LY_DEFINE (ly_gettext, "ly:gettext",
224            1, 0, 0, (SCM string),
225            "Gettext wrapper.")
226 {
227   LY_ASSERT_TYPE (scm_is_string, string, 1);
228   return ly_string2scm (_ (scm_i_string_chars (string)));
229 }
230
231 LY_DEFINE (ly_output_backend, "ly:output-backend",
232            0, 0, 0, (),
233            "Return name of output backend.")
234 {
235   return ly_string2scm (output_backend_global);
236 }
237
238 LY_DEFINE (ly_output_formats, "ly:output-formats",
239            0, 0, 0, (),
240            "Formats passed to --format as a list of strings, "
241            "used for the output.")
242 {
243   vector<string> output_formats = string_split (output_format_global, ',');
244
245   SCM lst = SCM_EOL;
246   int output_formats_count = output_formats.size ();
247   for (int i = 0; i < output_formats_count; i++)
248     lst = scm_cons (ly_string2scm (output_formats[i]), lst);
249
250   return lst;
251 }
252
253 LY_DEFINE (ly_wide_char_2_utf_8, "ly:wide-char->utf-8",
254            1, 0, 0, (SCM wc),
255            "Encode the Unicode codepoint @var{wc}, an integer, as UTF-8")
256 {
257   char buf[5];
258
259   LY_ASSERT_TYPE (scm_is_integer, wc, 1);
260   unsigned wide_char = (unsigned) scm_to_int (wc);
261   char *p = buf;
262
263   if (wide_char < 0x0080)
264     *p++ = (char)wide_char;
265   else if (wide_char < 0x0800)
266     {
267       *p++ = (char) (((wide_char >> 6)) | 0xC0);
268       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
269     }
270   else if (wide_char < 0x10000)
271     {
272       *p++ = (char) (((wide_char >> 12)) | 0xE0);
273       *p++ = (char) (((wide_char >> 6) & 0x3F) | 0x80);
274       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
275     }
276   else
277     {
278       *p++ = (char) (((wide_char >> 18)) | 0xF0);
279       *p++ = (char) (((wide_char >> 12) & 0x3F) | 0x80);
280       *p++ = (char) (((wide_char >> 6) & 0x3F) | 0x80);
281       *p++ = (char) (((wide_char) & 0x3F) | 0x80);
282     }
283   *p = 0;
284
285   return scm_from_locale_string (buf);
286 }
287
288 LY_DEFINE (ly_effective_prefix, "ly:effective-prefix",
289            0, 0, 0, (),
290            "Return effective prefix.")
291 {
292   return ly_string2scm (prefix_directory);
293 }
294
295 LY_DEFINE (ly_chain_assoc_get, "ly:chain-assoc-get",
296            2, 1, 0, (SCM key, SCM achain, SCM dfault),
297            "Return value for @var{key} from a list of alists @var{achain}.  "
298            "If no if no entry is found, return DFAULT, "
299            "or #f if no DFAULT not specified.")
300 {
301   if (scm_is_pair (achain))
302     {
303       SCM handle = scm_assoc (key, scm_car (achain));
304       if (scm_is_pair (handle))
305         return scm_cdr (handle);
306       else
307         return ly_chain_assoc_get (key, scm_cdr (achain), dfault);
308     }
309   return dfault == SCM_UNDEFINED ? SCM_BOOL_F : dfault;
310 }
311
312
313 LY_DEFINE (ly_stderr_redirect, "ly:stderr-redirect",
314            1, 1, 0, (SCM file_name, SCM mode),
315            "Redirect stderr to FILE-NAME, opened with MODE.")
316 {
317   LY_ASSERT_TYPE (scm_is_string, file_name, 1);
318
319   string m = "w";
320   if (mode != SCM_UNDEFINED && scm_string_p (mode))
321     m = ly_scm2string (mode);
322   /* dup2 and (fileno (current-error-port)) do not work with mingw'c
323      gcc -mwindows.  */
324   fflush (stderr); 
325   freopen (ly_scm2string (file_name).c_str (), m.c_str (), stderr);
326   return SCM_UNSPECIFIED;
327 }
328
329 static SCM
330 accumulate_symbol (void *closure, SCM key, SCM val, SCM result)
331 {
332   (void) closure;
333   (void) val;
334   return scm_cons (key, result);
335 }
336
337 LY_DEFINE(ly_hash_table_keys, "ly:hash-table-keys",
338           1,0,0, (SCM tab),
339           "return a list of keys in @var{tab}")
340 {
341   return scm_internal_hash_fold ((Hash_closure_function) & accumulate_symbol,
342                                  NULL, SCM_EOL, tab);
343 }
344
345 LY_DEFINE (ly_camel_case_2_lisp_identifier, "ly:camel-case->lisp-identifier",
346            1, 0, 0, (SCM name_sym),
347            "Convert FooBar_Bla to foo-bar-bla style symbol.")
348 {
349   LY_ASSERT_TYPE (ly_is_symbol, name_sym, 1);
350   
351   /*
352     TODO: should use strings instead?
353   */
354   
355   const string in = ly_symbol2string (name_sym);
356   string result = camel_case_to_lisp_identifier (in);
357
358   return ly_symbol2scm (result.c_str ());
359 }
360
361 LY_DEFINE (ly_expand_environment, "ly:expand-environment",
362            1, 0, 0, (SCM str),
363            "Expand $VAR and $@{VAR@} in @var{str}.")
364 {
365   LY_ASSERT_TYPE (scm_is_string, str, 1);
366
367   return ly_string2scm (expand_environment_variables (ly_scm2string (str)));
368 }
369                  
370
371 LY_DEFINE (ly_truncate_list_x, "ly:truncate-list!",
372            2, 0, 0, (SCM lst, SCM i),
373            "Take at most the first @var{i} of list @var{lst}")
374 {
375   LY_ASSERT_TYPE (scm_is_integer, i, 1);
376
377   int k = scm_to_int (i);
378   if (k == 0)
379     lst = SCM_EOL;
380   else
381     {
382       SCM s = lst;
383       k--;
384       for (; scm_is_pair (s) && k--; s = scm_cdr (s))
385         ;
386
387       if (scm_is_pair (s))
388         scm_set_cdr_x (s, SCM_EOL);
389     }
390   return lst;
391 }
392
393 string
394 format_single_argument (SCM arg, int precision)
395 {
396   if (scm_is_integer (arg) && scm_exact_p (arg) == SCM_BOOL_T)
397     return (String_convert::int_string (scm_to_int (arg)));
398   else if (scm_is_number (arg))
399     {
400       Real val = scm_to_double (arg);
401
402       if (isnan (val) || isinf (val))
403         {
404           warning (_ ("Found infinity or nan in output. Substituting 0.0"));
405           return ("0.0");
406           if (strict_infinity_checking)
407             abort();
408         }
409       else
410         return (String_convert::form_string ("%.*lf", precision, val));
411     }
412   else if (scm_is_string (arg))
413     return (ly_scm2string (arg));
414   else if (scm_is_symbol (arg))
415     return (ly_symbol2string (arg));
416   else
417     {
418       ly_progress (scm_from_locale_string ("Unsupported SCM value for format: ~a"),
419                    scm_list_1 (arg));
420     }
421   
422     
423   return "";    
424 }
425
426 LY_DEFINE (ly_format, "ly:format",
427            1, 0, 1, (SCM str, SCM rest),
428            "LilyPond specific format, supporting ~a ~[0-9]f.")
429 {
430   LY_ASSERT_TYPE (scm_is_string, str, 1);
431
432   string format = ly_scm2string (str);
433   vector<string> results;
434
435   vsize i = 0;
436   while (i < format.size())
437     {
438       vsize tilde = format.find ('~', i);
439
440       results.push_back (format.substr (i, (tilde-i)));
441
442       if (tilde == NPOS)
443         break ;
444       
445       tilde ++;
446
447       char spec = format.at (tilde ++);
448       if (spec == '~')
449         results.push_back ("~");
450       else
451         {
452           if (!scm_is_pair (rest))
453             {
454               programming_error (string (__FUNCTION__) 
455                                  + ": not enough arguments for format.");
456               return ly_string2scm ("");
457             }
458           
459           SCM arg = scm_car (rest);
460           rest = scm_cdr (rest);
461
462           int precision = 8;
463           
464           if (spec == '$')
465             precision = '2';
466           else if (isdigit (spec))
467             {
468               precision = spec - '0';
469               spec = format.at (tilde ++);
470             }
471                    
472           if (spec == 'a' || spec == 'f')
473             results.push_back (format_single_argument (arg, precision));
474           else if (spec == 'l')
475             {
476               SCM s = arg;
477               for (; scm_is_pair (s); s = scm_cdr (s))
478                 {
479                   results.push_back (format_single_argument (scm_car (s), precision));
480                   if (scm_cdr (s) != SCM_EOL)
481                     results.push_back (" ");
482                 }
483
484               if (s != SCM_EOL)
485                 results.push_back (format_single_argument (s, precision));
486                 
487             }
488         }
489
490       i = tilde;
491     }
492
493   if (scm_is_pair (rest))
494     programming_error (string (__FUNCTION__)
495                        + ": too many  arguments");
496
497   vsize len = 0;
498   for (vsize i = 0; i < results.size(); i++)
499     len += results[i].size();
500   
501   char *result = (char*) scm_malloc (len + 1);
502   char *ptr = result;
503   for (vsize i = 0; i < results.size(); i++)
504     {
505       strncpy (ptr, results[i].c_str (), results[i].size());
506       ptr += results[i].size();
507     }
508   *ptr = '\0';
509     
510   return scm_take_locale_stringn (result, len);
511 }