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