Added 'repeated_words_options' action to the menu.
[mp-5.x.git] / mp_core.mpsl
blobf39ecfcadd81c76556c19b1578c076df0c66ce1c
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;
48 /* default end of line, system dependent */
49 if (mp.drv.id eq 'win32')
50         mp.config.eol = "\r\n";
51 else
52         mp.config.eol = "\n";
54 /* status line */
55 mp.config.status_format = "%m%n %x,%y [%l] %R%O %s %t";
56 mp.status_line_info = {
57         '%V'    =>      mp.VERSION,
58         '%m'    =>      sub { mp.active.txt.mod && '*' || ''; },
59         '%x'    =>      sub { mp.active.txt.x + 1; },
60         '%y'    =>      sub { mp.active.txt.y + 1; },
61         '%l'    =>      sub { size(mp.active.txt.lines); },
62         '%R'    =>      sub { mp.macro.process_event && 'R' || ''; },
63         '%O'    =>      '',
64         '%s'    =>      sub { mp.active.syntax.name; },
65         '%t'    =>      sub { mp.tags[mp.get_word(mp.active())].label; },
66         '%n'    =>      sub { mp.active.name; },
67         '%w'    =>      sub { mp.word_count(mp.active()); },
68         '%%'    =>      '%'
71 /* a regex for selection words */
72 mp.word_regex = '/[A-Z_][A-Z0-9_]*/i';
74 /* document list */
75 mp.docs = [];
76 mp.active_i = 0;
78 /* allowed color names (order matters, match the Unix curses one) */
79 mp.color_names = [ "default", "black", "red", "green",
80         "yellow", "blue", "magenta", "cyan", "white" ];
82 /* color definitions */
83 mp.colors = {
84         'normal' => {           'text'  => [ 'default', 'default' ],
85                                 'gui'   => [ 0x000000, 0xffffff ] },
86         'cursor' => {           'text'  => [ 'default', 'default' ],
87                                 'gui'   => [ 0x000000, 0xffffff ],
88                                 'flags' => [ 'reverse' ] },
89         'selection' => {        'text'  => [ 'red', 'default' ],
90                                 'gui'   => [ 0xff0000, 0xffffff ],
91                                 'flags' => [ 'reverse'] },
92         'comments' => {         'text'  => [ 'green', 'default' ],
93                                 'gui'   => [ 0x00cc77, 0xffffff ] },
94         'documentation' => {    'text'  => [ 'cyan', 'default' ],
95                                 'gui'   => [ 0x8888ff, 0xffffff ] },
96         'quotes' => {           'text'  => [ 'blue', 'default' ],
97                                 'gui'   => [ 0x0000ff, 0xffffff ],
98                                 'flags' => [ 'bright' ] },
99         'matching' => {         'text'  => [ 'black', 'cyan' ],
100                                 'gui'   => [ 0x000000, 0xffff00 ] },
101         'word1' => {            'text'  => [ 'green', 'default' ],
102                                 'gui'   => [ 0x00aa00, 0xffffff ],
103                                 'flags' => [ 'bright' ] },
104         'word2' => {            'text'  => [ 'red', 'default' ],
105                                 'gui'   => [ 0xff6666, 0xffffff ],
106                                 'flags' => [ 'bright' ] },
107         'tag' => {              'text'  => [ 'cyan', 'default' ],
108                                 'gui'   => [ 0x8888ff, 0xffffff ],
109                                 'flags' => [ 'underline' ] },
110         'spell' => {            'text'  => [ 'red', 'default' ],
111                                 'gui'   => [ 0xff8888, 0xffffff ],
112                                 'flags' => [ 'bright', 'underline' ] },
113         'search' => {           'text'  => [ 'black', 'green' ],
114                                 'gui'   => [ 0x000000, 0x00cc77 ] }
117 /* hash of specially coloured words */
118 mp.word_color = {};
120 mp.keycodes = {};
122 mp.actions = {};
124 mp.actdesc = {};
126 mp.alert_log = [];
128 /** the menu **/
130 mp.menu = [
131         [
132                 LL("&File"),
133                 [ 'new', 'open', 'save', 'save_as', 'close', 'revert',
134                         'open_under_cursor',
135                         '-', 'set_password',
136                         '-', 'open_config_file', 'open_templates_file',
137                         '-', 'sync',
138                         '-', 'save_session', 'load_session',
139                         '-', 'exit'
140                 ]
141         ],
142         [
143                 LL("&Edit"),
144                 [ 'undo', 'redo', '-',
145                         'cut_mark', 'copy_mark', 'paste_mark', 'delete_line', '-',
146                         'mark', 'mark_vertical', 'unmark', '-',
147                         'insert_template', '-',
148                         'word_wrap_paragraph', 'join_paragraph', '-',
149                         'exec_command', '-',
150                         'eval', 'eval_doc'
151                 ]
152         ],
153         [
154                 LL("&Search"),
155                 [ 'seek', 'seek_next', 'seek_prev', 'replace', '-',
156                         'complete', '-',
157                         'seek_misspelled', 'ignore_last_misspell', '-',
158                         'seek_repeated_word', '-',
159                         'find_tag', 'complete_symbol', '-', 'grep'
160                 ]
161         ],
162         [
163                 LL("&Go to"),
164                 [ 'next', 'prev',
165                         'move_bof', 'move_eof', 'move_bol', 'move_eol',
166                         'goto', 'move_word_right', 'move_word_left',
167                         'section_list',
168                         '-', 'document_list'
169                 ]
170         ],
171         [
172                 LL("&Options"),
173                 [ 'record_macro', 'play_macro', '-',
174                         'encoding', 'tab_options', 'line_options', 'repeated_words_options',
175                         'toggle_spellcheck', '-',
176                         'word_count', '-',
177                         'zoom_in', 'zoom_out', '-',
178                         'about'
179                 ]
180         ]
183 mp.actions_by_menu_label = {};
185 /** code **/
188  * mp.redraw - Triggers a redraw on the next cycle.
190  * Triggers a full document redraw in the next cycle.
191  */
192 sub mp.redraw()
194         /* just increment the redraw trigger */
195         mp.redraw_counter++;
199 sub mp.active()
200 /* returns the active document */
202         local d;
204         /* empty document list? create a new, empty one */
205         if (size(mp.docs) == 0)
206                 mp.new();
208         /* get active document */
209         d = mp.docs[mp.active_i];
211         /* if it's read only but has modifications, revert them */
212         if (d.read_only && size(d.undo)) {
213                 while (size(d.undo))
214                         mp.undo(d);
216                 mp.message = {
217                         'timeout'       => time() + 2,
218                         'string'        => '*' ~ L("Read-only document") ~ '*'
219                 };
220         }
222         return d;
226 sub mp.process_action(a)
227 /* processes an action */
229         local f, d;
231         d = mp.active();
233         if ((f = mp.actions[a]) != NULL)
234                 f(d);
235         else {
236                 mp.message = {
237                         'timeout'       => time() + 2,
238                         'string'        => sprintf(L("Unknown action '%s'"), a)
239                 };
240         }
244 sub mp.process_event(k)
245 /* processes a key event */
247         local d, a;
249         /* empty document list? do nothing */
250         if (size(mp.docs) == 0)
251                 return;
253         d = mp.active();
255         if (mp.keycodes_t == NULL)
256                 mp.keycodes_t = mp.keycodes;
258         /* get the action asociated to the keycode */
259         if ((a = mp.keycodes_t[k]) != NULL) {
261                 /* if it's a hash, store for further testing */
262                 if (is_hash(a))
263                         mp.keycodes_t = a;
264                 else {
265                         /* if it's executable, run it */
266                         if (is_exec(a))
267                                 a(d);
268                         else
269                         /* if it's an array, process it sequentially */
270                         if (is_array(a))
271                                 foreach(l, a)
272                                         mp.process_action(l);
273                         else
274                                 mp.process_action(a);
276                         mp.keycodes_t = NULL;
277                 }
278         }
279         else {
280                 mp.insert_keystroke(d, k);
281                 mp.keycodes_t = NULL;
282         }
284         mp.shift_pressed = NULL;
288 sub mp.build_status_line()
289 /* returns the string to be drawn in the status line */
291         if (mp.message) {
292                 /* is the message still active? */
293                 if (mp.message.timeout > time())
294                         return mp.message.string;
296                 mp.message = NULL;
297         }
299         return sregex("/%./g", mp.config.status_format, mp.status_line_info);
303 sub mp.backslash_codes(s, d)
304 /* encodes (d == 0) or decodes (d == 1) backslash codes
305    (like \n, \r, etc.) */
307         d &&    sregex("/[\r\n\t]/g", s, { "\r" => '\r', "\n" => '\n', "\t" => '\t'}) ||
308                 sregex("/\\\\[rnt]/g", s, { '\r' => "\r", '\n' => "\n", '\t' => "\t"});
312 sub mp.long_op(func, a1, a2, a3, a4)
313 /* executes a potentially long function */
315         local r;
317         mp.busy(1);
318         r = func(a1, a2, a3, a4);
319         mp.busy(0);
321         return r;
325 sub mp.get_history(key)
326 /* returns a history for the specified key */
328         if (key == NULL)
329                 return NULL;
330         if (mp.history == NULL)
331                 mp.history = {};
332         if (mp.history[key] == NULL)
333                 mp.history[key] = [];
335         return mp.history[key];
339 sub mp.menu_label(action)
340 /* returns a label for the menu for an action */
342         local l;
344         /* if action is '-', it's a menu separator */
345         if (action eq '-')
346                 return NULL;
348         /* no recognized action? return */
349         if (!exists(mp.actions, action))
350                 return action ~ "?";
352         /* get the translated description */
353         l = L(mp.actdesc[action]) || action;
355         /* is there a keycode that generates this action? */
356         foreach (i, sort(keys(mp.keycodes))) {
357                 if (mp.keycodes[i] eq action) {
358                         /* avoid mouse and window pseudo-keycodes */
359                         if (!regex("/window/", i) && !regex("/mouse/", i)) {
360                                 l = l ~ ' [' ~ i ~ ']';
361                                 break;
362                         }
363                 }
364         }
366         mp.actions_by_menu_label[l] = action;
368         return l;
372 sub mp.trim_with_ellipsis(str, max)
373 /* trims the string to the last max characters, adding ellipsis if done */
375         local v = regex('/.{' ~ max ~ '}$/', str);
376         return v && '...' ~ v || str;
380 sub mp.get_doc_names(max)
381 /* returns an array with the trimmed names of the documents */
383         map(sub(e) {
384                 (e.txt.mod && '* ' || '') ~ mp.trim_with_ellipsis(e.name, (max || 24));
385         }, mp.docs);
389 sub mp.usage()
390 /* set mp.exit_message with an usage message (--help) */
392         mp.exit_message = 
393         sprintf(L(
394                 "Minimum Profit %s - Programmer Text Editor\n"\
395                 "Copyright (C) Angel Ortega <angel@triptico.com>\n"\
396                 "This software is covered by the GPL license. NO WARRANTY.\n"\
397                 "\n"\
398                 "Usage: mp-5 [options] [files...]\n"\
399                 "\n"\
400                 "Options:\n"\
401                 "\n"\
402                 " -t {tag}           Edits the file where tag is defined\n"\
403                 " -e {mpsl_code}     Executes MPSL code\n"\
404                 " -f {mpsl_script}   Executes MPSL script file\n"\
405                 " -d {directory}     Set current directory\n"\
406                 " +NNN               Moves to line number NNN of last file\n"\
407                 "\n"\
408                 "Homepage: http://www.triptico.com/software/mp.html\n"\
409                 "Mailing list: mp-subscribe@lists.triptico.com\n"
410         ), mp.VERSION);
414 sub mp.process_cmdline()
415 /* process the command line arguments (ARGV) */
417         local o, line;
419         mp.load_tags();
421         /* skip ARGV[0] */
422         shift(ARGV);
424         while (o = shift(ARGV)) {
425                 if (o eq '-h' || o eq '--help') {
426                         mp.usage();
427                         mp.exit();
428                         return;
429                 }
430                 else
431                 if (o eq '-e') {
432                         /* execute code */
433                         local c = shift(ARGV);
435                         if (! regex('/;\s*$/', c))
436                                 c = c ~ ';';
438                         eval(c);
439                 }
440                 else
441                 if (o eq '-f') {
442                         /* execute script */
443                         local s = shift(ARGV);
445                         if (stat(s) == NULL)
446                                 ERROR = sprintf(L("Cannot open '%s'"), s);
447                         else {
448                                 mp.open(s);
449                                 eval(join("\n", mp.active.txt.lines));
450                                 mp.close();
451                         }
452                 }
453                 else
454                 if (o eq '-d')
455                         chdir(shift(ARGV));
456                 else
457                 if (o eq '-t')
458                         mp.open_tag(shift(ARGV));
459                 else
460                 if (regex('/^\+/', o)) {
461                         /* move to line */
462                         line = o - 1;
463                 }
464                 else
465                         mp.open(o);
466         }
468         if (ERROR) {
469                 mp.exit_message = ERROR ~ "\n";
470                 ERROR = NULL;
471                 mp.exit();
472                 return;
473         }
475         /* if no files are loaded, try a session */
476         if (size(mp.docs) == 0 && mp.config.auto_sessions) {
477                 mp.load_session();
478         }
479         else {
480                 /* set the first as the active one */
481                 mp.active_i = 0;
482         }
484         mp.active();
486         /* if there is a line defined, move there */
487         if (line != NULL)
488                 mp.set_y(mp.active(), line);
492 sub mp.load_profile()
493 /* loads ~/.mp.mpsl */
495         /* if /etc/mp.mpsl exists, execute it */
496         if (stat('/etc/mp.mpsl') != NULL) {
497                 eval( sub {
498                         local INC = [ '/etc' ];
499                         load('mp.mpsl');
500                 });
501         }
503         /* if ~/.mp.mpsl exists, execute it */
504         if (ERROR == NULL && stat(HOMEDIR ~ '.mp.mpsl') != NULL) {
505                 eval( sub {
506                         local INC = [ HOMEDIR ];
507                         load(".mp.mpsl");
508                 });
509         }
511         /* errors? show in a message */
512         if (ERROR != NULL) {
513                 mp.message = {
514                         'timeout'       => time() + 20,
515                         'string'        => ERROR
516                 };
518                 ERROR = NULL;
519         }
523 sub mp.setup_language()
524 /* sets up the language */
526         /* set gettext() domain */
527         gettext_domain('minimum-profit', APPDIR ~ 'locale');
529         /* test if gettext() can do a basic translation */
530         if (gettext('&File') eq '&File' && ENV.LANG) {
531                 /* no; try alternatives using the LANG variable */
532                 local v = [ sregex('!/!g', ENV.LANG) ]; /* es_ES.UTF-8 */
533                 push(v, shift(split('.', v[-1])));      /* es_ES */
534                 push(v, shift(split('_', v[-1])));      /* es */
536                 foreach (l, v) {
537                         eval('load("lang/' ~ l ~ '.mpsl");');
539                         if (ERROR == NULL)
540                                 break;
541                 }
543                 ERROR = NULL;
544         }
548 sub mp.normalize_version(vs)
549 /* converts a version string to something usable with cmp() */
551         map(sub(e) { sprintf("%03d", e); },
552                 split('.',
553                         sregex('/-.+$/', vs)));
557 sub mp.assert_version(found, minimal, package)
558 /* asserts that 'found' version of 'package' is at least 'minimal',
559    or generate a warning otherwise */
561         if (cmp(mp.normalize_version(found),
562                 mp.normalize_version(minimal)) < 0) {
563                 mp.alert(sprintf(L("WARNING: %s version found is %s, but %s is needed"),
564                                 package, found, minimal));
565         }
569 sub mp.test_versions()
570 /* tests component versions */
572         local mpdm = MPDM();
574         mp.assert_version(mpdm.version, '1.0.7', 'MPDM');
575         mp.assert_version(MPSL.VERSION, '1.0.7', 'MPSL');
579 /** MAIN **/
581 load("mp_drv.mpsl");
582 load("mp_move.mpsl");
583 load("mp_edit.mpsl");
584 load("mp_file.mpsl");
585 load("mp_clipboard.mpsl");
586 load("mp_search.mpsl");
587 load("mp_tags.mpsl");
588 load("mp_syntax.mpsl");
589 load("mp_macro.mpsl");
590 load("mp_templates.mpsl");
591 load("mp_spell.mpsl");
592 load("mp_misc.mpsl");
593 load("mp_crypt.mpsl");
594 load("mp_keyseq.mpsl");
595 load("mp_session.mpsl");
596 load("mp_build.mpsl");
597 load("mp_writing.mpsl");
599 mp.load_profile();
600 mp.setup_language();
601 mp.drv.startup();
602 mp.process_cmdline();
603 mp.test_versions();
604 mp.drv.main_loop();
605 mp.drv.shutdown();