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