Updated RELEASE_NOTES.
[mp-5.x.git] / mp_core.mpsl
blob82c7ca01fee8b65fc7b3bc165f1779618cbdb9f2
1 /*
3     Minimum Profit 5.x
4     A Programmer's Text Editor
6     Copyright (C) 1991-2009 Angel Ortega <angel@triptico.com>
8     This program is free software; you can redistribute it and/or
9     modify it under the terms of the GNU General Public License
10     as published by the Free Software Foundation; either version 2
11     of the License, or (at your option) any later version.
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
18     You should have received a copy of the GNU General Public License
19     along with this program; if not, write to the Free Software
20     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22     http://www.triptico.com
26 /** global data **/
28 /* L(x) is the same as gettext(x) */
29 L = gettext;
31 /* LL(x) is the same as x */
32 sub LL(x) { x; }
34 /* configuration */
36 mp.config = {};
37 mp.config.undo_levels = 100;
38 mp.config.word_wrap = 0;
39 mp.config.auto_indent = 0;
40 mp.config.tab_size = 8;
41 mp.config.tabs_as_spaces = 0;
42 mp.config.unlink = 1;
43 mp.config.case_sensitive_search = 1;
44 mp.config.global_replace = 0;
45 mp.config.preread_lines = 60;
46 mp.config.mark_eol = 0;
47 mp.config.maximize = 0;
48 mp.config.keep_eol = 1;
50 /* default end of line, system dependent */
51 if (mp.drv.id eq 'win32')
52         mp.config.eol = "\r\n";
53 else
54         mp.config.eol = "\n";
56 /* status line */
57 mp.config.status_format = "%m%n %x,%y [%l] %R%O %s %e %t";
58 mp.status_line_info = {
59         '%V'    =>      mp.VERSION,
60         '%m'    =>      sub { mp.active.txt.mod && '*' || ''; },
61         '%x'    =>      sub { mp.active.txt.x + 1; },
62         '%y'    =>      sub { mp.active.txt.y + 1; },
63         '%l'    =>      sub { size(mp.active.txt.lines); },
64         '%R'    =>      sub { mp.macro.process_event && 'R' || ''; },
65         '%O'    =>      '',
66         '%s'    =>      sub { mp.active.syntax.name; },
67         '%t'    =>      sub { mp.tags[mp.get_word(mp.active())].label; },
68         '%n'    =>      sub { mp.active.name; },
69         '%w'    =>      sub { mp.word_count(mp.active()); },
70         '%e'    =>      sub { mp.active.encoding || ''; },
71         '%%'    =>      '%'
74 /* a regex for selecting words */
75 mp.word_regex = "/[[:alnum:]_]+/i";
77 /* if it does not work (i.e. not GNU regex), fall back */
78 if (regex(mp.word_regex, "test") == NULL)
79         mp.word_regex = '/[A-Z_][A-Z0-9_]*/i';
81 /* document list */
82 mp.docs = [];
83 mp.active_i = 0;
85 /* allowed color names (order matters, match the Unix curses one) */
86 mp.color_names = [ "default", "black", "red", "green",
87         "yellow", "blue", "magenta", "cyan", "white" ];
89 /* color definitions */
90 mp.colors = {
91         'normal' => {           'text'  => [ 'default', 'default' ],
92                                 'gui'   => [ 0x000000, 0xffffff ] },
93         'cursor' => {           'text'  => [ 'default', 'default' ],
94                                 'gui'   => [ 0x000000, 0xffffff ],
95                                 'flags' => [ 'reverse' ] },
96         'selection' => {        'text'  => [ 'red', 'default' ],
97                                 'gui'   => [ 0xff0000, 0xffffff ],
98                                 'flags' => [ 'reverse'] },
99         'comments' => {         'text'  => [ 'green', 'default' ],
100                                 'gui'   => [ 0x00cc77, 0xffffff ] },
101         'documentation' => {    'text'  => [ 'cyan', 'default' ],
102                                 'gui'   => [ 0x8888ff, 0xffffff ] },
103         'quotes' => {           'text'  => [ 'blue', 'default' ],
104                                 'gui'   => [ 0x0000ff, 0xffffff ],
105                                 'flags' => [ 'bright' ] },
106         'matching' => {         'text'  => [ 'black', 'cyan' ],
107                                 'gui'   => [ 0x000000, 0xffff00 ] },
108         'word1' => {            'text'  => [ 'green', 'default' ],
109                                 'gui'   => [ 0x00aa00, 0xffffff ],
110                                 'flags' => [ 'bright' ] },
111         'word2' => {            'text'  => [ 'red', 'default' ],
112                                 'gui'   => [ 0xff6666, 0xffffff ],
113                                 'flags' => [ 'bright' ] },
114         'tag' => {              'text'  => [ 'cyan', 'default' ],
115                                 'gui'   => [ 0x8888ff, 0xffffff ],
116                                 'flags' => [ 'underline' ] },
117         'spell' => {            'text'  => [ 'red', 'default' ],
118                                 'gui'   => [ 0xff8888, 0xffffff ],
119                                 'flags' => [ 'bright', 'underline' ] },
120         'search' => {           'text'  => [ 'black', 'green' ],
121                                 'gui'   => [ 0x000000, 0x00cc77 ] }
124 /* hash of specially coloured words */
125 mp.word_color = {};
127 mp.keycodes = {};
129 mp.actions = {};
131 mp.actdesc = {};
133 mp.alert_log = [];
135 /** the menu **/
137 mp.menu = [
138         [
139                 LL("&File"),
140                 [ 'new', 'open', 'save', 'save_as', 'close', 'revert',
141                         'open_under_cursor',
142                         '-', 'hex_view',
143                         '-', 'set_password',
144                         '-', 'open_config_file', 'open_templates_file',
145                         '-', 'sync',
146                         '-', 'save_session', 'load_session',
147                         '-', 'exit'
148                 ]
149         ],
150         [
151                 LL("&Edit"),
152                 [ 'undo', 'redo', '-',
153                         'cut_mark', 'copy_mark', 'paste_mark', 'delete_line', '-',
154                         'mark', 'mark_vertical', 'unmark', '-',
155                         'insert_template', '-',
156                         'word_wrap_paragraph', 'join_paragraph', '-',
157                         'exec_command', '-',
158                         'eval', 'eval_doc'
159                 ]
160         ],
161         [
162                 LL("&Search"),
163                 [ 'seek', 'seek_next', 'seek_prev', 'replace', '-',
164                         'complete', '-',
165                         'seek_misspelled', 'ignore_last_misspell', '-',
166                         'seek_repeated_word', '-',
167                         'find_tag', 'complete_symbol', '-', 'grep'
168                 ]
169         ],
170         [
171                 LL("&Go to"),
172                 [ 'next', 'prev',
173                         'move_bof', 'move_eof', 'move_bol', 'move_eol',
174                         'goto', 'move_word_right', 'move_word_left',
175                         'section_list',
176                         '-', 'document_list'
177                 ]
178         ],
179         [
180                 LL("&Options"),
181                 [ 'record_macro', 'play_macro', '-',
182                         'encoding', 'tab_options', 'line_options', 'repeated_words_options',
183                         'toggle_spellcheck', '-',
184                         'word_count', '-',
185                         'zoom_in', 'zoom_out', '-',
186                         'about'
187                 ]
188         ]
191 mp.actions_by_menu_label = {};
193 /** code **/
196  * mp.redraw - Triggers a redraw on the next cycle.
198  * Triggers a full document redraw in the next cycle.
199  */
200 sub mp.redraw()
202         /* just increment the redraw trigger */
203         mp.redraw_counter++;
207 sub mp.active()
208 /* returns the active document */
210         local d;
212         /* empty document list? create a new, empty one */
213         if (size(mp.docs) == 0)
214                 mp.new();
216         /* get active document */
217         d = mp.docs[mp.active_i];
219         /* if it's read only but has modifications, revert them */
220         if (d.read_only && size(d.undo)) {
221                 while (size(d.undo))
222                         mp.undo(d);
224                 mp.message = {
225                         'timeout'       => time() + 2,
226                         'string'        => '*' ~ L("Read-only document") ~ '*'
227                 };
228         }
230         return d;
234 sub mp.process_action(a)
235 /* processes an action */
237         local f, d;
239         d = mp.active();
241         if ((f = mp.actions[a]) != NULL)
242                 f(d);
243         else {
244                 mp.message = {
245                         'timeout'       => time() + 2,
246                         'string'        => sprintf(L("Unknown action '%s'"), a)
247                 };
248         }
252 sub mp.process_event(k)
253 /* processes a key event */
255         local d, a;
257         /* empty document list? do nothing */
258         if (size(mp.docs) == 0)
259                 return;
261         d = mp.active();
263         if (mp.keycodes_t == NULL)
264                 mp.keycodes_t = mp.keycodes;
266         /* get the action asociated to the keycode */
267         if ((a = mp.keycodes_t[k]) != NULL) {
269                 /* if it's a hash, store for further testing */
270                 if (is_hash(a))
271                         mp.keycodes_t = a;
272                 else {
273                         /* if it's executable, run it */
274                         if (is_exec(a))
275                                 a(d);
276                         else
277                         /* if it's an array, process it sequentially */
278                         if (is_array(a))
279                                 foreach(l, a)
280                                         mp.process_action(l);
281                         else
282                                 mp.process_action(a);
284                         mp.keycodes_t = NULL;
285                 }
286         }
287         else {
288                 mp.insert_keystroke(d, k);
289                 mp.keycodes_t = NULL;
290         }
292         mp.shift_pressed = NULL;
296 sub mp.build_status_line()
297 /* returns the string to be drawn in the status line */
299         if (mp.message) {
300                 /* is the message still active? */
301                 if (mp.message.timeout > time())
302                         return mp.message.string;
304                 mp.message = NULL;
305         }
307         return sregex("/%./g", mp.config.status_format, mp.status_line_info);
311 sub mp.backslash_codes(s, d)
312 /* encodes (d == 0) or decodes (d == 1) backslash codes
313    (like \n, \r, etc.) */
315         d &&    sregex("/[\r\n\t]/g", s, { "\r" => '\r', "\n" => '\n', "\t" => '\t'}) ||
316                 sregex("/\\\\[rnt]/g", s, { '\r' => "\r", '\n' => "\n", '\t' => "\t"});
320 sub mp.long_op(func, a1, a2, a3, a4)
321 /* executes a potentially long function */
323         local r;
325         mp.busy(1);
326         r = func(a1, a2, a3, a4);
327         mp.busy(0);
329         return r;
333 sub mp.get_history(key)
334 /* returns a history for the specified key */
336         if (key == NULL)
337                 return NULL;
338         if (mp.history == NULL)
339                 mp.history = {};
340         if (mp.history[key] == NULL)
341                 mp.history[key] = [];
343         return mp.history[key];
347 sub mp.menu_label(action)
348 /* returns a label for the menu for an action */
350         local l;
352         /* if action is '-', it's a menu separator */
353         if (action eq '-')
354                 return NULL;
356         /* no recognized action? return */
357         if (!exists(mp.actions, action))
358                 return action ~ "?";
360         /* get the translated description */
361         l = L(mp.actdesc[action]) || action;
363         /* is there a keycode that generates this action? */
364         foreach (i, sort(keys(mp.keycodes))) {
365                 if (mp.keycodes[i] eq action) {
366                         /* avoid mouse and window pseudo-keycodes */
367                         if (!regex("/window/", i) && !regex("/mouse/", i)) {
368                                 l = l ~ ' [' ~ i ~ ']';
369                                 break;
370                         }
371                 }
372         }
374         mp.actions_by_menu_label[l] = action;
376         return l;
380 sub mp.trim_with_ellipsis(str, max)
381 /* trims the string to the last max characters, adding ellipsis if done */
383         local v = regex('/.{' ~ max ~ '}$/', str);
384         return v && '...' ~ v || str;
388 sub mp.get_doc_names(max)
389 /* returns an array with the trimmed names of the documents */
391         map(sub(e) {
392                 (e.txt.mod && '* ' || '') ~ mp.trim_with_ellipsis(e.name, (max || 24));
393         }, mp.docs);
397 sub mp.usage()
398 /* set mp.exit_message with an usage message (--help) */
400         mp.exit_message = 
401         sprintf(L(
402                 "Minimum Profit %s - Programmer Text Editor\n"\
403                 "Copyright (C) Angel Ortega <angel@triptico.com>\n"\
404                 "This software is covered by the GPL license. NO WARRANTY.\n"\
405                 "\n"\
406                 "Usage: mp-5 [options] [files...]\n"\
407                 "\n"\
408                 "Options:\n"\
409                 "\n"\
410                 " -t {tag}           Edits the file where tag is defined\n"\
411                 " -e {mpsl_code}     Executes MPSL code\n"\
412                 " -f {mpsl_script}   Executes MPSL script file\n"\
413                 " -d {directory}     Set current directory\n"\
414                 " +NNN               Moves to line number NNN of last file\n"\
415                 "\n"\
416                 "Homepage: http://www.triptico.com/software/mp.html\n"\
417                 "Mailing list: mp-subscribe@lists.triptico.com\n"
418         ), mp.VERSION);
422 sub mp.process_cmdline()
423 /* process the command line arguments (ARGV) */
425         local o, line;
427         mp.load_tags();
429         /* skip ARGV[0] */
430         shift(ARGV);
432         while (o = shift(ARGV)) {
433                 if (o eq '-h' || o eq '--help') {
434                         mp.usage();
435                         mp.exit();
436                         return;
437                 }
438                 else
439                 if (o eq '-e') {
440                         /* execute code */
441                         local c = shift(ARGV);
443                         if (! regex('/;\s*$/', c))
444                                 c = c ~ ';';
446                         eval(c);
447                 }
448                 else
449                 if (o eq '-f') {
450                         /* execute script */
451                         local s = shift(ARGV);
453                         if (stat(s) == NULL)
454                                 ERROR = sprintf(L("Cannot open '%s'"), s);
455                         else {
456                                 mp.open(s);
457                                 eval(join("\n", mp.active.txt.lines));
458                                 mp.close();
459                         }
460                 }
461                 else
462                 if (o eq '-d')
463                         chdir(shift(ARGV));
464                 else
465                 if (o eq '-t')
466                         mp.open_tag(shift(ARGV));
467                 else
468                 if (o eq '-x') {
469                         local s = shift(ARGV);
471                         if (mp.hex_view(s) == NULL)
472                                 ERROR = sprintf(L("Cannot open '%s'"), s);
473                 }
474                 else
475                 if (regex('/^\+/', o)) {
476                         /* move to line */
477                         line = o - 1;
478                 }
479                 else
480                         mp.open(o);
481         }
483         if (ERROR) {
484                 mp.exit_message = ERROR ~ "\n";
485                 ERROR = NULL;
486                 mp.exit();
487                 return;
488         }
490         /* if no files are loaded, try a session */
491         if (size(mp.docs) == 0 && mp.config.auto_sessions) {
492                 mp.load_session();
493         }
494         else {
495                 /* set the first as the active one */
496                 mp.active_i = 0;
497         }
499         mp.active();
501         /* if there is a line defined, move there */
502         if (line != NULL)
503                 mp.set_y(mp.active(), line);
507 sub mp.load_profile()
508 /* loads ~/.mp.mpsl */
510         /* if /etc/mp.mpsl exists, execute it */
511         if (stat('/etc/mp.mpsl') != NULL) {
512                 eval( sub {
513                         local INC = [ '/etc' ];
514                         load('mp.mpsl');
515                 });
516         }
518         /* if ~/.mp.mpsl exists, execute it */
519         if (ERROR == NULL && stat(HOMEDIR ~ '.mp.mpsl') != NULL) {
520                 eval( sub {
521                         local INC = [ HOMEDIR ];
522                         load(".mp.mpsl");
523                 });
524         }
526         /* errors? show in a message */
527         if (ERROR != NULL) {
528                 mp.message = {
529                         'timeout'       => time() + 20,
530                         'string'        => ERROR
531                 };
533                 ERROR = NULL;
534         }
538 sub mp.setup_language()
539 /* sets up the language */
541         /* set gettext() domain */
542         gettext_domain('minimum-profit', APPDIR ~ 'locale');
544         /* test if gettext() can do a basic translation */
545         if (gettext('&File') eq '&File' && ENV.LANG) {
546                 /* no; try alternatives using the LANG variable */
547                 local v = [ sregex('!/!g', ENV.LANG) ]; /* es_ES.UTF-8 */
548                 push(v, shift(split('.', v[-1])));      /* es_ES */
549                 push(v, shift(split('_', v[-1])));      /* es */
551                 foreach (l, v) {
552                         eval('load("lang/' ~ l ~ '.mpsl");');
554                         if (ERROR == NULL)
555                                 break;
556                 }
558                 ERROR = NULL;
559         }
563 sub mp.normalize_version(vs)
564 /* converts a version string to something usable with cmp() */
566         map(sub(e) { sprintf("%03d", e); },
567                 split('.',
568                         sregex('/-.+$/', vs)));
572 sub mp.assert_version(found, minimal, package)
573 /* asserts that 'found' version of 'package' is at least 'minimal',
574    or generate a warning otherwise */
576         if (cmp(mp.normalize_version(found),
577                 mp.normalize_version(minimal)) < 0) {
578                 mp.alert(sprintf(L("WARNING: %s version found is %s, but %s is needed"),
579                                 package, found, minimal));
580         }
584 sub mp.test_versions()
585 /* tests component versions */
587         local mpdm = MPDM();
589         mp.assert_version(mpdm.version, '1.0.7', 'MPDM');
590         mp.assert_version(MPSL.VERSION, '1.0.7', 'MPSL');
594 /** MAIN **/
596 load("mp_drv.mpsl");
597 load("mp_move.mpsl");
598 load("mp_edit.mpsl");
599 load("mp_file.mpsl");
600 load("mp_clipboard.mpsl");
601 load("mp_search.mpsl");
602 load("mp_tags.mpsl");
603 load("mp_syntax.mpsl");
604 load("mp_macro.mpsl");
605 load("mp_templates.mpsl");
606 load("mp_spell.mpsl");
607 load("mp_misc.mpsl");
608 load("mp_crypt.mpsl");
609 load("mp_keyseq.mpsl");
610 load("mp_session.mpsl");
611 load("mp_build.mpsl");
612 load("mp_writing.mpsl");
614 mp.load_profile();
615 mp.setup_language();
616 mp.drv.startup();
617 mp.process_cmdline();
618 mp.test_versions();
619 mp.drv.main_loop();
620 mp.drv.shutdown();