The detected or global encoding is stored inside each document.
[mp-5.x.git] / mp_core.mpsl
blobdf7cdc4ba2cfb692a05933d031ef4fe942cf718e
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                         '-', 'hex_view',
141                         '-', 'set_password',
142                         '-', 'open_config_file', 'open_templates_file',
143                         '-', 'sync',
144                         '-', 'save_session', 'load_session',
145                         '-', 'exit'
146                 ]
147         ],
148         [
149                 LL("&Edit"),
150                 [ 'undo', 'redo', '-',
151                         'cut_mark', 'copy_mark', 'paste_mark', 'delete_line', '-',
152                         'mark', 'mark_vertical', 'unmark', '-',
153                         'insert_template', '-',
154                         'word_wrap_paragraph', 'join_paragraph', '-',
155                         'exec_command', '-',
156                         'eval', 'eval_doc'
157                 ]
158         ],
159         [
160                 LL("&Search"),
161                 [ 'seek', 'seek_next', 'seek_prev', 'replace', '-',
162                         'complete', '-',
163                         'seek_misspelled', 'ignore_last_misspell', '-',
164                         'seek_repeated_word', '-',
165                         'find_tag', 'complete_symbol', '-', 'grep'
166                 ]
167         ],
168         [
169                 LL("&Go to"),
170                 [ 'next', 'prev',
171                         'move_bof', 'move_eof', 'move_bol', 'move_eol',
172                         'goto', 'move_word_right', 'move_word_left',
173                         'section_list',
174                         '-', 'document_list'
175                 ]
176         ],
177         [
178                 LL("&Options"),
179                 [ 'record_macro', 'play_macro', '-',
180                         'encoding', 'tab_options', 'line_options', 'repeated_words_options',
181                         'toggle_spellcheck', '-',
182                         'word_count', '-',
183                         'zoom_in', 'zoom_out', '-',
184                         'about'
185                 ]
186         ]
189 mp.actions_by_menu_label = {};
191 /** code **/
194  * mp.redraw - Triggers a redraw on the next cycle.
196  * Triggers a full document redraw in the next cycle.
197  */
198 sub mp.redraw()
200         /* just increment the redraw trigger */
201         mp.redraw_counter++;
205 sub mp.active()
206 /* returns the active document */
208         local d;
210         /* empty document list? create a new, empty one */
211         if (size(mp.docs) == 0)
212                 mp.new();
214         /* get active document */
215         d = mp.docs[mp.active_i];
217         /* if it's read only but has modifications, revert them */
218         if (d.read_only && size(d.undo)) {
219                 while (size(d.undo))
220                         mp.undo(d);
222                 mp.message = {
223                         'timeout'       => time() + 2,
224                         'string'        => '*' ~ L("Read-only document") ~ '*'
225                 };
226         }
228         return d;
232 sub mp.process_action(a)
233 /* processes an action */
235         local f, d;
237         d = mp.active();
239         if ((f = mp.actions[a]) != NULL)
240                 f(d);
241         else {
242                 mp.message = {
243                         'timeout'       => time() + 2,
244                         'string'        => sprintf(L("Unknown action '%s'"), a)
245                 };
246         }
250 sub mp.process_event(k)
251 /* processes a key event */
253         local d, a;
255         /* empty document list? do nothing */
256         if (size(mp.docs) == 0)
257                 return;
259         d = mp.active();
261         if (mp.keycodes_t == NULL)
262                 mp.keycodes_t = mp.keycodes;
264         /* get the action asociated to the keycode */
265         if ((a = mp.keycodes_t[k]) != NULL) {
267                 /* if it's a hash, store for further testing */
268                 if (is_hash(a))
269                         mp.keycodes_t = a;
270                 else {
271                         /* if it's executable, run it */
272                         if (is_exec(a))
273                                 a(d);
274                         else
275                         /* if it's an array, process it sequentially */
276                         if (is_array(a))
277                                 foreach(l, a)
278                                         mp.process_action(l);
279                         else
280                                 mp.process_action(a);
282                         mp.keycodes_t = NULL;
283                 }
284         }
285         else {
286                 mp.insert_keystroke(d, k);
287                 mp.keycodes_t = NULL;
288         }
290         mp.shift_pressed = NULL;
294 sub mp.build_status_line()
295 /* returns the string to be drawn in the status line */
297         if (mp.message) {
298                 /* is the message still active? */
299                 if (mp.message.timeout > time())
300                         return mp.message.string;
302                 mp.message = NULL;
303         }
305         return sregex("/%./g", mp.config.status_format, mp.status_line_info);
309 sub mp.backslash_codes(s, d)
310 /* encodes (d == 0) or decodes (d == 1) backslash codes
311    (like \n, \r, etc.) */
313         d &&    sregex("/[\r\n\t]/g", s, { "\r" => '\r', "\n" => '\n', "\t" => '\t'}) ||
314                 sregex("/\\\\[rnt]/g", s, { '\r' => "\r", '\n' => "\n", '\t' => "\t"});
318 sub mp.long_op(func, a1, a2, a3, a4)
319 /* executes a potentially long function */
321         local r;
323         mp.busy(1);
324         r = func(a1, a2, a3, a4);
325         mp.busy(0);
327         return r;
331 sub mp.get_history(key)
332 /* returns a history for the specified key */
334         if (key == NULL)
335                 return NULL;
336         if (mp.history == NULL)
337                 mp.history = {};
338         if (mp.history[key] == NULL)
339                 mp.history[key] = [];
341         return mp.history[key];
345 sub mp.menu_label(action)
346 /* returns a label for the menu for an action */
348         local l;
350         /* if action is '-', it's a menu separator */
351         if (action eq '-')
352                 return NULL;
354         /* no recognized action? return */
355         if (!exists(mp.actions, action))
356                 return action ~ "?";
358         /* get the translated description */
359         l = L(mp.actdesc[action]) || action;
361         /* is there a keycode that generates this action? */
362         foreach (i, sort(keys(mp.keycodes))) {
363                 if (mp.keycodes[i] eq action) {
364                         /* avoid mouse and window pseudo-keycodes */
365                         if (!regex("/window/", i) && !regex("/mouse/", i)) {
366                                 l = l ~ ' [' ~ i ~ ']';
367                                 break;
368                         }
369                 }
370         }
372         mp.actions_by_menu_label[l] = action;
374         return l;
378 sub mp.trim_with_ellipsis(str, max)
379 /* trims the string to the last max characters, adding ellipsis if done */
381         local v = regex('/.{' ~ max ~ '}$/', str);
382         return v && '...' ~ v || str;
386 sub mp.get_doc_names(max)
387 /* returns an array with the trimmed names of the documents */
389         map(sub(e) {
390                 (e.txt.mod && '* ' || '') ~ mp.trim_with_ellipsis(e.name, (max || 24));
391         }, mp.docs);
395 sub mp.usage()
396 /* set mp.exit_message with an usage message (--help) */
398         mp.exit_message = 
399         sprintf(L(
400                 "Minimum Profit %s - Programmer Text Editor\n"\
401                 "Copyright (C) Angel Ortega <angel@triptico.com>\n"\
402                 "This software is covered by the GPL license. NO WARRANTY.\n"\
403                 "\n"\
404                 "Usage: mp-5 [options] [files...]\n"\
405                 "\n"\
406                 "Options:\n"\
407                 "\n"\
408                 " -t {tag}           Edits the file where tag is defined\n"\
409                 " -e {mpsl_code}     Executes MPSL code\n"\
410                 " -f {mpsl_script}   Executes MPSL script file\n"\
411                 " -d {directory}     Set current directory\n"\
412                 " +NNN               Moves to line number NNN of last file\n"\
413                 "\n"\
414                 "Homepage: http://www.triptico.com/software/mp.html\n"\
415                 "Mailing list: mp-subscribe@lists.triptico.com\n"
416         ), mp.VERSION);
420 sub mp.process_cmdline()
421 /* process the command line arguments (ARGV) */
423         local o, line;
425         mp.load_tags();
427         /* skip ARGV[0] */
428         shift(ARGV);
430         while (o = shift(ARGV)) {
431                 if (o eq '-h' || o eq '--help') {
432                         mp.usage();
433                         mp.exit();
434                         return;
435                 }
436                 else
437                 if (o eq '-e') {
438                         /* execute code */
439                         local c = shift(ARGV);
441                         if (! regex('/;\s*$/', c))
442                                 c = c ~ ';';
444                         eval(c);
445                 }
446                 else
447                 if (o eq '-f') {
448                         /* execute script */
449                         local s = shift(ARGV);
451                         if (stat(s) == NULL)
452                                 ERROR = sprintf(L("Cannot open '%s'"), s);
453                         else {
454                                 mp.open(s);
455                                 eval(join("\n", mp.active.txt.lines));
456                                 mp.close();
457                         }
458                 }
459                 else
460                 if (o eq '-d')
461                         chdir(shift(ARGV));
462                 else
463                 if (o eq '-t')
464                         mp.open_tag(shift(ARGV));
465                 else
466                 if (regex('/^\+/', o)) {
467                         /* move to line */
468                         line = o - 1;
469                 }
470                 else
471                         mp.open(o);
472         }
474         if (ERROR) {
475                 mp.exit_message = ERROR ~ "\n";
476                 ERROR = NULL;
477                 mp.exit();
478                 return;
479         }
481         /* if no files are loaded, try a session */
482         if (size(mp.docs) == 0 && mp.config.auto_sessions) {
483                 mp.load_session();
484         }
485         else {
486                 /* set the first as the active one */
487                 mp.active_i = 0;
488         }
490         mp.active();
492         /* if there is a line defined, move there */
493         if (line != NULL)
494                 mp.set_y(mp.active(), line);
498 sub mp.load_profile()
499 /* loads ~/.mp.mpsl */
501         /* if /etc/mp.mpsl exists, execute it */
502         if (stat('/etc/mp.mpsl') != NULL) {
503                 eval( sub {
504                         local INC = [ '/etc' ];
505                         load('mp.mpsl');
506                 });
507         }
509         /* if ~/.mp.mpsl exists, execute it */
510         if (ERROR == NULL && stat(HOMEDIR ~ '.mp.mpsl') != NULL) {
511                 eval( sub {
512                         local INC = [ HOMEDIR ];
513                         load(".mp.mpsl");
514                 });
515         }
517         /* errors? show in a message */
518         if (ERROR != NULL) {
519                 mp.message = {
520                         'timeout'       => time() + 20,
521                         'string'        => ERROR
522                 };
524                 ERROR = NULL;
525         }
529 sub mp.setup_language()
530 /* sets up the language */
532         /* set gettext() domain */
533         gettext_domain('minimum-profit', APPDIR ~ 'locale');
535         /* test if gettext() can do a basic translation */
536         if (gettext('&File') eq '&File' && ENV.LANG) {
537                 /* no; try alternatives using the LANG variable */
538                 local v = [ sregex('!/!g', ENV.LANG) ]; /* es_ES.UTF-8 */
539                 push(v, shift(split('.', v[-1])));      /* es_ES */
540                 push(v, shift(split('_', v[-1])));      /* es */
542                 foreach (l, v) {
543                         eval('load("lang/' ~ l ~ '.mpsl");');
545                         if (ERROR == NULL)
546                                 break;
547                 }
549                 ERROR = NULL;
550         }
554 sub mp.normalize_version(vs)
555 /* converts a version string to something usable with cmp() */
557         map(sub(e) { sprintf("%03d", e); },
558                 split('.',
559                         sregex('/-.+$/', vs)));
563 sub mp.assert_version(found, minimal, package)
564 /* asserts that 'found' version of 'package' is at least 'minimal',
565    or generate a warning otherwise */
567         if (cmp(mp.normalize_version(found),
568                 mp.normalize_version(minimal)) < 0) {
569                 mp.alert(sprintf(L("WARNING: %s version found is %s, but %s is needed"),
570                                 package, found, minimal));
571         }
575 sub mp.test_versions()
576 /* tests component versions */
578         local mpdm = MPDM();
580         mp.assert_version(mpdm.version, '1.0.7', 'MPDM');
581         mp.assert_version(MPSL.VERSION, '1.0.7', 'MPSL');
585 /** MAIN **/
587 load("mp_drv.mpsl");
588 load("mp_move.mpsl");
589 load("mp_edit.mpsl");
590 load("mp_file.mpsl");
591 load("mp_clipboard.mpsl");
592 load("mp_search.mpsl");
593 load("mp_tags.mpsl");
594 load("mp_syntax.mpsl");
595 load("mp_macro.mpsl");
596 load("mp_templates.mpsl");
597 load("mp_spell.mpsl");
598 load("mp_misc.mpsl");
599 load("mp_crypt.mpsl");
600 load("mp_keyseq.mpsl");
601 load("mp_session.mpsl");
602 load("mp_build.mpsl");
603 load("mp_writing.mpsl");
605 mp.load_profile();
606 mp.setup_language();
607 mp.drv.startup();
608 mp.process_cmdline();
609 mp.test_versions();
610 mp.drv.main_loop();
611 mp.drv.shutdown();