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