Suppressed error in window initialisation.
[mp-5.x.git] / mp_file.mpsl
blob0b88952285f5639cfae0d44115b137b76cd15e8a
1 /*
3     Minimum Profit 5.x
4     A Programmer's Text Editor
6     File manipulation.
8     Copyright (C) 1991-2009 Angel Ortega <angel@triptico.com>
10     This program is free software; you can redistribute it and/or
11     modify it under the terms of the GNU General Public License
12     as published by the Free Software Foundation; either version 2
13     of the License, or (at your option) any later version.
15     This program is distributed in the hope that it will be useful,
16     but WITHOUT ANY WARRANTY; without even the implied warranty of
17     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18     GNU General Public License for more details.
20     You should have received a copy of the GNU General Public License
21     along with this program; if not, write to the Free Software
22     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24     http://www.triptico.com
28 /** editor actions **/
30 mp.actions['new']       = sub (d) {
31         d = mp.find_file_by_name(L("<unnamed>"));
33         if (d != -1) {
34                 mp.active_i = d;
35                 d = mp.active();
36         }
37         else
38                 d = mp.new();
41 mp.actions['next']      = sub (d) { mp.next(); };
42 mp.actions['prev']      = sub (d) { mp.prev(); };
44 mp.actions['save_as']   = sub (d) {
46         local t;
48         if ((t = mp.savefile(L("Save file as:"))) == NULL)
49                 return;
51         /* store new name */
52         d.name = t;
54         if (mp.long_op(mp.save, d) == -1)
55                 mp.alert(sprintf(L("Error saving file: %s"), ERRNO));
56         else
57                 mp.detect_syntax(d);
60 mp.actions['save']      = sub (d) {
62         /* name is <unnamed> or something similar; ask for one */
63         if (regex("/^<.+>$/", d.name))
64                 mp.actions.save_as(d);
65         else
66         if (mp.long_op(mp.save, d) == -1)
67                 mp.alert(sprintf(L("Error saving file: %s"), ERRNO));
70 mp.actions['close']     = sub (d) {
72         if (d.txt.mod) {
73                 local r;
74                 r = mp.confirm(L("File has changed. Save changes?"));
76                 /* cancel? don't close */
77                 if (r == 0)
78                         return;
79                 if (r == 1)
80                         mp.actions.save(d);
81         }
83         mp.close();
86 mp.actions['exit']      = sub (d) {
88         local s;
90         if (mp.config.auto_sessions)
91                 mp.save_session();
93         if (mp.actions.close_all())
94                 mp.exit();
97 mp.actions['open']      = sub (d) {
99         local n;
101         if ((n = mp.openfile(L("File to open:"))) != NULL && n ne "")
102                 if (mp.long_op(mp.open, n) == NULL && ERRNO != NULL)
103                         mp.alert(sprintf("Error opening '%s': %s", n, ERRNO));
106 mp.actions['revert']    = sub (d) {
107         /* save current name */
108         local p = d.name;
110         if (d.txt.mod) {
111                 local r;
112                 r = mp.confirm(L("File has changed. Are you sure?"));
114                 /* cancel? don't close */
115                 if (r == 0 || r == 2)
116                         return;
117         }
119         mp.close();
120         if (mp.long_op(mp.open, p) == NULL && ERRNO != NULL)
121                 mp.alert(sprintf("Error opening '%s': %s", p, ERRNO));
124 mp.actions['open_config_file']  = sub (d) {
126         mp.open(HOMEDIR ~ ".mp.mpsl");
129 mp.actions['sync'] = sub (d) {
131         /* save all modified documents */
132         foreach (d, grep(sub (e) { e.txt.mod; }, mp.docs))
133                 mp.actions.save(d);
136 mp.actions['exec_command']      = sub (d) {
138         local t = mp.form( [
139                 { 'label' => L("System command:"),
140                   'type' => 'text',
141                   'history' => 'system' }
142                 ]);
144         if (t != NULL) {
145                 local cmd = t[0];
147                 /* does it start with a pipe? */
148                 if (regex('/^\|/', cmd)) {
149                         local p;
151                         /* yes; current document should be fed to it */
152                         cmd = sregex('/^\|/', cmd, NULL);
154                         if ((p = popen(cmd, "w")) != NULL) {
155                                 foreach (l, mp.get_active_area(d))
156                                         write(p, l ~ mp.config.eol);
158                                 pclose(p);
159                         }
160                         else
161                                 mp.drv.alert(
162                                         sprintf(L("Error writing to command '%s'"), cmd));
163                 }
164                 else {
165                         /* no; execute command and insert into cursor */
166                         local p;
168                         if ((p = popen(cmd, "r")) != NULL) {
169                                 local l;
171                                 mp.store_undo(d);
173                                 while ((l = read(p)) != NULL) {
174                                         mp.insert(d, mp.chomp(l));
175                                         mp.insert_newline(d);
176                                 }
178                                 pclose(p);
179                         }
180                         else
181                                 mp.drv.alert(
182                                         sprintf(L("Error reading from command '%s'"), cmd));
183                 }
184         }
187 mp.actions['close_all'] = sub {
189         local s;
191         while (s = size(mp.docs)) {
192                 local doc = mp.docs[mp.active_i];
193                 
194                 /* close current document */
195                 mp.actions.close(doc);
197                 /* if the size of the list hasn't changed,
198                    action was cancelled, so don't exit */
199                 if (s == size(mp.docs))
200                         return 0;
201         }
203         return 1;
206 mp.actions['open_under_cursor'] = sub (d) {
207         local w;
209         /* is the word under cursor file:line: ? */
210         if ((w = mp.get_word(d, '/[a-z\._0-9\/ :-]+:[0-9]+: ?/i')) != NULL) {
211                 w = split(':', w);
213                 /* drop garbage */
214                 pop(w);
216                 /* pick the line */
217                 local l = pop(w) - 1;
219                 /* open the file, rejoining with : */
220                 local n = mp.open(join(':', w));
222                 /* now move to the line */
223                 mp.search_set_y(n, l);
224         }
225         else
226         if ((w = mp.get_word(d, '/[a-z\._0-9\/ :-]+/i')) != NULL) {
227                 mp.open(w);
228         }
231 mp.actions['hex_view']  = sub (d) {
233         local n;
235         if ((n = mp.openfile(L("File to open:"))) != NULL && n ne "")
236                 if (mp.long_op(mp.hex_view, n) == NULL && ERRNO != NULL)
237                         mp.alert(sprintf("Error opening '%s': %s", n, ERRNO));
240 mp.actions['open_dropped_files'] = sub (d) {
241         while (size(mp.dropped_files))
242                 mp.open(shift(mp.dropped_files));
246 /** default key bindings **/
248 mp.keycodes['ctrl-n']           = 'next';
249 mp.keycodes['ctrl-o']           = 'open';
250 mp.keycodes['ctrl-q']           = 'exit';
251 mp.keycodes['ctrl-s']           = 'save';
252 mp.keycodes['ctrl-w']           = 'close';
253 mp.keycodes['ctrl-enter']       = 'open_under_cursor';
254 mp.keycodes['dropped-files']    = 'open_dropped_files';
256 mp.keycodes['close-window']     = 'exit';
258 /** action descriptions **/
260 mp.actdesc['new']       = LL("New");
261 mp.actdesc['save']      = LL("Save...");
262 mp.actdesc['save_as']   = LL("Save as...");
263 mp.actdesc['next']      = LL("Next");
264 mp.actdesc['prev']      = LL("Previous");
265 mp.actdesc['open']      = LL("Open...");
266 mp.actdesc['exit']      = LL("Exit");
267 mp.actdesc['close']     = LL("Close");
268 mp.actdesc['revert']    = LL("Revert");
269 mp.actdesc['close_all'] = LL("Close all");
271 mp.actdesc['open_config_file']          = LL("Edit configuration file");
272 mp.actdesc['sync']                      = LL("Save modified texts");
273 mp.actdesc['exec_command']              = LL("Run system command...");
274 mp.actdesc['open_under_cursor']         = LL("Open file under cursor");
275 mp.actdesc['hex_view']                  = LL("Hexadecimal viewer...");
276 mp.actdesc['open_dropped_files']        = LL("Open dropped files");
278 /** code **/
280 sub mp.chomp(str)
281 /* chomps the end of file chars from a string */
283         sregex("/\r*\n*$/", str, NULL);
287 sub mp.save(doc)
288 /* saves a file */
290         local f;
291         local s = NULL;
292         local nl = 0;
294         /* if unlink before write is desired, do it */
295         if (mp.config.unlink && (s = stat(doc.name)) != NULL)
296                 unlink(doc.name);
298         /* set the encoding for this file opening */
299         TEMP_ENCODING = doc.encoding;
301         if ((f = open(doc.name, "wb")) == NULL) {
302                 /* can't write? delete name */
303                 doc.name = L("<unnamed>");
304                 return -1;
305         }
307         /* if the document has a password, save it encrypted */
308         if (doc.password)
309                 nl = mp.crypt1_save(f, doc.txt.lines, doc.password);
310         else {
311                 /* save as a plain text file */
312                 foreach (l, doc.txt.lines) {
313                         /* write a line separator if it's not the first line */
314                         if (nl)
315                                 write(f, doc.eol || mp.config.eol);
317                         write(f, l);
318                         nl++;
319                 }
320         }
322         close(f);
324         doc.txt.mod = 0;
326         /* set back the permissions and ownership, if available */
327         if (s != NULL) {
328                 chmod(doc.name, s[2]);
329                 chown(doc.name, s[4], s[5]);
330         }
332         return nl;
336 sub mp.new(filename, lines)
337 /* creates a new document */
339         local doc, txt;
341         txt = {};
342         txt.x = 0;
343         txt.y = 0;
344         txt.vx = 0;
345         txt.vy = 0;
346         txt.lines = lines || [ '' ];
347         txt.mod = 0;
349         doc = {};
350         doc.name = filename || L("<unnamed>");
351         doc.txt = txt;
353         doc.undo = [];
354         doc.redo = [];
356         doc.syntax = NULL;
358         /* store in the list and set as active */
359         push(mp.docs, doc);
360         mp.active_i = size(mp.docs) - 1;
362         /* autodetect syntax */
363         mp.detect_syntax(doc);
365         return doc;
369 sub mp.next()
370 /* rotates through the document list */
372         if (++mp.active_i == size(mp.docs))
373                 mp.active_i = 0;
375         return mp.active();
379 sub mp.prev()
380 /* rotates through the document list, backwards */
382         if (--mp.active_i == -1)
383                 mp.active_i = size(mp.docs) - 1;
385         return mp.active();
389 sub mp.close()
390 /* closes the active document */
392         local k = mp.active_i;
394         /* delete from the list */
395         adel(mp.docs, mp.active_i);
397         /* rotate if it was the last one */
398         if (mp.active_i == size(mp.docs))
399                 mp.active_i = 0;
401         /* cannot call mp.active() */
405 sub mp.find_file_by_name(filename)
406 /* finds an open file by its name */
408         seek(map(sub(d) { d.name; }, mp.docs), filename);
412 sub mp.open(filename)
413 /* opens a new document (uses UI) */
415         local s;
417         /* looks first if the file is already open */
418         if ((s = mp.find_file_by_name(filename)) != -1) {
419                 mp.active_i = s;
420                 return mp.active();
421         }
423         if ((s = stat(filename)) == NULL) {
424                 mp.message = {
425                         'timeout' => time() + 2,
426                         'string'  => sprintf(L("New file '%s'"), filename)
427                 };
429                 return mp.new(filename);
430         }
432         /* canonicalize, if possible */
433         if (s[13] != NULL) {
434                 filename = s[13];
436                 /* look again for this filename in the open files */
437                 if ((s = mp.find_file_by_name(filename)) != -1) {
438                         mp.active_i = s;
439                         return mp.active();
440                 }
441         }
443         local d, f;
445         if ((f = open(filename, "rb")) == NULL)
446                 return NULL;
447         else {
448                 if (mp.crypt1_detect(f)) {
449                         /* password needed; ask for it */
450                         local p;
452                         if ((p = mp.form( [
453                                 { 'label'       => L("Password:"),
454                                   'type'        => 'password' }
455                                 ])) == NULL) {
456                                 /* cancel? fail, but not on error */
457                                 return NULL;
458                         }
460                         /* get the password */
461                         p = p[0];
463                         /* an empty password is equal to cancellation */
464                         if (p eq '')
465                                 return NULL;
467                         /* and load the file */
468                         d = mp.new(filename, mp.crypt1_load(f, p));
469                         d.password = p;
470                 }
471                 else {
472                         /* close file (needed for rewinding AND
473                            possible encoding autodetection) */
474                         close(f);
476                         /* reopen and read */
477                         f = open(filename, "rb");
478                         d = mp.new(filename, mp.plain_load(f));
479                 }
481                 close(f);
482         }
484         /* store the encoding */
485         d.encoding = DETECTED_ENCODING || ENCODING || '';
487         /* if original EOL is to be kept, store it */
488         if (mp.config.keep_eol)
489                 d.eol = mp.last_seen_eol;
491         return d;
495 sub mp.hex_view(filename)
496 /* shows a file as an hex dump */
498         local f, c;
500         if ((f = open(filename, "rb")) == NULL)
501                 return NULL;
503         local lines =   [];
504         local l =       [];
505         local offset =  0;
507         while (1) {
508                 if ((c = getchar(f)) != NULL)
509                         push(l, c);
511                 if (size(l) == 16 || c == NULL) {
512                         local h = '';
513                         local a = ' ';
515                         /* add hex view */
516                         foreach (v, l) {
517                                 h = h ~ sprintf(' %02X', ord(v));
519                                 if (ord(v) == 0x0a)
520                                         v = "\x{00b6}";
521                                 else
522                                 if (ord(v) < 32 || ord(v) > 126)
523                                         v = "\x{00b7}";
525                                 a = a ~ v;
526                         }
528                         local n = 16 - size(l);
530                         /* fill up to 16 */
531                         while (n--) {
532                                 h = h ~ '   ';
533                                 a = a ~ ' ';
534                         }
536                         push(lines, join(' |', [ sprintf('| %06X', offset), h, a, '']));
537                         offset += 16;
538                         l = [];
540                         if (c == NULL)
541                                 break;
542                 }
543         }
545         close(f);
547         local d = mp.new('<' ~ filename ~ ' hex view>', lines);
548         d.read_only = 1;
549         d.syntax = mp.syntax.hex_view;
551         return d;