The mp_plain_load() function stores the last seen EOL in mp.last_seen_eol.
[mp-5.x.git] / mp_core.mpsl
blobe3ee2ad1ac1531575bbfe6960867c7a7546d6763
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;
49 /* default end of line, system dependent */
50 if (mp.drv.id eq 'win32')
51         mp.config.eol = "\r\n";
52 else
53         mp.config.eol = "\n";
55 /* status line */
56 mp.config.status_format = "%m%n %x,%y [%l] %R%O %s %e %t";
57 mp.status_line_info = {
58         '%V'    =>      mp.VERSION,
59         '%m'    =>      sub { mp.active.txt.mod && '*' || ''; },
60         '%x'    =>      sub { mp.active.txt.x + 1; },
61         '%y'    =>      sub { mp.active.txt.y + 1; },
62         '%l'    =>      sub { size(mp.active.txt.lines); },
63         '%R'    =>      sub { mp.macro.process_event && 'R' || ''; },
64         '%O'    =>      '',
65         '%s'    =>      sub { mp.active.syntax.name; },
66         '%t'    =>      sub { mp.tags[mp.get_word(mp.active())].label; },
67         '%n'    =>      sub { mp.active.name; },
68         '%w'    =>      sub { mp.word_count(mp.active()); },
69         '%e'    =>      sub { mp.active.encoding || ''; },
70         '%%'    =>      '%'
73 /* a regex for selecting words */
74 mp.word_regex = "/[[:alnum:]_]+/i";
76 /* if it does not work (i.e. not GNU regex), fall back */
77 if (regex(mp.word_regex, "test") == NULL)
78         mp.word_regex = '/[A-Z_][A-Z0-9_]*/i';
80 /* document list */
81 mp.docs = [];
82 mp.active_i = 0;
84 /* allowed color names (order matters, match the Unix curses one) */
85 mp.color_names = [ "default", "black", "red", "green",
86         "yellow", "blue", "magenta", "cyan", "white" ];
88 /* color definitions */
89 mp.colors = {
90         'normal' => {           'text'  => [ 'default', 'default' ],
91                                 'gui'   => [ 0x000000, 0xffffff ] },
92         'cursor' => {           'text'  => [ 'default', 'default' ],
93                                 'gui'   => [ 0x000000, 0xffffff ],
94                                 'flags' => [ 'reverse' ] },
95         'selection' => {        'text'  => [ 'red', 'default' ],
96                                 'gui'   => [ 0xff0000, 0xffffff ],
97                                 'flags' => [ 'reverse'] },
98         'comments' => {         'text'  => [ 'green', 'default' ],
99                                 'gui'   => [ 0x00cc77, 0xffffff ] },
100         'documentation' => {    'text'  => [ 'cyan', 'default' ],
101                                 'gui'   => [ 0x8888ff, 0xffffff ] },
102         'quotes' => {           'text'  => [ 'blue', 'default' ],
103                                 'gui'   => [ 0x0000ff, 0xffffff ],
104                                 'flags' => [ 'bright' ] },
105         'matching' => {         'text'  => [ 'black', 'cyan' ],
106                                 'gui'   => [ 0x000000, 0xffff00 ] },
107         'word1' => {            'text'  => [ 'green', 'default' ],
108                                 'gui'   => [ 0x00aa00, 0xffffff ],
109                                 'flags' => [ 'bright' ] },
110         'word2' => {            'text'  => [ 'red', 'default' ],
111                                 'gui'   => [ 0xff6666, 0xffffff ],
112                                 'flags' => [ 'bright' ] },
113         'tag' => {              'text'  => [ 'cyan', 'default' ],
114                                 'gui'   => [ 0x8888ff, 0xffffff ],
115                                 'flags' => [ 'underline' ] },
116         'spell' => {            'text'  => [ 'red', 'default' ],
117                                 'gui'   => [ 0xff8888, 0xffffff ],
118                                 'flags' => [ 'bright', 'underline' ] },
119         'search' => {           'text'  => [ 'black', 'green' ],
120                                 'gui'   => [ 0x000000, 0x00cc77 ] }
123 /* hash of specially coloured words */
124 mp.word_color = {};
126 mp.keycodes = {};
128 mp.actions = {};
130 mp.actdesc = {};
132 mp.alert_log = [];
134 /** the menu **/
136 mp.menu = [
137         [
138                 LL("&File"),
139                 [ 'new', 'open', 'save', 'save_as', 'close', 'revert',
140                         'open_under_cursor',
141                         '-', 'hex_view',
142                         '-', 'set_password',
143                         '-', 'open_config_file', 'open_templates_file',
144                         '-', 'sync',
145                         '-', 'save_session', 'load_session',
146                         '-', 'exit'
147                 ]
148         ],
149         [
150                 LL("&Edit"),
151                 [ 'undo', 'redo', '-',
152                         'cut_mark', 'copy_mark', 'paste_mark', 'delete_line', '-',
153                         'mark', 'mark_vertical', 'unmark', '-',
154                         'insert_template', '-',
155                         'word_wrap_paragraph', 'join_paragraph', '-',
156                         'exec_command', '-',
157                         'eval', 'eval_doc'
158                 ]
159         ],
160         [
161                 LL("&Search"),
162                 [ 'seek', 'seek_next', 'seek_prev', 'replace', '-',
163                         'complete', '-',
164                         'seek_misspelled', 'ignore_last_misspell', '-',
165                         'seek_repeated_word', '-',
166                         'find_tag', 'complete_symbol', '-', 'grep'
167                 ]
168         ],
169         [
170                 LL("&Go to"),
171                 [ 'next', 'prev',
172                         'move_bof', 'move_eof', 'move_bol', 'move_eol',
173                         'goto', 'move_word_right', 'move_word_left',
174                         'section_list',
175                         '-', 'document_list'
176                 ]
177         ],
178         [
179                 LL("&Options"),
180                 [ 'record_macro', 'play_macro', '-',
181                         'encoding', 'tab_options', 'line_options', 'repeated_words_options',
182                         'toggle_spellcheck', '-',
183                         'word_count', '-',
184                         'zoom_in', 'zoom_out', '-',
185                         'about'
186                 ]
187         ]
190 mp.actions_by_menu_label = {};
192 /** code **/
195  * mp.redraw - Triggers a redraw on the next cycle.
197  * Triggers a full document redraw in the next cycle.
198  */
199 sub mp.redraw()
201         /* just increment the redraw trigger */
202         mp.redraw_counter++;
206 sub mp.active()
207 /* returns the active document */
209         local d;
211         /* empty document list? create a new, empty one */
212         if (size(mp.docs) == 0)
213                 mp.new();
215         /* get active document */
216         d = mp.docs[mp.active_i];
218         /* if it's read only but has modifications, revert them */
219         if (d.read_only && size(d.undo)) {
220                 while (size(d.undo))
221                         mp.undo(d);
223                 mp.message = {
224                         'timeout'       => time() + 2,
225                         'string'        => '*' ~ L("Read-only document") ~ '*'
226                 };
227         }
229         return d;
233 sub mp.process_action(a)
234 /* processes an action */
236         local f, d;
238         d = mp.active();
240         if ((f = mp.actions[a]) != NULL)
241                 f(d);
242         else {
243                 mp.message = {
244                         'timeout'       => time() + 2,
245                         'string'        => sprintf(L("Unknown action '%s'"), a)
246                 };
247         }
251 sub mp.process_event(k)
252 /* processes a key event */
254         local d, a;
256         /* empty document list? do nothing */
257         if (size(mp.docs) == 0)
258                 return;
260         d = mp.active();
262         if (mp.keycodes_t == NULL)
263                 mp.keycodes_t = mp.keycodes;
265         /* get the action asociated to the keycode */
266         if ((a = mp.keycodes_t[k]) != NULL) {
268                 /* if it's a hash, store for further testing */
269                 if (is_hash(a))
270                         mp.keycodes_t = a;
271                 else {
272                         /* if it's executable, run it */
273                         if (is_exec(a))
274                                 a(d);
275                         else
276                         /* if it's an array, process it sequentially */
277                         if (is_array(a))
278                                 foreach(l, a)
279                                         mp.process_action(l);
280                         else
281                                 mp.process_action(a);
283                         mp.keycodes_t = NULL;
284                 }
285         }
286         else {
287                 mp.insert_keystroke(d, k);
288                 mp.keycodes_t = NULL;
289         }
291         mp.shift_pressed = NULL;
295 sub mp.build_status_line()
296 /* returns the string to be drawn in the status line */
298         if (mp.message) {
299                 /* is the message still active? */
300                 if (mp.message.timeout > time())
301                         return mp.message.string;
303                 mp.message = NULL;
304         }
306         return sregex("/%./g", mp.config.status_format, mp.status_line_info);
310 sub mp.backslash_codes(s, d)
311 /* encodes (d == 0) or decodes (d == 1) backslash codes
312    (like \n, \r, etc.) */
314         d &&    sregex("/[\r\n\t]/g", s, { "\r" => '\r', "\n" => '\n', "\t" => '\t'}) ||
315                 sregex("/\\\\[rnt]/g", s, { '\r' => "\r", '\n' => "\n", '\t' => "\t"});
319 sub mp.long_op(func, a1, a2, a3, a4)
320 /* executes a potentially long function */
322         local r;
324         mp.busy(1);
325         r = func(a1, a2, a3, a4);
326         mp.busy(0);
328         return r;
332 sub mp.get_history(key)
333 /* returns a history for the specified key */
335         if (key == NULL)
336                 return NULL;
337         if (mp.history == NULL)
338                 mp.history = {};
339         if (mp.history[key] == NULL)
340                 mp.history[key] = [];
342         return mp.history[key];
346 sub mp.menu_label(action)
347 /* returns a label for the menu for an action */
349         local l;
351         /* if action is '-', it's a menu separator */
352         if (action eq '-')
353                 return NULL;
355         /* no recognized action? return */
356         if (!exists(mp.actions, action))
357                 return action ~ "?";
359         /* get the translated description */
360         l = L(mp.actdesc[action]) || action;
362         /* is there a keycode that generates this action? */
363         foreach (i, sort(keys(mp.keycodes))) {
364                 if (mp.keycodes[i] eq action) {
365                         /* avoid mouse and window pseudo-keycodes */
366                         if (!regex("/window/", i) && !regex("/mouse/", i)) {
367                                 l = l ~ ' [' ~ i ~ ']';
368                                 break;
369                         }
370                 }
371         }
373         mp.actions_by_menu_label[l] = action;
375         return l;
379 sub mp.trim_with_ellipsis(str, max)
380 /* trims the string to the last max characters, adding ellipsis if done */
382         local v = regex('/.{' ~ max ~ '}$/', str);
383         return v && '...' ~ v || str;
387 sub mp.get_doc_names(max)
388 /* returns an array with the trimmed names of the documents */
390         map(sub(e) {
391                 (e.txt.mod && '* ' || '') ~ mp.trim_with_ellipsis(e.name, (max || 24));
392         }, mp.docs);
396 sub mp.usage()
397 /* set mp.exit_message with an usage message (--help) */
399         mp.exit_message = 
400         sprintf(L(
401                 "Minimum Profit %s - Programmer Text Editor\n"\
402                 "Copyright (C) Angel Ortega <angel@triptico.com>\n"\
403                 "This software is covered by the GPL license. NO WARRANTY.\n"\
404                 "\n"\
405                 "Usage: mp-5 [options] [files...]\n"\
406                 "\n"\
407                 "Options:\n"\
408                 "\n"\
409                 " -t {tag}           Edits the file where tag is defined\n"\
410                 " -e {mpsl_code}     Executes MPSL code\n"\
411                 " -f {mpsl_script}   Executes MPSL script file\n"\
412                 " -d {directory}     Set current directory\n"\
413                 " +NNN               Moves to line number NNN of last file\n"\
414                 "\n"\
415                 "Homepage: http://www.triptico.com/software/mp.html\n"\
416                 "Mailing list: mp-subscribe@lists.triptico.com\n"
417         ), mp.VERSION);
421 sub mp.process_cmdline()
422 /* process the command line arguments (ARGV) */
424         local o, line;
426         mp.load_tags();
428         /* skip ARGV[0] */
429         shift(ARGV);
431         while (o = shift(ARGV)) {
432                 if (o eq '-h' || o eq '--help') {
433                         mp.usage();
434                         mp.exit();
435                         return;
436                 }
437                 else
438                 if (o eq '-e') {
439                         /* execute code */
440                         local c = shift(ARGV);
442                         if (! regex('/;\s*$/', c))
443                                 c = c ~ ';';
445                         eval(c);
446                 }
447                 else
448                 if (o eq '-f') {
449                         /* execute script */
450                         local s = shift(ARGV);
452                         if (stat(s) == NULL)
453                                 ERROR = sprintf(L("Cannot open '%s'"), s);
454                         else {
455                                 mp.open(s);
456                                 eval(join("\n", mp.active.txt.lines));
457                                 mp.close();
458                         }
459                 }
460                 else
461                 if (o eq '-d')
462                         chdir(shift(ARGV));
463                 else
464                 if (o eq '-t')
465                         mp.open_tag(shift(ARGV));
466                 else
467                 if (o eq '-x') {
468                         local s = shift(ARGV);
470                         if (mp.hex_view(s) == NULL)
471                                 ERROR = sprintf(L("Cannot open '%s'"), s);
472                 }
473                 else
474                 if (regex('/^\+/', o)) {
475                         /* move to line */
476                         line = o - 1;
477                 }
478                 else
479                         mp.open(o);
480         }
482         if (ERROR) {
483                 mp.exit_message = ERROR ~ "\n";
484                 ERROR = NULL;
485                 mp.exit();
486                 return;
487         }
489         /* if no files are loaded, try a session */
490         if (size(mp.docs) == 0 && mp.config.auto_sessions) {
491                 mp.load_session();
492         }
493         else {
494                 /* set the first as the active one */
495                 mp.active_i = 0;
496         }
498         mp.active();
500         /* if there is a line defined, move there */
501         if (line != NULL)
502                 mp.set_y(mp.active(), line);
506 sub mp.load_profile()
507 /* loads ~/.mp.mpsl */
509         /* if /etc/mp.mpsl exists, execute it */
510         if (stat('/etc/mp.mpsl') != NULL) {
511                 eval( sub {
512                         local INC = [ '/etc' ];
513                         load('mp.mpsl');
514                 });
515         }
517         /* if ~/.mp.mpsl exists, execute it */
518         if (ERROR == NULL && stat(HOMEDIR ~ '.mp.mpsl') != NULL) {
519                 eval( sub {
520                         local INC = [ HOMEDIR ];
521                         load(".mp.mpsl");
522                 });
523         }
525         /* errors? show in a message */
526         if (ERROR != NULL) {
527                 mp.message = {
528                         'timeout'       => time() + 20,
529                         'string'        => ERROR
530                 };
532                 ERROR = NULL;
533         }
537 sub mp.setup_language()
538 /* sets up the language */
540         /* set gettext() domain */
541         gettext_domain('minimum-profit', APPDIR ~ 'locale');
543         /* test if gettext() can do a basic translation */
544         if (gettext('&File') eq '&File' && ENV.LANG) {
545                 /* no; try alternatives using the LANG variable */
546                 local v = [ sregex('!/!g', ENV.LANG) ]; /* es_ES.UTF-8 */
547                 push(v, shift(split('.', v[-1])));      /* es_ES */
548                 push(v, shift(split('_', v[-1])));      /* es */
550                 foreach (l, v) {
551                         eval('load("lang/' ~ l ~ '.mpsl");');
553                         if (ERROR == NULL)
554                                 break;
555                 }
557                 ERROR = NULL;
558         }
562 sub mp.normalize_version(vs)
563 /* converts a version string to something usable with cmp() */
565         map(sub(e) { sprintf("%03d", e); },
566                 split('.',
567                         sregex('/-.+$/', vs)));
571 sub mp.assert_version(found, minimal, package)
572 /* asserts that 'found' version of 'package' is at least 'minimal',
573    or generate a warning otherwise */
575         if (cmp(mp.normalize_version(found),
576                 mp.normalize_version(minimal)) < 0) {
577                 mp.alert(sprintf(L("WARNING: %s version found is %s, but %s is needed"),
578                                 package, found, minimal));
579         }
583 sub mp.test_versions()
584 /* tests component versions */
586         local mpdm = MPDM();
588         mp.assert_version(mpdm.version, '1.0.7', 'MPDM');
589         mp.assert_version(MPSL.VERSION, '1.0.7', 'MPSL');
593 /** MAIN **/
595 load("mp_drv.mpsl");
596 load("mp_move.mpsl");
597 load("mp_edit.mpsl");
598 load("mp_file.mpsl");
599 load("mp_clipboard.mpsl");
600 load("mp_search.mpsl");
601 load("mp_tags.mpsl");
602 load("mp_syntax.mpsl");
603 load("mp_macro.mpsl");
604 load("mp_templates.mpsl");
605 load("mp_spell.mpsl");
606 load("mp_misc.mpsl");
607 load("mp_crypt.mpsl");
608 load("mp_keyseq.mpsl");
609 load("mp_session.mpsl");
610 load("mp_build.mpsl");
611 load("mp_writing.mpsl");
613 mp.load_profile();
614 mp.setup_language();
615 mp.drv.startup();
616 mp.process_cmdline();
617 mp.test_versions();
618 mp.drv.main_loop();
619 mp.drv.shutdown();