]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
54c68f6acdab643f1dec21c5b096323f7132cd6c
[lyx.git] / src / lyxfunc.C
1 /**
2  * \file lyxfunc.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Allan Rae
13  * \author Dekel Tsur
14  * \author Martin Vermeer
15  * \author Jürgen Vigna
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "lyxfunc.h"
23
24 #include "BranchList.h"
25 #include "buffer.h"
26 #include "buffer_funcs.h"
27 #include "bufferlist.h"
28 #include "bufferparams.h"
29 #include "BufferView.h"
30 #include "cursor.h"
31 #include "debug.h"
32 #include "dispatchresult.h"
33 #include "encoding.h"
34 #include "exporter.h"
35 #include "format.h"
36 #include "funcrequest.h"
37 #include "gettext.h"
38 #include "importer.h"
39 #include "intl.h"
40 #include "kbmap.h"
41 #include "LColor.h"
42 #include "lyx_cb.h"
43 #include "LyXAction.h"
44 #include "lyxfind.h"
45 #include "lyxrc.h"
46 #include "lyxrow.h"
47 #include "lyxserver.h"
48 #include "lyxvc.h"
49 #include "paragraph.h"
50 #include "pariterator.h"
51 #include "ParagraphParameters.h"
52 #include "undo.h"
53
54 #include "insets/insetbox.h"
55 #include "insets/insetbranch.h"
56 #include "insets/insetcommand.h"
57 #include "insets/insetert.h"
58 #include "insets/insetexternal.h"
59 #include "insets/insetfloat.h"
60 #include "insets/insetgraphics.h"
61 #include "insets/insetnote.h"
62 #include "insets/insettabular.h"
63 #include "insets/insetvspace.h"
64 #include "insets/insetwrap.h"
65
66 #include "frontends/Alert.h"
67 #include "frontends/Dialogs.h"
68 #include "frontends/FileDialog.h"
69 #include "frontends/lyx_gui.h"
70 #include "frontends/LyXKeySym.h"
71 #include "frontends/LyXView.h"
72 #include "frontends/Menubar.h"
73 #include "frontends/Toolbar.h"
74
75 #include "support/FileInfo.h"
76 #include "support/filetools.h"
77 #include "support/forkedcontr.h"
78 #include "support/globbing.h"
79 #include "support/lstrings.h"
80 #include "support/path.h"
81 #include "support/path_defines.h"
82 #include "support/systemcall.h"
83 #include "support/tostr.h"
84 #include "support/std_sstream.h"
85 #include "support/os.h"
86
87 using bv_funcs::freefont2string;
88
89 using lyx::support::AddName;
90 using lyx::support::AddPath;
91 using lyx::support::bformat;
92 using lyx::support::ChangeExtension;
93 using lyx::support::contains;
94 using lyx::support::FileFilterList;
95 using lyx::support::FileInfo;
96 using lyx::support::FileSearch;
97 using lyx::support::ForkedcallsController;
98 using lyx::support::i18nLibFileSearch;
99 using lyx::support::IsDirWriteable;
100 using lyx::support::IsFileReadable;
101 using lyx::support::isStrInt;
102 using lyx::support::MakeAbsPath;
103 using lyx::support::MakeDisplayPath;
104 using lyx::support::Path;
105 using lyx::support::QuoteName;
106 using lyx::support::rtrim;
107 using lyx::support::split;
108 using lyx::support::strToInt;
109 using lyx::support::strToUnsignedInt;
110 using lyx::support::subst;
111 using lyx::support::system_lyxdir;
112 using lyx::support::Systemcall;
113 using lyx::support::token;
114 using lyx::support::trim;
115 using lyx::support::user_lyxdir;
116 using lyx::support::prefixIs;
117 using lyx::support::os::getTmpDir;
118
119 using std::endl;
120 using std::make_pair;
121 using std::pair;
122 using std::string;
123 using std::istringstream;
124
125
126 extern BufferList bufferlist;
127 extern LyXServer * lyxserver;
128 extern bool selection_possible;
129
130 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
131
132 // (alkis)
133 extern tex_accent_struct get_accent(kb_action action);
134
135
136 LyXFunc::LyXFunc(LyXView * lv)
137         : owner(lv),
138         encoded_last_key(0),
139         keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
140         cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
141         meta_fake_bit(key_modifier::none)
142 {
143 }
144
145
146 void LyXFunc::handleKeyFunc(kb_action action)
147 {
148         char c = encoded_last_key;
149
150         if (keyseq.length()) {
151                 c = 0;
152         }
153
154         owner->getIntl().getTransManager()
155                 .deadkey(c, get_accent(action).accent, view()->getLyXText());
156         // Need to clear, in case the minibuffer calls these
157         // actions
158         keyseq.clear();
159         // copied verbatim from do_accent_char
160         view()->cursor().resetAnchor();
161         view()->update();
162 }
163
164
165 void LyXFunc::processKeySym(LyXKeySymPtr keysym, key_modifier::state state)
166 {
167         lyxerr[Debug::KEY] << "KeySym is " << keysym->getSymbolName() << endl;
168
169         // Do nothing if we have nothing (JMarc)
170         if (!keysym->isOK()) {
171                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
172                                    << endl;
173                 return;
174         }
175
176         if (keysym->isModifier()) {
177                 lyxerr[Debug::KEY] << "isModifier true" << endl;
178                 return;
179         }
180
181         Encoding const * encoding = view()->cursor().getEncoding();
182
183         encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
184
185         // Do a one-deep top-level lookup for
186         // cancel and meta-fake keys. RVDK_PATCH_5
187         cancel_meta_seq.reset();
188
189         FuncRequest func = cancel_meta_seq.addkey(keysym, state);
190         lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
191
192         // When not cancel or meta-fake, do the normal lookup.
193         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
194         // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
195         if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
196                 // remove Caps Lock and Mod2 as a modifiers
197                 func = keyseq.addkey(keysym, (state | meta_fake_bit));
198                 lyxerr[Debug::KEY] << "action now set to ["
199                         << func.action << ']' << endl;
200         }
201
202         // Dont remove this unless you know what you are doing.
203         meta_fake_bit = key_modifier::none;
204
205         // can this happen now ?
206         if (func.action == LFUN_NOACTION) {
207                 func = FuncRequest(LFUN_PREFIX);
208         }
209
210         if (lyxerr.debugging(Debug::KEY)) {
211                 lyxerr << "Key [action="
212                        << func.action << "]["
213                        << keyseq.print() << ']'
214                        << endl;
215         }
216
217         // already here we know if it any point in going further
218         // why not return already here if action == -1 and
219         // num_bytes == 0? (Lgb)
220
221         if (keyseq.length() > 1) {
222                 owner->message(keyseq.print());
223         }
224
225
226         // Maybe user can only reach the key via holding down shift.
227         // Let's see. But only if shift is the only modifier
228         if (func.action == LFUN_UNKNOWN_ACTION &&
229             state == key_modifier::shift) {
230                 lyxerr[Debug::KEY] << "Trying without shift" << endl;
231                 func = keyseq.addkey(keysym, key_modifier::none);
232                 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
233         }
234
235         if (func.action == LFUN_UNKNOWN_ACTION) {
236                 // Hmm, we didn't match any of the keysequences. See
237                 // if it's normal insertable text not already covered
238                 // by a binding
239                 if (keysym->isText() && keyseq.length() == 1) {
240                         lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
241                         func = FuncRequest(LFUN_SELFINSERT);
242                 } else {
243                         lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
244                         owner->message(_("Unknown function."));
245                         return;
246                 }
247         }
248
249         if (func.action == LFUN_SELFINSERT) {
250                 if (encoded_last_key != 0) {
251                         string arg(1, encoded_last_key);
252                         dispatch(FuncRequest(LFUN_SELFINSERT, arg));
253                         lyxerr[Debug::KEY]
254                                 << "SelfInsert arg[`" << arg << "']" << endl;
255                 }
256         } else {
257                 dispatch(func);
258         }
259 }
260
261
262 FuncStatus LyXFunc::getStatus(FuncRequest const & cmd) const
263 {
264         //lyxerr << "LyXFunc::getStatus: cmd: " << cmd << endl;
265         FuncStatus flag;
266         Buffer * buf = owner->buffer();
267         LCursor & cur = view()->cursor();
268
269         if (cmd.action == LFUN_NOACTION) {
270                 setStatusMessage(N_("Nothing to do"));
271                 flag.enabled(false);
272                 return flag;
273         }
274
275         switch (cmd.action) {
276         case LFUN_UNKNOWN_ACTION:
277 #ifndef HAVE_LIBAIKSAURUS
278         case LFUN_THESAURUS_ENTRY:
279 #endif
280                 flag.unknown(true);
281                 flag.enabled(false);
282                 break;
283         default:
284                 flag |= lyx_gui::getStatus(cmd);
285         }
286
287         if (flag.unknown()) {
288                 setStatusMessage(N_("Unknown action"));
289                 return flag;
290         }
291
292         // the default error message if we disable the command
293         setStatusMessage(N_("Command disabled"));
294
295         // Check whether we need a buffer
296         if (!lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer) && !buf) {
297                 // no, exit directly
298                 setStatusMessage(N_("Command not allowed with"
299                                     "out any document open"));
300                 flag.enabled(false);
301                 return flag;
302         }
303
304         // I would really like to avoid having this switch and rather try to
305         // encode this in the function itself.
306         // -- And I'd rather let an inset decide which LFUNs it is willing
307         // to handle (Andre')
308         bool enable = true;
309         switch (cmd.action) {
310         case LFUN_TOOLTIPS_TOGGLE:
311                 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
312                 break;
313
314         case LFUN_READ_ONLY_TOGGLE:
315                 flag.setOnOff(buf->isReadonly());
316                 break;
317
318         case LFUN_SWITCHBUFFER:
319                 // toggle on the current buffer, but do not toggle off
320                 // the other ones (is that a good idea?)
321                 if (cmd.argument == buf->fileName())
322                         flag.setOnOff(true);
323                 break;
324
325         case LFUN_TRACK_CHANGES:
326                 flag.setOnOff(buf->params().tracking_changes);
327                 break;
328
329         case LFUN_EXPORT:
330                 enable = cmd.argument == "custom"
331                         || Exporter::IsExportable(*buf, cmd.argument);
332                 break;
333         case LFUN_UNDO:
334                 enable = !buf->undostack().empty();
335                 break;
336         case LFUN_REDO:
337                 enable = !buf->redostack().empty();
338                 break;
339         case LFUN_CUT:
340         case LFUN_COPY:
341                 enable = cur.selection();
342                 break;
343
344         case LFUN_RUNCHKTEX:
345                 enable = buf->isLatex() && lyxrc.chktex_command != "none";
346                 break;
347
348         case LFUN_BUILDPROG:
349                 enable = Exporter::IsExportable(*buf, "program");
350                 break;
351
352         case LFUN_LAYOUT_TABULAR:
353                 enable = cur.innerInsetOfType(InsetBase::TABULAR_CODE);
354                 break;
355
356         case LFUN_LAYOUT:
357         case LFUN_LAYOUT_PARAGRAPH:
358                 enable = !cur.inset().forceDefaultParagraphs(&cur.inset());
359                 break;
360
361         case LFUN_VC_REGISTER:
362                 enable = !buf->lyxvc().inUse();
363                 break;
364         case LFUN_VC_CHECKIN:
365                 enable = buf->lyxvc().inUse() && !buf->isReadonly();
366                 break;
367         case LFUN_VC_CHECKOUT:
368                 enable = buf->lyxvc().inUse() && buf->isReadonly();
369                 break;
370         case LFUN_VC_REVERT:
371         case LFUN_VC_UNDO:
372                 enable = buf->lyxvc().inUse();
373                 break;
374         case LFUN_MENURELOAD:
375                 enable = !buf->isUnnamed() && !buf->isClean();
376                 break;
377         case LFUN_BOOKMARK_GOTO:
378                 enable = view()->isSavedPosition(strToUnsignedInt(cmd.argument));
379                 break;
380
381         case LFUN_MERGE_CHANGES:
382         case LFUN_ACCEPT_CHANGE:
383         case LFUN_REJECT_CHANGE:
384         case LFUN_ACCEPT_ALL_CHANGES:
385         case LFUN_REJECT_ALL_CHANGES:
386                 enable = buf && buf->params().tracking_changes;
387                 break;
388
389         case LFUN_INSET_SETTINGS: {
390                 enable = false;
391                 if (!cur.size())
392                         break;
393                 UpdatableInset * inset = cur.inset().asUpdatableInset();
394                 lyxerr << "inset: " << inset << endl;
395                 if (!inset)
396                         break;
397
398                 InsetOld::Code code = inset->lyxCode();
399                 switch (code) {
400                         case InsetOld::TABULAR_CODE:
401                                 enable = cmd.argument == "tabular";
402                                 break;
403                         case InsetOld::ERT_CODE:
404                                 enable = cmd.argument == "ert";
405                                 break;
406                         case InsetOld::FLOAT_CODE:
407                                 enable = cmd.argument == "float";
408                                 break;
409                         case InsetOld::WRAP_CODE:
410                                 enable = cmd.argument == "wrap";
411                                 break;
412                         case InsetOld::NOTE_CODE:
413                                 enable = cmd.argument == "note";
414                                 break;
415                         case InsetOld::BRANCH_CODE:
416                                 enable = cmd.argument == "branch";
417                                 break;
418                         case InsetOld::BOX_CODE:
419                                 enable = cmd.argument == "box";
420                                 break;
421                         default:
422                                 break;
423                 }
424                 break;
425         }
426
427         case LFUN_DIALOG_SHOW: {
428                 string const name = cmd.getArg(0);
429                 if (!buf)
430                         enable = name == "aboutlyx"
431                                 || name == "file"
432                                 || name == "forks"
433                                 || name == "preferences"
434                                 || name == "texinfo";
435                 else if (name == "print")
436                         enable = Exporter::IsExportable(*buf, "dvi")
437                                 && lyxrc.print_command != "none";
438                 else if (name == "character")
439                         enable = cur.inset().lyxCode() != InsetOld::ERT_CODE;
440                 else if (name == "vclog")
441                         enable = buf->lyxvc().inUse();
442                 else if (name == "latexlog")
443                         enable = IsFileReadable(buf->getLogName().second);
444                 break;
445         }
446
447         case LFUN_MENUNEW:
448         case LFUN_MENUNEWTMPLT:
449         case LFUN_WORDFINDFORWARD:
450         case LFUN_WORDFINDBACKWARD:
451         case LFUN_PREFIX:
452         case LFUN_EXEC_COMMAND:
453         case LFUN_CANCEL:
454         case LFUN_META_FAKE:
455         case LFUN_CLOSEBUFFER:
456         case LFUN_MENUWRITE:
457         case LFUN_WRITEAS:
458         case LFUN_UPDATE:
459         case LFUN_PREVIEW:
460         case LFUN_IMPORT:
461         case LFUN_QUIT:
462         case LFUN_TOCVIEW:
463         case LFUN_AUTOSAVE:
464         case LFUN_RECONFIGURE:
465         case LFUN_HELP_OPEN:
466         case LFUN_FILE_NEW:
467         case LFUN_FILE_OPEN:
468         case LFUN_DROP_LAYOUTS_CHOICE:
469         case LFUN_MENU_OPEN_BY_NAME:
470         case LFUN_GETNAME:
471         case LFUN_NOTIFY:
472         case LFUN_GOTOFILEROW:
473         case LFUN_GOTO_PARAGRAPH:
474         case LFUN_DIALOG_SHOW_NEW_INSET:
475         case LFUN_DIALOG_SHOW_NEXT_INSET:
476         case LFUN_DIALOG_UPDATE:
477         case LFUN_DIALOG_HIDE:
478         case LFUN_DIALOG_DISCONNECT_INSET:
479         case LFUN_CHILDOPEN:
480         case LFUN_TOGGLECURSORFOLLOW:
481         case LFUN_KMAP_OFF:
482         case LFUN_KMAP_PRIM:
483         case LFUN_KMAP_SEC:
484         case LFUN_KMAP_TOGGLE:
485         case LFUN_REPEAT:
486         case LFUN_EXPORT_CUSTOM:
487         case LFUN_PRINT:
488         case LFUN_SEQUENCE:
489         case LFUN_SAVEPREFERENCES:
490         case LFUN_SCREEN_FONT_UPDATE:
491         case LFUN_SET_COLOR:
492         case LFUN_MESSAGE:
493         case LFUN_EXTERNAL_EDIT:
494         case LFUN_FILE_INSERT:
495         case LFUN_FILE_INSERT_ASCII:
496         case LFUN_FILE_INSERT_ASCII_PARA:
497                 // these are handled in our dispatch()
498                 break;
499
500         default:
501                 cur.getStatus(cmd, flag);
502         }
503
504         if (!enable)
505                 flag.enabled(false);
506
507         // Can we use a readonly buffer?
508         if (buf && buf->isReadonly() 
509             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
510             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
511                 setStatusMessage(N_("Document is read-only"));
512                 flag.enabled(false);
513         }
514
515         return flag;
516 }
517
518
519 namespace {
520
521 bool ensureBufferClean(BufferView * bv)
522 {
523         Buffer & buf = *bv->buffer();
524         if (buf.isClean())
525                 return true;
526
527         string const file = MakeDisplayPath(buf.fileName(), 30);
528         string text = bformat(_("The document %1$s has unsaved "
529                                 "changes.\n\nDo you want to save "
530                                 "the document?"), file);
531         int const ret = Alert::prompt(_("Save changed document?"),
532                                       text, 0, 1, _("&Save"),
533                                       _("&Cancel"));
534
535         if (ret == 0)
536                 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
537
538         return buf.isClean();
539 }
540
541 void showPrintError(string const & name)
542 {
543                 string str = bformat(_("Could not print the document %1$s.\n"
544                         "Check that your printer is set up correctly."),
545                         MakeDisplayPath(name, 50));
546                 Alert::error(_("Print document failed"), str);
547 }
548
549 } //namespace anon
550
551
552 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
553 {
554         string const argument = cmd.argument;
555         kb_action const action = cmd.action;
556
557         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
558         //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
559
560         // we have not done anything wrong yet.
561         errorstat = false;
562         dispatch_buffer.erase();
563         selection_possible = false;
564
565         // We cannot use this function here
566         if (!getStatus(cmd).enabled()) {
567                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
568                        << lyxaction.getActionName(action)
569                        << " [" << action << "] is disabled at this location"
570                        << endl;
571                 setErrorMessage(getStatusMessage());
572
573         } else {
574
575                 if (view()->available())
576                         view()->hideCursor();
577
578                 switch (action) {
579
580                 case LFUN_WORDFINDFORWARD:
581                 case LFUN_WORDFINDBACKWARD: {
582                         static string last_search;
583                         string searched_string;
584
585                         if (!argument.empty()) {
586                                 last_search = argument;
587                                 searched_string = argument;
588                         } else {
589                                 searched_string = last_search;
590                         }
591
592                         if (searched_string.empty())
593                                 break;
594
595                         bool const fw = action == LFUN_WORDFINDFORWARD;
596                         string const data =
597                                 lyx::find::find2string(searched_string, true, false, fw);
598                         lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
599                         break;
600                 }
601
602                 case LFUN_PREFIX:
603                         owner->message(keyseq.printOptions());
604                         break;
605
606                 case LFUN_EXEC_COMMAND:
607                         owner->focus_command_buffer();
608                         break;
609
610                 case LFUN_CANCEL:
611                         keyseq.reset();
612                         meta_fake_bit = key_modifier::none;
613                         if (view()->available())
614                                 // cancel any selection
615                                 dispatch(FuncRequest(LFUN_MARK_OFF));
616                         setMessage(N_("Cancel"));
617                         break;
618
619                 case LFUN_META_FAKE:
620                         meta_fake_bit = key_modifier::alt;
621                         setMessage(keyseq.print());
622                         break;
623
624                 case LFUN_READ_ONLY_TOGGLE:
625                         if (owner->buffer()->lyxvc().inUse())
626                                 owner->buffer()->lyxvc().toggleReadOnly();
627                         else
628                                 owner->buffer()->setReadonly(
629                                         !owner->buffer()->isReadonly());
630                         break;
631
632                 // --- Menus -----------------------------------------------
633                 case LFUN_MENUNEW:
634                         menuNew(argument, false);
635                         break;
636
637                 case LFUN_MENUNEWTMPLT:
638                         menuNew(argument, true);
639                         break;
640
641                 case LFUN_CLOSEBUFFER:
642                         closeBuffer();
643                         break;
644
645                 case LFUN_MENUWRITE:
646                         if (!owner->buffer()->isUnnamed()) {
647                                 string const str = bformat(_("Saving document %1$s..."),
648                                          MakeDisplayPath(owner->buffer()->fileName()));
649                                 owner->message(str);
650                                 MenuWrite(owner->buffer());
651                                 owner->message(str + _(" done."));
652                         } else
653                                 WriteAs(owner->buffer());
654                         break;
655
656                 case LFUN_WRITEAS:
657                         WriteAs(owner->buffer(), argument);
658                         break;
659
660                 case LFUN_MENURELOAD: {
661                         string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
662                         string text = bformat(_("Any changes will be lost. Are you sure "
663                                 "you want to revert to the saved version of the document %1$s?"), file);
664                         int const ret = Alert::prompt(_("Revert to saved document?"),
665                                 text, 0, 1, _("&Revert"), _("&Cancel"));
666
667                         if (ret == 0)
668                                 view()->reload();
669                         break;
670                 }
671
672                 case LFUN_UPDATE:
673                         Exporter::Export(owner->buffer(), argument, true);
674                         view()->showErrorList(BufferFormat(*owner->buffer()));
675                         break;
676
677                 case LFUN_PREVIEW:
678                         Exporter::Preview(owner->buffer(), argument);
679                         view()->showErrorList(BufferFormat(*owner->buffer()));
680                         break;
681
682                 case LFUN_BUILDPROG:
683                         Exporter::Export(owner->buffer(), "program", true);
684                         view()->showErrorList(_("Build"));
685                         break;
686
687                 case LFUN_RUNCHKTEX:
688                         owner->buffer()->runChktex();
689                         view()->showErrorList(_("ChkTeX"));
690                         break;
691
692                 case LFUN_EXPORT:
693                         if (argument == "custom")
694                                 owner->getDialogs().show("sendto");
695                         else {
696                                 Exporter::Export(owner->buffer(), argument, false);
697                                 view()->showErrorList(BufferFormat(*owner->buffer()));
698                         }
699                         break;
700
701                 case LFUN_EXPORT_CUSTOM: {
702                         string format_name;
703                         string command = split(argument, format_name, ' ');
704                         Format const * format = formats.getFormat(format_name);
705                         if (!format) {
706                                 lyxerr << "Format \"" << format_name
707                                        << "\" not recognized!"
708                                        << std::endl;
709                                 break;
710                         }
711
712                         Buffer * buffer = owner->buffer();
713
714                         // The name of the file created by the conversion process
715                         string filename;
716
717                         // Output to filename
718                         if (format->name() == "lyx") {
719                                 string const latexname =
720                                         buffer->getLatexName(false);
721                                 filename = ChangeExtension(latexname,
722                                                            format->extension());
723                                 filename = AddName(buffer->temppath(), filename);
724
725                                 if (!buffer->writeFile(filename))
726                                         break;
727
728                         } else {
729                                 Exporter::Export(buffer, format_name, true,
730                                                  filename);
731                         }
732
733                         // Substitute $$FName for filename
734                         if (!contains(command, "$$FName"))
735                                 command = "( " + command + " ) < $$FName";
736                         command = subst(command, "$$FName", filename);
737
738                         // Execute the command in the background
739                         Systemcall call;
740                         call.startscript(Systemcall::DontWait, command);
741                         break;
742                 }
743
744                 case LFUN_PRINT: {
745                         string target;
746                         string target_name;
747                         string command = split(split(argument, target, ' '),
748                                                target_name, ' ');
749
750                         if (target.empty()
751                             || target_name.empty()
752                             || command.empty()) {
753                                 lyxerr << "Unable to parse \""
754                                        << argument << '"' << std::endl;
755                                 break;
756                         }
757                         if (target != "printer" && target != "file") {
758                                 lyxerr << "Unrecognized target \""
759                                        << target << '"' << std::endl;
760                                 break;
761                         }
762
763                         Buffer * buffer = owner->buffer();
764
765                         if (!Exporter::Export(buffer, "dvi", true)) {
766                                 showPrintError(buffer->fileName());
767                                 break;
768                         }
769
770                         // Push directory path.
771                         string const path = buffer->temppath();
772                         Path p(path);
773
774                         // there are three cases here:
775                         // 1. we print to a file
776                         // 2. we print directly to a printer
777                         // 3. we print using a spool command (print to file first)
778                         Systemcall one;
779                         int res = 0;
780                         string const dviname =
781                                 ChangeExtension(buffer->getLatexName(true),
782                                                 "dvi");
783
784                         if (target == "printer") {
785                                 if (!lyxrc.print_spool_command.empty()) {
786                                         // case 3: print using a spool
787                                         string const psname =
788                                                 ChangeExtension(dviname,".ps");
789                                         command += lyxrc.print_to_file
790                                                 + QuoteName(psname)
791                                                 + ' '
792                                                 + QuoteName(dviname);
793
794                                         string command2 =
795                                                 lyxrc.print_spool_command +' ';
796                                         if (target_name != "default") {
797                                                 command2 += lyxrc.print_spool_printerprefix
798                                                         + target_name
799                                                         + ' ';
800                                         }
801                                         command2 += QuoteName(psname);
802                                         // First run dvips.
803                                         // If successful, then spool command
804                                         res = one.startscript(
805                                                 Systemcall::Wait,
806                                                 command);
807
808                                         if (res == 0)
809                                                 res = one.startscript(
810                                                         Systemcall::DontWait,
811                                                         command2);
812                                 } else {
813                                         // case 2: print directly to a printer
814                                         res = one.startscript(
815                                                 Systemcall::DontWait,
816                                                 command + QuoteName(dviname));
817                                 }
818                 
819                         } else {
820                                 // case 1: print to a file
821                                 command += lyxrc.print_to_file
822                                         + QuoteName(MakeAbsPath(target_name,
823                                                                 path))
824                                         + ' '
825                                         + QuoteName(dviname);
826                                 res = one.startscript(Systemcall::DontWait,
827                                                       command);
828                         }
829
830                         if (res != 0)
831                                 showPrintError(buffer->fileName());
832                         break;
833                 }
834
835                 case LFUN_IMPORT:
836                         doImport(argument);
837                         break;
838
839                 case LFUN_QUIT:
840                         QuitLyX();
841                         break;
842
843                 case LFUN_TOCVIEW: {
844                         InsetCommandParams p("tableofcontents");
845                         string const data = InsetCommandMailer::params2string("toc", p);
846                         owner->getDialogs().show("toc", data, 0);
847                         break;
848                 }
849
850                 case LFUN_AUTOSAVE:
851                         AutoSave(view());
852                         break;
853
854                 case LFUN_RECONFIGURE:
855                         Reconfigure(view());
856                         break;
857
858                 case LFUN_HELP_OPEN: {
859                         string const arg = argument;
860                         if (arg.empty()) {
861                                 setErrorMessage(N_("Missing argument"));
862                                 break;
863                         }
864                         string const fname = i18nLibFileSearch("doc", arg, "lyx");
865                         if (fname.empty()) {
866                                 lyxerr << "LyX: unable to find documentation file `"
867                                                          << arg << "'. Bad installation?" << endl;
868                                 break;
869                         }
870                         owner->message(bformat(_("Opening help file %1$s..."),
871                                 MakeDisplayPath(fname)));
872                         view()->loadLyXFile(fname, false);
873                         break;
874                 }
875
876                 // --- version control -------------------------------
877                 case LFUN_VC_REGISTER:
878                         if (!ensureBufferClean(view()))
879                                 break;
880                         if (!owner->buffer()->lyxvc().inUse()) {
881                                 owner->buffer()->lyxvc().registrer();
882                                 view()->reload();
883                         }
884                         break;
885
886                 case LFUN_VC_CHECKIN:
887                         if (!ensureBufferClean(view()))
888                                 break;
889                         if (owner->buffer()->lyxvc().inUse()
890                                         && !owner->buffer()->isReadonly()) {
891                                 owner->buffer()->lyxvc().checkIn();
892                                 view()->reload();
893                         }
894                         break;
895
896                 case LFUN_VC_CHECKOUT:
897                         if (!ensureBufferClean(view()))
898                                 break;
899                         if (owner->buffer()->lyxvc().inUse()
900                                         && owner->buffer()->isReadonly()) {
901                                 owner->buffer()->lyxvc().checkOut();
902                                 view()->reload();
903                         }
904                         break;
905
906                 case LFUN_VC_REVERT:
907                         owner->buffer()->lyxvc().revert();
908                         view()->reload();
909                         break;
910
911                 case LFUN_VC_UNDO:
912                         owner->buffer()->lyxvc().undoLast();
913                         view()->reload();
914                         break;
915
916                 // --- buffers ----------------------------------------
917                 case LFUN_SWITCHBUFFER:
918                         view()->setBuffer(bufferlist.getBuffer(argument));
919                         break;
920
921                 case LFUN_FILE_NEW:
922                         NewFile(view(), argument);
923                         break;
924
925                 case LFUN_FILE_OPEN:
926                         open(argument);
927                         break;
928
929                 case LFUN_DROP_LAYOUTS_CHOICE:
930                         owner->getToolbar().openLayoutList();
931                         break;
932
933                 case LFUN_MENU_OPEN_BY_NAME:
934                         owner->getMenubar().openByName(argument);
935                         break;
936
937                 // --- lyxserver commands ----------------------------
938                 case LFUN_GETNAME:
939                         setMessage(owner->buffer()->fileName());
940                         lyxerr[Debug::INFO] << "FNAME["
941                                                          << owner->buffer()->fileName()
942                                                          << "] " << endl;
943                         break;
944
945                 case LFUN_NOTIFY:
946                         dispatch_buffer = keyseq.print();
947                         lyxserver->notifyClient(dispatch_buffer);
948                         break;
949
950                 case LFUN_GOTOFILEROW: {
951                         string file_name;
952                         int row;
953                         istringstream is(argument);
954                         is >> file_name >> row;
955                         if (prefixIs(file_name, getTmpDir())) {
956                                 // Needed by inverse dvi search. If it is a file
957                                 // in tmpdir, call the apropriated function
958                                 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
959                         } else {
960                                 // Must replace extension of the file to be .lyx
961                                 // and get full path
962                                 string const s = ChangeExtension(file_name, ".lyx");
963                                 // Either change buffer or load the file
964                                 if (bufferlist.exists(s)) {
965                                         view()->setBuffer(bufferlist.getBuffer(s));
966                                 } else {
967                                         view()->loadLyXFile(s);
968                                 }
969                         }
970
971                         view()->setCursorFromRow(row);
972
973                         view()->center();
974                         // see BufferView_pimpl::center()
975                         view()->updateScrollbar();
976                         break;
977                 }
978
979                 case LFUN_GOTO_PARAGRAPH: {
980                         istringstream is(argument);
981                         int id;
982                         is >> id;
983                         ParIterator par = owner->buffer()->getParFromID(id);
984                         if (par == owner->buffer()->par_iterator_end()) {
985                                 lyxerr[Debug::INFO] << "No matching paragraph found! ["
986                                                                 << id << ']' << endl;
987                                 break;
988                         } else {
989                                 lyxerr[Debug::INFO] << "Paragraph " << par->id()
990                                                                 << " found." << endl;
991                         }
992
993                         // Set the cursor
994                         view()->setCursor(par, 0);
995
996                         view()->switchKeyMap();
997                         owner->view_state_changed();
998
999                         view()->center();
1000                         // see BufferView_pimpl::center()
1001                         view()->updateScrollbar();
1002                         break;
1003                 }
1004
1005                 case LFUN_DIALOG_SHOW: {
1006                         string const name = cmd.getArg(0);
1007                         string data = trim(cmd.argument.substr(name.size()));
1008
1009                         if (name == "character") {
1010                                 data = freefont2string();
1011                                 if (!data.empty())
1012                                         owner->getDialogs().show("character", data);
1013                         }
1014                         else if (name == "document")
1015                                 owner->getDialogs().showDocument();
1016                         else if (name == "preamble")
1017                                 owner->getDialogs().showPreamble();
1018                         else if (name == "preferences")
1019                                 owner->getDialogs().showPreferences();
1020                         else if (name == "spellchecker")
1021                                 owner->getDialogs().showSpellchecker();
1022
1023                         else if (name == "latexlog") {
1024                                 pair<Buffer::LogType, string> const logfile =
1025                                         owner->buffer()->getLogName();
1026                                 switch (logfile.first) {
1027                                 case Buffer::latexlog:
1028                                         data = "latex ";
1029                                         break;
1030                                 case Buffer::buildlog:
1031                                         data = "literate ";
1032                                         break;
1033                                 }
1034                                 data += logfile.second;
1035                                 owner->getDialogs().show("log", data);
1036                         }
1037                         else if (name == "vclog") {
1038                                 string const data = "vc " +
1039                                         owner->buffer()->lyxvc().getLogFile();
1040                                 owner->getDialogs().show("log", data);
1041                         }
1042                         else
1043                                 owner->getDialogs().show(name, data);
1044                         break;
1045                 }
1046
1047                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1048                         string const name = cmd.getArg(0);
1049                         string data = trim(cmd.argument.substr(name.size()));
1050                         if (name == "bibitem" ||
1051                             name == "bibtex" ||
1052                             name == "include" ||
1053                             name == "index" ||
1054                             name == "label" ||
1055                             name == "ref" ||
1056                             name == "toc" ||
1057                             name == "url") {
1058                                 InsetCommandParams p(name);
1059                                 data = InsetCommandMailer::params2string(name, p);
1060                         } else if (name == "box") {
1061                                 // \c data == "Boxed" || "Frameless" etc
1062                                 InsetBoxParams p(data);
1063                                 data = InsetBoxMailer::params2string(p);
1064                         } else if (name == "branch") {
1065                                 InsetBranchParams p;
1066                                 data = InsetBranchMailer::params2string(p);
1067                         } else if (name == "citation") {
1068                                 InsetCommandParams p("cite");
1069                                 data = InsetCommandMailer::params2string(name, p);
1070                         } else if (name == "ert") {
1071                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1072                         } else if (name == "external") {
1073                                 InsetExternalParams p;
1074                                 Buffer const & buffer = *owner->buffer();
1075                                 data = InsetExternalMailer::params2string(p, buffer);
1076                         } else if (name == "float") {
1077                                 InsetFloatParams p;
1078                                 data = InsetFloatMailer::params2string(p);
1079                         } else if (name == "graphics") {
1080                                 InsetGraphicsParams p;
1081                                 Buffer const & buffer = *owner->buffer();
1082                                 data = InsetGraphicsMailer::params2string(p, buffer);
1083                         } else if (name == "note") {
1084                                 InsetNoteParams p;
1085                                 data = InsetNoteMailer::params2string(p);
1086                         } else if (name == "vspace") {
1087                                 VSpace space;
1088                                 data = InsetVSpaceMailer::params2string(space);
1089                         } else if (name == "wrap") {
1090                                 InsetWrapParams p;
1091                                 data = InsetWrapMailer::params2string(p);
1092                         }
1093                         owner->getDialogs().show(name, data, 0);
1094                         break;
1095                 }
1096
1097                 case LFUN_DIALOG_SHOW_NEXT_INSET:
1098                         break;
1099
1100                 case LFUN_DIALOG_UPDATE: {
1101                         string const & name = argument;
1102                         // Can only update a dialog connected to an existing inset
1103                         InsetBase * inset = owner->getDialogs().getOpenInset(name);
1104                         if (inset) {
1105                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1106                                 inset->dispatch(view()->cursor(), fr);
1107                         } else if (name == "paragraph") {
1108                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1109                         }
1110                         break;
1111                 }
1112
1113                 case LFUN_DIALOG_HIDE:
1114                         Dialogs::hide(argument, 0);
1115                         break;
1116
1117                 case LFUN_DIALOG_DISCONNECT_INSET:
1118                         owner->getDialogs().disconnect(argument);
1119                         break;
1120
1121                 case LFUN_CHILDOPEN: {
1122                         string const filename =
1123                                 MakeAbsPath(argument, owner->buffer()->filePath());
1124                         setMessage(N_("Opening child document ") +
1125                                          MakeDisplayPath(filename) + "...");
1126                         view()->savePosition(0);
1127                         string const parentfilename = owner->buffer()->fileName();
1128                         if (bufferlist.exists(filename))
1129                                 view()->setBuffer(bufferlist.getBuffer(filename));
1130                         else
1131                                 view()->loadLyXFile(filename);
1132                         // Set the parent name of the child document.
1133                         // This makes insertion of citations and references in the child work,
1134                         // when the target is in the parent or another child document.
1135                         owner->buffer()->setParentName(parentfilename);
1136                         break;
1137                 }
1138
1139                 case LFUN_TOGGLECURSORFOLLOW:
1140                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1141                         break;
1142
1143                 case LFUN_KMAP_OFF:
1144                         owner->getIntl().KeyMapOn(false);
1145                         break;
1146
1147                 case LFUN_KMAP_PRIM:
1148                         owner->getIntl().KeyMapPrim();
1149                         break;
1150
1151                 case LFUN_KMAP_SEC:
1152                         owner->getIntl().KeyMapSec();
1153                         break;
1154
1155                 case LFUN_KMAP_TOGGLE:
1156                         owner->getIntl().ToggleKeyMap();
1157                         break;
1158
1159                 case LFUN_REPEAT: {
1160                         // repeat command
1161                         string countstr;
1162                         string rest = split(argument, countstr, ' ');
1163                         istringstream is(countstr);
1164                         int count = 0;
1165                         is >> count;
1166                         lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1167                         for (int i = 0; i < count; ++i)
1168                                 dispatch(lyxaction.lookupFunc(rest));
1169                         break;
1170                 }
1171
1172                 case LFUN_SEQUENCE:
1173                         // argument contains ';'-terminated commands
1174                         while (!argument.empty()) {
1175                                 string first;
1176                                 string rest = split(argument, first, ';');
1177                                 dispatch(lyxaction.lookupFunc(rest));
1178                         }
1179                         break;
1180
1181                 case LFUN_SAVEPREFERENCES: {
1182                         Path p(user_lyxdir());
1183                         lyxrc.write("preferences");
1184                         break;
1185                 }
1186
1187                 case LFUN_SCREEN_FONT_UPDATE:
1188                         // handle the screen font changes.
1189                         lyxrc.set_font_norm_type();
1190                         lyx_gui::update_fonts();
1191                         // All visible buffers will need resize
1192                         view()->resize();
1193                         break;
1194
1195                 case LFUN_SET_COLOR: {
1196                         string lyx_name;
1197                         string const x11_name = split(argument, lyx_name, ' ');
1198                         if (lyx_name.empty() || x11_name.empty()) {
1199                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1200                                                         " <x11_name>"));
1201                                 break;
1202                         }
1203
1204                         bool const graphicsbg_changed =
1205                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1206                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1207
1208                         if (!lcolor.setColor(lyx_name, x11_name)) {
1209                                 setErrorMessage(
1210                                         bformat(_("Set-color \"%1$s\" failed "
1211                                                                 "- color is undefined or "
1212                                                                 "may not be redefined"), lyx_name));
1213                                 break;
1214                         }
1215
1216                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1217
1218                         if (graphicsbg_changed) {
1219 #ifdef WITH_WARNINGS
1220 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1221 #endif
1222 #if 0
1223                                 lyx::graphics::GCache::get().changeDisplay(true);
1224 #endif
1225                         }
1226                         break;
1227                 }
1228
1229                 case LFUN_MESSAGE:
1230                         owner->message(argument);
1231                         break;
1232
1233                 case LFUN_TOOLTIPS_TOGGLE:
1234                         owner->getDialogs().toggleTooltips();
1235                         break;
1236
1237                 case LFUN_EXTERNAL_EDIT: {
1238                         FuncRequest fr(action, argument);
1239                         InsetExternal().dispatch(view()->cursor(), fr);
1240                         break;
1241                 }
1242
1243                 case LFUN_BREAKLINE: {
1244 #warning swallow 'Return' if the minibuffer is focused. But how?
1245                 }
1246
1247                 default: {
1248                         DispatchResult res = view()->cursor().dispatch(cmd);
1249                         if (!res.dispatched());
1250                                 view()->dispatch(cmd);
1251                         break;
1252                 }
1253                 }
1254
1255                 if (view()->available()) {
1256                         view()->fitCursor();
1257                         view()->update();
1258                         view()->cursor().updatePos();
1259                         // if we executed a mutating lfun, mark the buffer as dirty
1260                         if (getStatus(cmd).enabled()
1261                                         && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1262                                         && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1263                                 view()->buffer()->markDirty();
1264                 }
1265
1266                 if (view()->cursor().inTexted()) {
1267                         view()->owner()->updateLayoutChoice();
1268                         sendDispatchMessage(getMessage(), cmd, verbose);
1269                 }
1270         }
1271 }
1272
1273
1274 void LyXFunc::sendDispatchMessage(string const & msg,
1275                                   FuncRequest const & cmd, bool verbose)
1276 {
1277         owner->updateMenubar();
1278         owner->updateToolbar();
1279
1280         if (cmd.action == LFUN_SELFINSERT || !verbose) {
1281                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1282                 if (!msg.empty())
1283                         owner->message(msg);
1284                 return;
1285         }
1286
1287         string dispatch_msg = msg;
1288         if (!dispatch_msg.empty())
1289                 dispatch_msg += ' ';
1290
1291         string comname = lyxaction.getActionName(cmd.action);
1292
1293         bool argsadded = false;
1294
1295         if (!cmd.argument.empty()) {
1296                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1297                         comname += ' ' + cmd.argument;
1298                         argsadded = true;
1299                 }
1300         }
1301
1302         string const shortcuts = toplevel_keymap->findbinding(cmd);
1303
1304         if (!shortcuts.empty()) {
1305                 comname += ": " + shortcuts;
1306         } else if (!argsadded && !cmd.argument.empty()) {
1307                 comname += ' ' + cmd.argument;
1308         }
1309
1310         if (!comname.empty()) {
1311                 comname = rtrim(comname);
1312                 dispatch_msg += '(' + comname + ')';
1313         }
1314
1315         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1316         if (!dispatch_msg.empty())
1317                 owner->message(dispatch_msg);
1318 }
1319
1320
1321 void LyXFunc::setupLocalKeymap()
1322 {
1323         keyseq.stdmap = toplevel_keymap.get();
1324         keyseq.curmap = toplevel_keymap.get();
1325         cancel_meta_seq.stdmap = toplevel_keymap.get();
1326         cancel_meta_seq.curmap = toplevel_keymap.get();
1327 }
1328
1329
1330 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1331 {
1332         string initpath = lyxrc.document_path;
1333         string filename(name);
1334
1335         if (view()->available()) {
1336                 string const trypath = owner->buffer()->filePath();
1337                 // If directory is writeable, use this as default.
1338                 if (IsDirWriteable(trypath))
1339                         initpath = trypath;
1340         }
1341
1342         static int newfile_number;
1343
1344         if (filename.empty()) {
1345                 filename = AddName(lyxrc.document_path,
1346                             "newfile" + tostr(++newfile_number) + ".lyx");
1347                 FileInfo fi(filename);
1348                 while (bufferlist.exists(filename) || fi.readable()) {
1349                         ++newfile_number;
1350                         filename = AddName(lyxrc.document_path,
1351                                     "newfile" + tostr(newfile_number) +
1352                                     ".lyx");
1353                         fi.newFile(filename);
1354                 }
1355         }
1356
1357         // The template stuff
1358         string templname;
1359         if (fromTemplate) {
1360                 FileDialog fileDlg(_("Select template file"),
1361                         LFUN_SELECT_FILE_SYNC,
1362                         make_pair(string(_("Documents|#o#O")),
1363                                   string(lyxrc.document_path)),
1364                         make_pair(string(_("Templates|#T#t")),
1365                                   string(lyxrc.template_path)));
1366
1367                 FileDialog::Result result =
1368                         fileDlg.open(lyxrc.template_path,
1369                                      FileFilterList(_("LyX Documents (*.lyx)")),
1370                                      string());
1371
1372                 if (result.first == FileDialog::Later)
1373                         return;
1374                 if (result.second.empty())
1375                         return;
1376                 templname = result.second;
1377         }
1378
1379         view()->newFile(filename, templname, !name.empty());
1380 }
1381
1382
1383 void LyXFunc::open(string const & fname)
1384 {
1385         string initpath = lyxrc.document_path;
1386
1387         if (view()->available()) {
1388                 string const trypath = owner->buffer()->filePath();
1389                 // If directory is writeable, use this as default.
1390                 if (IsDirWriteable(trypath))
1391                         initpath = trypath;
1392         }
1393
1394         string filename;
1395
1396         if (fname.empty()) {
1397                 FileDialog fileDlg(_("Select document to open"),
1398                         LFUN_FILE_OPEN,
1399                         make_pair(string(_("Documents|#o#O")),
1400                                   string(lyxrc.document_path)),
1401                         make_pair(string(_("Examples|#E#e")),
1402                                   string(AddPath(system_lyxdir(), "examples"))));
1403
1404                 FileDialog::Result result =
1405                         fileDlg.open(initpath,
1406                                      FileFilterList(_("LyX Documents (*.lyx)")),
1407                                      string());
1408
1409                 if (result.first == FileDialog::Later)
1410                         return;
1411
1412                 filename = result.second;
1413
1414                 // check selected filename
1415                 if (filename.empty()) {
1416                         owner->message(_("Canceled."));
1417                         return;
1418                 }
1419         } else
1420                 filename = fname;
1421
1422         // get absolute path of file and add ".lyx" to the filename if
1423         // necessary
1424         string const fullpath = FileSearch(string(), filename, "lyx");
1425         if (!fullpath.empty()) {
1426                 filename = fullpath;
1427         }
1428
1429         string const disp_fn(MakeDisplayPath(filename));
1430
1431         // if the file doesn't exist, let the user create one
1432         FileInfo const f(filename, true);
1433         if (!f.exist()) {
1434                 // the user specifically chose this name. Believe them.
1435                 view()->newFile(filename, "", true);
1436                 return;
1437         }
1438
1439         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1440
1441         string str2;
1442         if (view()->loadLyXFile(filename)) {
1443                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1444         } else {
1445                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1446         }
1447         owner->message(str2);
1448 }
1449
1450
1451 void LyXFunc::doImport(string const & argument)
1452 {
1453         string format;
1454         string filename = split(argument, format, ' ');
1455
1456         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1457                             << " file: " << filename << endl;
1458
1459         // need user interaction
1460         if (filename.empty()) {
1461                 string initpath = lyxrc.document_path;
1462
1463                 if (view()->available()) {
1464                         string const trypath = owner->buffer()->filePath();
1465                         // If directory is writeable, use this as default.
1466                         if (IsDirWriteable(trypath))
1467                                 initpath = trypath;
1468                 }
1469
1470                 string const text = bformat(_("Select %1$s file to import"),
1471                         formats.prettyName(format));
1472
1473                 FileDialog fileDlg(text,
1474                         LFUN_IMPORT,
1475                         make_pair(string(_("Documents|#o#O")),
1476                                   string(lyxrc.document_path)),
1477                         make_pair(string(_("Examples|#E#e")),
1478                                   string(AddPath(system_lyxdir(), "examples"))));
1479
1480                 string const filter = formats.prettyName(format)
1481                         + " (*." + formats.extension(format) + ')';
1482
1483                 FileDialog::Result result =
1484                         fileDlg.open(initpath,
1485                                      FileFilterList(filter),
1486                                      string());
1487
1488                 if (result.first == FileDialog::Later)
1489                         return;
1490
1491                 filename = result.second;
1492
1493                 // check selected filename
1494                 if (filename.empty())
1495                         owner->message(_("Canceled."));
1496         }
1497
1498         if (filename.empty())
1499                 return;
1500
1501         // get absolute path of file
1502         filename = MakeAbsPath(filename);
1503
1504         string const lyxfile = ChangeExtension(filename, ".lyx");
1505
1506         // Check if the document already is open
1507         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1508                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1509                         owner->message(_("Canceled."));
1510                         return;
1511                 }
1512         }
1513
1514         // if the file exists already, and we didn't do
1515         // -i lyx thefile.lyx, warn
1516         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1517                 string const file = MakeDisplayPath(lyxfile, 30);
1518
1519                 string text = bformat(_("The document %1$s already exists.\n\n"
1520                         "Do you want to over-write that document?"), file);
1521                 int const ret = Alert::prompt(_("Over-write document?"),
1522                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1523
1524                 if (ret == 1) {
1525                         owner->message(_("Canceled."));
1526                         return;
1527                 }
1528         }
1529
1530         Importer::Import(owner, filename, format);
1531 }
1532
1533
1534 void LyXFunc::closeBuffer()
1535 {
1536         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1537                 if (bufferlist.empty()) {
1538                         // need this otherwise SEGV may occur while
1539                         // trying to set variables that don't exist
1540                         // since there's no current buffer
1541                         owner->getDialogs().hideBufferDependent();
1542                 } else {
1543                         view()->setBuffer(bufferlist.first());
1544                 }
1545         }
1546 }
1547
1548
1549 // Each "owner" should have it's own message method. lyxview and
1550 // the minibuffer would use the minibuffer, but lyxserver would
1551 // send an ERROR signal to its client.  Alejandro 970603
1552 // This function is bit problematic when it comes to NLS, to make the
1553 // lyx servers client be language indepenent we must not translate
1554 // strings sent to this func.
1555 void LyXFunc::setErrorMessage(string const & m) const
1556 {
1557         dispatch_buffer = m;
1558         errorstat = true;
1559 }
1560
1561
1562 void LyXFunc::setMessage(string const & m) const
1563 {
1564         dispatch_buffer = m;
1565 }
1566
1567
1568 void LyXFunc::setStatusMessage(string const & m) const
1569 {
1570         status_buffer = m;
1571 }
1572
1573
1574 string const LyXFunc::viewStatusMessage()
1575 {
1576         // When meta-fake key is pressed, show the key sequence so far + "M-".
1577         if (wasMetaKey())
1578                 return keyseq.print() + "M-";
1579
1580         // Else, when a non-complete key sequence is pressed,
1581         // show the available options.
1582         if (keyseq.length() > 0 && !keyseq.deleted())
1583                 return keyseq.printOptions();
1584
1585         if (!view()->available())
1586                 return _("Welcome to LyX!");
1587
1588         return view()->cursor().currentState();
1589 }
1590
1591
1592 BufferView * LyXFunc::view() const
1593 {
1594         BOOST_ASSERT(owner);
1595         return owner->view().get();
1596 }
1597
1598
1599 bool LyXFunc::wasMetaKey() const
1600 {
1601         return (meta_fake_bit != key_modifier::none);
1602 }