Set mp.config.maximize to 0.
[mp-5.x.git] / mp_core.mpsl
blobddd574d633b4f75e6ac7a17e4643abd9d99537ca
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 %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         '%%'    =>      '%'
72 /* a regex for selecting words */
73 mp.word_regex = "/[[:alnum:]_]+/i";
75 /* if it does not work (i.e. not GNU regex), fall back */
76 if (regex(mp.word_regex, "test") == NULL)
77         mp.word_regex = '/[A-Z_][A-Z0-9_]*/i';
79 /* document list */
80 mp.docs = [];
81 mp.active_i = 0;
83 /* allowed color names (order matters, match the Unix curses one) */
84 mp.color_names = [ "default", "black", "red", "green",
85         "yellow", "blue", "magenta", "cyan", "white" ];
87 /* color definitions */
88 mp.colors = {
89         'normal' => {           'text'  => [ 'default', 'default' ],
90                                 'gui'   => [ 0x000000, 0xffffff ] },
91         'cursor' => {           'text'  => [ 'default', 'default' ],
92                                 'gui'   => [ 0x000000, 0xffffff ],
93                                 'flags' => [ 'reverse' ] },
94         'selection' => {        'text'  => [ 'red', 'default' ],
95                                 'gui'   => [ 0xff0000, 0xffffff ],
96                                 'flags' => [ 'reverse'] },
97         'comments' => {         'text'  => [ 'green', 'default' ],
98                                 'gui'   => [ 0x00cc77, 0xffffff ] },
99         'documentation' => {    'text'  => [ 'cyan', 'default' ],
100                                 'gui'   => [ 0x8888ff, 0xffffff ] },
101         'quotes' => {           'text'  => [ 'blue', 'default' ],
102                                 'gui'   => [ 0x0000ff, 0xffffff ],
103                                 'flags' => [ 'bright' ] },
104         'matching' => {         'text'  => [ 'black', 'cyan' ],
105                                 'gui'   => [ 0x000000, 0xffff00 ] },
106         'word1' => {            'text'  => [ 'green', 'default' ],
107                                 'gui'   => [ 0x00aa00, 0xffffff ],
108                                 'flags' => [ 'bright' ] },
109         'word2' => {            'text'  => [ 'red', 'default' ],
110                                 'gui'   => [ 0xff6666, 0xffffff ],
111                                 'flags' => [ 'bright' ] },
112         'tag' => {              'text'  => [ 'cyan', 'default' ],
113                                 'gui'   => [ 0x8888ff, 0xffffff ],
114                                 'flags' => [ 'underline' ] },
115         'spell' => {            'text'  => [ 'red', 'default' ],
116                                 'gui'   => [ 0xff8888, 0xffffff ],
117                                 'flags' => [ 'bright', 'underline' ] },
118         'search' => {           'text'  => [ 'black', 'green' ],
119                                 'gui'   => [ 0x000000, 0x00cc77 ] }
122 /* hash of specially coloured words */
123 mp.word_color = {};
125 mp.keycodes = {};
127 mp.actions = {};
129 mp.actdesc = {};
131 mp.alert_log = [];
133 /** the menu **/
135 mp.menu = [
136         [
137                 LL("&File"),
138                 [ 'new', 'open', 'save', 'save_as', 'close', 'revert',
139                         'open_under_cursor',
140                         '-', 'set_password',
141                         '-', 'open_config_file', 'open_templates_file',
142                         '-', 'sync',
143                         '-', 'save_session', 'load_session',
144                         '-', 'exit'
145                 ]
146         ],
147         [
148                 LL("&Edit"),
149                 [ 'undo', 'redo', '-',
150                         'cut_mark', 'copy_mark', 'paste_mark', 'delete_line', '-',
151                         'mark', 'mark_vertical', 'unmark', '-',
152                         'insert_template', '-',
153                         'word_wrap_paragraph', 'join_paragraph', '-',
154                         'exec_command', '-',
155                         'eval', 'eval_doc'
156                 ]
157         ],
158         [
159                 LL("&Search"),
160                 [ 'seek', 'seek_next', 'seek_prev', 'replace', '-',
161                         'complete', '-',
162                         'seek_misspelled', 'ignore_last_misspell', '-',
163                         'seek_repeated_word', '-',
164                         'find_tag', 'complete_symbol', '-', 'grep'
165                 ]
166         ],
167         [
168                 LL("&Go to"),
169                 [ 'next', 'prev',
170                         'move_bof', 'move_eof', 'move_bol', 'move_eol',
171                         'goto', 'move_word_right', 'move_word_left',
172                         'section_list',
173                         '-', 'document_list'
174                 ]
175         ],
176         [
177                 LL("&Options"),
178                 [ 'record_macro', 'play_macro', '-',
179                         'encoding', 'tab_options', 'line_options', 'repeated_words_options',
180                         'toggle_spellcheck', '-',
181                         'word_count', '-',
182                         'zoom_in', 'zoom_out', '-',
183                         'about'
184                 ]
185         ]
188 mp.actions_by_menu_label = {};
190 /** code **/
193  * mp.redraw - Triggers a redraw on the next cycle.
195  * Triggers a full document redraw in the next cycle.
196  */
197 sub mp.redraw()
199         /* just increment the redraw trigger */
200         mp.redraw_counter++;
204 sub mp.active()
205 /* returns the active document */
207         local d;
209         /* empty document list? create a new, empty one */
210         if (size(mp.docs) == 0)
211                 mp.new();
213         /* get active document */
214         d = mp.docs[mp.active_i];
216         /* if it's read only but has modifications, revert them */
217         if (d.read_only && size(d.undo)) {
218                 while (size(d.undo))
219                         mp.undo(d);
221                 mp.message = {
222                         'timeout'       => time() + 2,
223                         'string'        => '*' ~ L("Read-only document") ~ '*'
224                 };
225         }
227         return d;
231 sub mp.process_action(a)
232 /* processes an action */
234         local f, d;
236         d = mp.active();
238         if ((f = mp.actions[a]) != NULL)
239                 f(d);
240         else {
241                 mp.message = {
242                         'timeout'       => time() + 2,
243                         'string'        => sprintf(L("Unknown action '%s'"), a)
244                 };
245         }
249 sub mp.process_event(k)
250 /* processes a key event */
252         local d, a;
254         /* empty document list? do nothing */
255         if (size(mp.docs) == 0)
256                 return;
258         d = mp.active();
260         if (mp.keycodes_t == NULL)
261                 mp.keycodes_t = mp.keycodes;
263         /* get the action asociated to the keycode */
264         if ((a = mp.keycodes_t[k]) != NULL) {
266                 /* if it's a hash, store for further testing */
267                 if (is_hash(a))
268                         mp.keycodes_t = a;
269                 else {
270                         /* if it's executable, run it */
271                         if (is_exec(a))
272                                 a(d);
273                         else
274                         /* if it's an array, process it sequentially */
275                         if (is_array(a))
276                                 foreach(l, a)
277                                         mp.process_action(l);
278                         else
279                                 mp.process_action(a);
281                         mp.keycodes_t = NULL;
282                 }
283         }
284         else {
285                 mp.insert_keystroke(d, k);
286                 mp.keycodes_t = NULL;
287         }
289         mp.shift_pressed = NULL;
293 sub mp.build_status_line()
294 /* returns the string to be drawn in the status line */
296         if (mp.message) {
297                 /* is the message still active? */
298                 if (mp.message.timeout > time())
299                         return mp.message.string;
301                 mp.message = NULL;
302         }
304         return sregex("/%./g", mp.config.status_format, mp.status_line_info);
308 sub mp.backslash_codes(s, d)
309 /* encodes (d == 0) or decodes (d == 1) backslash codes
310    (like \n, \r, etc.) */
312         d &&    sregex("/[\r\n\t]/g", s, { "\r" => '\r', "\n" => '\n', "\t" => '\t'}) ||
313                 sregex("/\\\\[rnt]/g", s, { '\r' => "\r", '\n' => "\n", '\t' => "\t"});
317 sub mp.long_op(func, a1, a2, a3, a4)
318 /* executes a potentially long function */
320         local r;
322         mp.busy(1);
323         r = func(a1, a2, a3, a4);
324         mp.busy(0);
326         return r;
330 sub mp.get_history(key)
331 /* returns a history for the specified key */
333         if (key == NULL)
334                 return NULL;
335         if (mp.history == NULL)
336                 mp.history = {};
337         if (mp.history[key] == NULL)
338                 mp.history[key] = [];
340         return mp.history[key];
344 sub mp.menu_label(action)
345 /* returns a label for the menu for an action */
347         local l;
349         /* if action is '-', it's a menu separator */
350         if (action eq '-')
351                 return NULL;
353         /* no recognized action? return */
354         if (!exists(mp.actions, action))
355                 return action ~ "?";
357         /* get the translated description */
358         l = L(mp.actdesc[action]) || action;
360         /* is there a keycode that generates this action? */
361         foreach (i, sort(keys(mp.keycodes))) {
362                 if (mp.keycodes[i] eq action) {
363                         /* avoid mouse and window pseudo-keycodes */
364                         if (!regex("/window/", i) && !regex("/mouse/", i)) {
365                                 l = l ~ ' [' ~ i ~ ']';
366                                 break;
367                         }
368                 }
369         }
371         mp.actions_by_menu_label[l] = action;
373         return l;
377 sub mp.trim_with_ellipsis(str, max)
378 /* trims the string to the last max characters, adding ellipsis if done */
380         local v = regex('/.{' ~ max ~ '}$/', str);
381         return v && '...' ~ v || str;
385 sub mp.get_doc_names(max)
386 /* returns an array with the trimmed names of the documents */
388         map(sub(e) {
389                 (e.txt.mod && '* ' || '') ~ mp.trim_with_ellipsis(e.name, (max || 24));
390         }, mp.docs);
394 sub mp.usage()
395 /* set mp.exit_message with an usage message (--help) */
397         mp.exit_message = 
398         sprintf(L(
399                 "Minimum Profit %s - Programmer Text Editor\n"\
400                 "Copyright (C) Angel Ortega <angel@triptico.com>\n"\
401                 "This software is covered by the GPL license. NO WARRANTY.\n"\
402                 "\n"\
403                 "Usage: mp-5 [options] [files...]\n"\
404                 "\n"\
405                 "Options:\n"\
406                 "\n"\
407                 " -t {tag}           Edits the file where tag is defined\n"\
408                 " -e {mpsl_code}     Executes MPSL code\n"\
409                 " -f {mpsl_script}   Executes MPSL script file\n"\
410                 " -d {directory}     Set current directory\n"\
411                 " +NNN               Moves to line number NNN of last file\n"\
412                 "\n"\
413                 "Homepage: http://www.triptico.com/software/mp.html\n"\
414                 "Mailing list: mp-subscribe@lists.triptico.com\n"
415         ), mp.VERSION);
419 sub mp.process_cmdline()
420 /* process the command line arguments (ARGV) */
422         local o, line;
424         mp.load_tags();
426         /* skip ARGV[0] */
427         shift(ARGV);
429         while (o = shift(ARGV)) {
430                 if (o eq '-h' || o eq '--help') {
431                         mp.usage();
432                         mp.exit();
433                         return;
434                 }
435                 else
436                 if (o eq '-e') {
437                         /* execute code */
438                         local c = shift(ARGV);
440                         if (! regex('/;\s*$/', c))
441                                 c = c ~ ';';
443                         eval(c);
444                 }
445                 else
446                 if (o eq '-f') {
447                         /* execute script */
448                         local s = shift(ARGV);
450                         if (stat(s) == NULL)
451                                 ERROR = sprintf(L("Cannot open '%s'"), s);
452                         else {
453                                 mp.open(s);
454                                 eval(join("\n", mp.active.txt.lines));
455                                 mp.close();
456                         }
457                 }
458                 else
459                 if (o eq '-d')
460                         chdir(shift(ARGV));
461                 else
462                 if (o eq '-t')
463                         mp.open_tag(shift(ARGV));
464                 else
465                 if (regex('/^\+/', o)) {
466                         /* move to line */
467                         line = o - 1;
468                 }
469                 else
470                         mp.open(o);
471         }
473         if (ERROR) {
474                 mp.exit_message = ERROR ~ "\n";
475                 ERROR = NULL;
476                 mp.exit();
477                 return;
478         }
480         /* if no files are loaded, try a session */
481         if (size(mp.docs) == 0 && mp.config.auto_sessions) {
482                 mp.load_session();
483         }
484         else {
485                 /* set the first as the active one */
486                 mp.active_i = 0;
487         }
489         mp.active();
491         /* if there is a line defined, move there */
492         if (line != NULL)
493                 mp.set_y(mp.active(), line);
497 sub mp.load_profile()
498 /* loads ~/.mp.mpsl */
500         /* if /etc/mp.mpsl exists, execute it */
501         if (stat('/etc/mp.mpsl') != NULL) {
502                 eval( sub {
503                         local INC = [ '/etc' ];
504                         load('mp.mpsl');
505                 });
506         }
508         /* if ~/.mp.mpsl exists, execute it */
509         if (ERROR == NULL && stat(HOMEDIR ~ '.mp.mpsl') != NULL) {
510                 eval( sub {
511                         local INC = [ HOMEDIR ];
512                         load(".mp.mpsl");
513                 });
514         }
516         /* errors? show in a message */
517         if (ERROR != NULL) {
518                 mp.message = {
519                         'timeout'       => time() + 20,
520                         'string'        => ERROR
521                 };
523                 ERROR = NULL;
524         }
528 sub mp.setup_language()
529 /* sets up the language */
531         /* set gettext() domain */
532         gettext_domain('minimum-profit', APPDIR ~ 'locale');
534         /* test if gettext() can do a basic translation */
535         if (gettext('&File') eq '&File' && ENV.LANG) {
536                 /* no; try alternatives using the LANG variable */
537                 local v = [ sregex('!/!g', ENV.LANG) ]; /* es_ES.UTF-8 */
538                 push(v, shift(split('.', v[-1])));      /* es_ES */
539                 push(v, shift(split('_', v[-1])));      /* es */
541                 foreach (l, v) {
542                         eval('load("lang/' ~ l ~ '.mpsl");');
544                         if (ERROR == NULL)
545                                 break;
546                 }
548                 ERROR = NULL;
549         }
553 sub mp.normalize_version(vs)
554 /* converts a version string to something usable with cmp() */
556         map(sub(e) { sprintf("%03d", e); },
557                 split('.',
558                         sregex('/-.+$/', vs)));
562 sub mp.assert_version(found, minimal, package)
563 /* asserts that 'found' version of 'package' is at least 'minimal',
564    or generate a warning otherwise */
566         if (cmp(mp.normalize_version(found),
567                 mp.normalize_version(minimal)) < 0) {
568                 mp.alert(sprintf(L("WARNING: %s version found is %s, but %s is needed"),
569                                 package, found, minimal));
570         }
574 sub mp.test_versions()
575 /* tests component versions */
577         local mpdm = MPDM();
579         mp.assert_version(mpdm.version, '1.0.7', 'MPDM');
580         mp.assert_version(MPSL.VERSION, '1.0.7', 'MPSL');
584 /** MAIN **/
586 load("mp_drv.mpsl");
587 load("mp_move.mpsl");
588 load("mp_edit.mpsl");
589 load("mp_file.mpsl");
590 load("mp_clipboard.mpsl");
591 load("mp_search.mpsl");
592 load("mp_tags.mpsl");
593 load("mp_syntax.mpsl");
594 load("mp_macro.mpsl");
595 load("mp_templates.mpsl");
596 load("mp_spell.mpsl");
597 load("mp_misc.mpsl");
598 load("mp_crypt.mpsl");
599 load("mp_keyseq.mpsl");
600 load("mp_session.mpsl");
601 load("mp_build.mpsl");
602 load("mp_writing.mpsl");
604 mp.load_profile();
605 mp.setup_language();
606 mp.drv.startup();
607 mp.process_cmdline();
608 mp.test_versions();
609 mp.drv.main_loop();
610 mp.drv.shutdown();