]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
fix crash after removing a table row (again due to uncorrected cursor
[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         case LFUN_NEXTBUFFER:
507         case LFUN_PREVIOUSBUFFER:
508                 // these are handled in our dispatch()
509                 break;
510
511         default:
512
513                 cur.getStatus(cmd, flag);
514                 if (!flag.enabled())
515                         flag = view()->getStatus(cmd);
516         }
517
518         if (!enable)
519                 flag.enabled(false);
520
521         // Can we use a readonly buffer?
522         if (buf && buf->isReadonly()
523             && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly)
524             && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)) {
525                 setStatusMessage(N_("Document is read-only"));
526                 flag.enabled(false);
527         }
528
529         //lyxerr << "LyXFunc::getStatus: got: " << flag.enabled() << endl;
530         return flag;
531 }
532
533
534 namespace {
535
536 bool ensureBufferClean(BufferView * bv)
537 {
538         Buffer & buf = *bv->buffer();
539         if (buf.isClean())
540                 return true;
541
542         string const file = MakeDisplayPath(buf.fileName(), 30);
543         string text = bformat(_("The document %1$s has unsaved "
544                                 "changes.\n\nDo you want to save "
545                                 "the document?"), file);
546         int const ret = Alert::prompt(_("Save changed document?"),
547                                       text, 0, 1, _("&Save"),
548                                       _("&Cancel"));
549
550         if (ret == 0)
551                 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
552
553         return buf.isClean();
554 }
555
556
557 void showPrintError(string const & name)
558 {
559         string str = bformat(_("Could not print the document %1$s.\n"
560                                "Check that your printer is set up correctly."),
561                              MakeDisplayPath(name, 50));
562         Alert::error(_("Print document failed"), str);
563 }
564
565
566 void loadTextclass(string const & name)
567 {
568         std::pair<bool, lyx::textclass_type> const tc_pair =
569                 textclasslist.NumberOfClass(name);
570
571         if (!tc_pair.first) {
572                 lyxerr << "Document class \"" << name
573                        << "\" does not exist."
574                        << std::endl;
575                 return;
576         }
577
578         lyx::textclass_type const tc = tc_pair.second;
579
580         if (!textclasslist[tc].load()) {
581                 string s = bformat(_("The document could not be converted\n"
582                                      "into the document class %1$s."),
583                                    textclasslist[tc].name());
584                 Alert::error(_("Could not change class"), s);
585         }
586 }
587
588 } //namespace anon
589
590
591 void LyXFunc::dispatch(FuncRequest const & cmd, bool verbose)
592 {
593         string const argument = cmd.argument;
594         kb_action const action = cmd.action;
595
596         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << cmd << endl;
597         //lyxerr << "LyXFunc::dispatch: cmd: " << cmd << endl;
598
599         // we have not done anything wrong yet.
600         errorstat = false;
601         dispatch_buffer.erase();
602         selection_possible = false;
603
604         bool update = true;
605
606         // We cannot use this function here
607         if (!getStatus(cmd).enabled()) {
608                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
609                        << lyxaction.getActionName(action)
610                        << " [" << action << "] is disabled at this location"
611                        << endl;
612                 setErrorMessage(getStatusMessage());
613
614         } else {
615
616                 if (view()->available())
617                         view()->hideCursor();
618
619                 switch (action) {
620
621                 case LFUN_WORDFINDFORWARD:
622                 case LFUN_WORDFINDBACKWARD: {
623                         static string last_search;
624                         string searched_string;
625
626                         if (!argument.empty()) {
627                                 last_search = argument;
628                                 searched_string = argument;
629                         } else {
630                                 searched_string = last_search;
631                         }
632
633                         if (searched_string.empty())
634                                 break;
635
636                         bool const fw = action == LFUN_WORDFINDFORWARD;
637                         string const data =
638                                 lyx::find::find2string(searched_string, true, false, fw);
639                         lyx::find::find(view(), FuncRequest(LFUN_WORD_FIND, data));
640                         break;
641                 }
642
643                 case LFUN_PREFIX:
644                         owner->message(keyseq.printOptions());
645                         break;
646
647                 case LFUN_EXEC_COMMAND:
648                         owner->getToolbars().display("minibuffer", true);
649                         owner->focus_command_buffer();
650                         break;
651
652                 case LFUN_CANCEL:
653                         keyseq.reset();
654                         meta_fake_bit = key_modifier::none;
655                         if (view()->available())
656                                 // cancel any selection
657                                 dispatch(FuncRequest(LFUN_MARK_OFF));
658                         setMessage(N_("Cancel"));
659                         break;
660
661                 case LFUN_META_FAKE:
662                         meta_fake_bit = key_modifier::alt;
663                         setMessage(keyseq.print());
664                         break;
665
666                 case LFUN_READ_ONLY_TOGGLE:
667                         if (owner->buffer()->lyxvc().inUse())
668                                 owner->buffer()->lyxvc().toggleReadOnly();
669                         else
670                                 owner->buffer()->setReadonly(
671                                         !owner->buffer()->isReadonly());
672                         break;
673
674                 // --- Menus -----------------------------------------------
675                 case LFUN_MENUNEW:
676                         menuNew(argument, false);
677                         break;
678
679                 case LFUN_MENUNEWTMPLT:
680                         menuNew(argument, true);
681                         break;
682
683                 case LFUN_CLOSEBUFFER:
684                         closeBuffer();
685                         break;
686
687                 case LFUN_MENUWRITE:
688                         if (!owner->buffer()->isUnnamed()) {
689                                 string const str = bformat(_("Saving document %1$s..."),
690                                          MakeDisplayPath(owner->buffer()->fileName()));
691                                 owner->message(str);
692                                 MenuWrite(owner->buffer());
693                                 owner->message(str + _(" done."));
694                         } else
695                                 WriteAs(owner->buffer());
696                         break;
697
698                 case LFUN_WRITEAS:
699                         WriteAs(owner->buffer(), argument);
700                         break;
701
702                 case LFUN_MENURELOAD: {
703                         string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
704                         string text = bformat(_("Any changes will be lost. Are you sure "
705                                 "you want to revert to the saved version of the document %1$s?"), file);
706                         int const ret = Alert::prompt(_("Revert to saved document?"),
707                                 text, 0, 1, _("&Revert"), _("&Cancel"));
708
709                         if (ret == 0)
710                                 view()->reload();
711                         break;
712                 }
713
714                 case LFUN_UPDATE:
715                         Exporter::Export(owner->buffer(), argument, true);
716                         view()->showErrorList(BufferFormat(*owner->buffer()));
717                         break;
718
719                 case LFUN_PREVIEW:
720                         Exporter::Preview(owner->buffer(), argument);
721                         view()->showErrorList(BufferFormat(*owner->buffer()));
722                         break;
723
724                 case LFUN_BUILDPROG:
725                         Exporter::Export(owner->buffer(), "program", true);
726                         view()->showErrorList(_("Build"));
727                         break;
728
729                 case LFUN_RUNCHKTEX:
730                         owner->buffer()->runChktex();
731                         view()->showErrorList(_("ChkTeX"));
732                         break;
733
734                 case LFUN_EXPORT:
735                         if (argument == "custom")
736                                 owner->getDialogs().show("sendto");
737                         else {
738                                 Exporter::Export(owner->buffer(), argument, false);
739                                 view()->showErrorList(BufferFormat(*owner->buffer()));
740                         }
741                         break;
742
743                 case LFUN_EXPORT_CUSTOM: {
744                         string format_name;
745                         string command = split(argument, format_name, ' ');
746                         Format const * format = formats.getFormat(format_name);
747                         if (!format) {
748                                 lyxerr << "Format \"" << format_name
749                                        << "\" not recognized!"
750                                        << std::endl;
751                                 break;
752                         }
753
754                         Buffer * buffer = owner->buffer();
755
756                         // The name of the file created by the conversion process
757                         string filename;
758
759                         // Output to filename
760                         if (format->name() == "lyx") {
761                                 string const latexname =
762                                         buffer->getLatexName(false);
763                                 filename = ChangeExtension(latexname,
764                                                            format->extension());
765                                 filename = AddName(buffer->temppath(), filename);
766
767                                 if (!buffer->writeFile(filename))
768                                         break;
769
770                         } else {
771                                 Exporter::Export(buffer, format_name, true,
772                                                  filename);
773                         }
774
775                         // Substitute $$FName for filename
776                         if (!contains(command, "$$FName"))
777                                 command = "( " + command + " ) < $$FName";
778                         command = subst(command, "$$FName", filename);
779
780                         // Execute the command in the background
781                         Systemcall call;
782                         call.startscript(Systemcall::DontWait, command);
783                         break;
784                 }
785
786                 case LFUN_PRINT: {
787                         string target;
788                         string target_name;
789                         string command = split(split(argument, target, ' '),
790                                                target_name, ' ');
791
792                         if (target.empty()
793                             || target_name.empty()
794                             || command.empty()) {
795                                 lyxerr << "Unable to parse \""
796                                        << argument << '"' << std::endl;
797                                 break;
798                         }
799                         if (target != "printer" && target != "file") {
800                                 lyxerr << "Unrecognized target \""
801                                        << target << '"' << std::endl;
802                                 break;
803                         }
804
805                         Buffer * buffer = owner->buffer();
806
807                         if (!Exporter::Export(buffer, "dvi", true)) {
808                                 showPrintError(buffer->fileName());
809                                 break;
810                         }
811
812                         // Push directory path.
813                         string const path = buffer->temppath();
814                         Path p(path);
815
816                         // there are three cases here:
817                         // 1. we print to a file
818                         // 2. we print directly to a printer
819                         // 3. we print using a spool command (print to file first)
820                         Systemcall one;
821                         int res = 0;
822                         string const dviname =
823                                 ChangeExtension(buffer->getLatexName(true),
824                                                 "dvi");
825
826                         if (target == "printer") {
827                                 if (!lyxrc.print_spool_command.empty()) {
828                                         // case 3: print using a spool
829                                         string const psname =
830                                                 ChangeExtension(dviname,".ps");
831                                         command += lyxrc.print_to_file
832                                                 + QuoteName(psname)
833                                                 + ' '
834                                                 + QuoteName(dviname);
835
836                                         string command2 =
837                                                 lyxrc.print_spool_command +' ';
838                                         if (target_name != "default") {
839                                                 command2 += lyxrc.print_spool_printerprefix
840                                                         + target_name
841                                                         + ' ';
842                                         }
843                                         command2 += QuoteName(psname);
844                                         // First run dvips.
845                                         // If successful, then spool command
846                                         res = one.startscript(
847                                                 Systemcall::Wait,
848                                                 command);
849
850                                         if (res == 0)
851                                                 res = one.startscript(
852                                                         Systemcall::DontWait,
853                                                         command2);
854                                 } else {
855                                         // case 2: print directly to a printer
856                                         res = one.startscript(
857                                                 Systemcall::DontWait,
858                                                 command + QuoteName(dviname));
859                                 }
860
861                         } else {
862                                 // case 1: print to a file
863                                 command += lyxrc.print_to_file
864                                         + QuoteName(MakeAbsPath(target_name,
865                                                                 path))
866                                         + ' '
867                                         + QuoteName(dviname);
868                                 res = one.startscript(Systemcall::DontWait,
869                                                       command);
870                         }
871
872                         if (res != 0)
873                                 showPrintError(buffer->fileName());
874                         break;
875                 }
876
877                 case LFUN_IMPORT:
878                         doImport(argument);
879                         break;
880
881                 case LFUN_QUIT:
882                         QuitLyX();
883                         break;
884
885                 case LFUN_TOCVIEW: {
886                         InsetCommandParams p("tableofcontents");
887                         string const data = InsetCommandMailer::params2string("toc", p);
888                         owner->getDialogs().show("toc", data, 0);
889                         break;
890                 }
891
892                 case LFUN_AUTOSAVE:
893                         AutoSave(view());
894                         break;
895
896                 case LFUN_RECONFIGURE:
897                         Reconfigure(view());
898                         break;
899
900                 case LFUN_HELP_OPEN: {
901                         string const arg = argument;
902                         if (arg.empty()) {
903                                 setErrorMessage(N_("Missing argument"));
904                                 break;
905                         }
906                         string const fname = i18nLibFileSearch("doc", arg, "lyx");
907                         if (fname.empty()) {
908                                 lyxerr << "LyX: unable to find documentation file `"
909                                                          << arg << "'. Bad installation?" << endl;
910                                 break;
911                         }
912                         owner->message(bformat(_("Opening help file %1$s..."),
913                                 MakeDisplayPath(fname)));
914                         view()->loadLyXFile(fname, false);
915                         break;
916                 }
917
918                 // --- version control -------------------------------
919                 case LFUN_VC_REGISTER:
920                         if (!ensureBufferClean(view()))
921                                 break;
922                         if (!owner->buffer()->lyxvc().inUse()) {
923                                 owner->buffer()->lyxvc().registrer();
924                                 view()->reload();
925                         }
926                         break;
927
928                 case LFUN_VC_CHECKIN:
929                         if (!ensureBufferClean(view()))
930                                 break;
931                         if (owner->buffer()->lyxvc().inUse()
932                                         && !owner->buffer()->isReadonly()) {
933                                 owner->buffer()->lyxvc().checkIn();
934                                 view()->reload();
935                         }
936                         break;
937
938                 case LFUN_VC_CHECKOUT:
939                         if (!ensureBufferClean(view()))
940                                 break;
941                         if (owner->buffer()->lyxvc().inUse()
942                                         && owner->buffer()->isReadonly()) {
943                                 owner->buffer()->lyxvc().checkOut();
944                                 view()->reload();
945                         }
946                         break;
947
948                 case LFUN_VC_REVERT:
949                         owner->buffer()->lyxvc().revert();
950                         view()->reload();
951                         break;
952
953                 case LFUN_VC_UNDO:
954                         owner->buffer()->lyxvc().undoLast();
955                         view()->reload();
956                         break;
957
958                 // --- buffers ----------------------------------------
959                 case LFUN_SWITCHBUFFER:
960                         view()->setBuffer(bufferlist.getBuffer(argument));
961                         break;
962
963                 case LFUN_NEXTBUFFER:
964                         view()->setBuffer(bufferlist.next(view()->buffer()));
965                         break;
966
967                 case LFUN_PREVIOUSBUFFER:
968                         view()->setBuffer(bufferlist.previous(view()->buffer()));
969                         break;
970
971                 case LFUN_FILE_NEW:
972                         NewFile(view(), argument);
973                         break;
974
975                 case LFUN_FILE_OPEN:
976                         open(argument);
977                         break;
978
979                 case LFUN_DROP_LAYOUTS_CHOICE:
980                         owner->getToolbars().openLayoutList();
981                         break;
982
983                 case LFUN_MENU_OPEN_BY_NAME:
984                         owner->getMenubar().openByName(argument);
985                         break;
986
987                 // --- lyxserver commands ----------------------------
988                 case LFUN_GETNAME:
989                         setMessage(owner->buffer()->fileName());
990                         lyxerr[Debug::INFO] << "FNAME["
991                                                          << owner->buffer()->fileName()
992                                                          << "] " << endl;
993                         break;
994
995                 case LFUN_NOTIFY:
996                         dispatch_buffer = keyseq.print();
997                         lyxserver->notifyClient(dispatch_buffer);
998                         break;
999
1000                 case LFUN_GOTOFILEROW: {
1001                         string file_name;
1002                         int row;
1003                         istringstream is(argument);
1004                         is >> file_name >> row;
1005                         if (prefixIs(file_name, getTmpDir())) {
1006                                 // Needed by inverse dvi search. If it is a file
1007                                 // in tmpdir, call the apropriated function
1008                                 view()->setBuffer(bufferlist.getBufferFromTmp(file_name));
1009                         } else {
1010                                 // Must replace extension of the file to be .lyx
1011                                 // and get full path
1012                                 string const s = ChangeExtension(file_name, ".lyx");
1013                                 // Either change buffer or load the file
1014                                 if (bufferlist.exists(s)) {
1015                                         view()->setBuffer(bufferlist.getBuffer(s));
1016                                 } else {
1017                                         view()->loadLyXFile(s);
1018                                 }
1019                         }
1020
1021                         view()->setCursorFromRow(row);
1022
1023                         view()->center();
1024                         // see BufferView_pimpl::center()
1025                         view()->updateScrollbar();
1026                         break;
1027                 }
1028
1029                 case LFUN_GOTO_PARAGRAPH: {
1030                         istringstream is(argument);
1031                         int id;
1032                         is >> id;
1033                         ParIterator par = owner->buffer()->getParFromID(id);
1034                         if (par == owner->buffer()->par_iterator_end()) {
1035                                 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1036                                                                 << id << ']' << endl;
1037                                 break;
1038                         } else {
1039                                 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1040                                                                 << " found." << endl;
1041                         }
1042
1043                         // Set the cursor
1044                         view()->setCursor(par, 0);
1045
1046                         view()->switchKeyMap();
1047                         owner->view_state_changed();
1048
1049                         view()->center();
1050                         // see BufferView_pimpl::center()
1051                         view()->updateScrollbar();
1052                         break;
1053                 }
1054
1055                 case LFUN_DIALOG_SHOW: {
1056                         string const name = cmd.getArg(0);
1057                         string data = trim(cmd.argument.substr(name.size()));
1058
1059                         if (name == "character") {
1060                                 data = freefont2string();
1061                                 if (!data.empty())
1062                                         owner->getDialogs().show("character", data);
1063                         }
1064
1065                         else if (name == "latexlog") {
1066                                 pair<Buffer::LogType, string> const logfile =
1067                                         owner->buffer()->getLogName();
1068                                 switch (logfile.first) {
1069                                 case Buffer::latexlog:
1070                                         data = "latex ";
1071                                         break;
1072                                 case Buffer::buildlog:
1073                                         data = "literate ";
1074                                         break;
1075                                 }
1076                                 data += logfile.second;
1077                                 owner->getDialogs().show("log", data);
1078                         }
1079                         else if (name == "vclog") {
1080                                 string const data = "vc " +
1081                                         owner->buffer()->lyxvc().getLogFile();
1082                                 owner->getDialogs().show("log", data);
1083                         }
1084                         else
1085                                 owner->getDialogs().show(name, data);
1086                         break;
1087                 }
1088
1089                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1090                         string const name = cmd.getArg(0);
1091                         string data = trim(cmd.argument.substr(name.size()));
1092                         if (name == "bibitem" ||
1093                             name == "bibtex" ||
1094                             name == "include" ||
1095                             name == "index" ||
1096                             name == "label" ||
1097                             name == "ref" ||
1098                             name == "toc" ||
1099                             name == "url") {
1100                                 InsetCommandParams p(name);
1101                                 data = InsetCommandMailer::params2string(name, p);
1102                         } else if (name == "box") {
1103                                 // \c data == "Boxed" || "Frameless" etc
1104                                 InsetBoxParams p(data);
1105                                 data = InsetBoxMailer::params2string(p);
1106                         } else if (name == "branch") {
1107                                 InsetBranchParams p;
1108                                 data = InsetBranchMailer::params2string(p);
1109                         } else if (name == "citation") {
1110                                 InsetCommandParams p("cite");
1111                                 data = InsetCommandMailer::params2string(name, p);
1112                         } else if (name == "ert") {
1113                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1114                         } else if (name == "external") {
1115                                 InsetExternalParams p;
1116                                 Buffer const & buffer = *owner->buffer();
1117                                 data = InsetExternalMailer::params2string(p, buffer);
1118                         } else if (name == "float") {
1119                                 InsetFloatParams p;
1120                                 data = InsetFloatMailer::params2string(p);
1121                         } else if (name == "graphics") {
1122                                 InsetGraphicsParams p;
1123                                 Buffer const & buffer = *owner->buffer();
1124                                 data = InsetGraphicsMailer::params2string(p, buffer);
1125                         } else if (name == "note") {
1126                                 InsetNoteParams p;
1127                                 data = InsetNoteMailer::params2string(p);
1128                         } else if (name == "vspace") {
1129                                 VSpace space;
1130                                 data = InsetVSpaceMailer::params2string(space);
1131                         } else if (name == "wrap") {
1132                                 InsetWrapParams p;
1133                                 data = InsetWrapMailer::params2string(p);
1134                         }
1135                         owner->getDialogs().show(name, data, 0);
1136                         break;
1137                 }
1138
1139                 case LFUN_DIALOG_SHOW_NEXT_INSET:
1140                         break;
1141
1142                 case LFUN_DIALOG_UPDATE: {
1143                         string const & name = argument;
1144                         // Can only update a dialog connected to an existing inset
1145                         InsetBase * inset = owner->getDialogs().getOpenInset(name);
1146                         if (inset) {
1147                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1148                                 inset->dispatch(view()->cursor(), fr);
1149                         } else if (name == "paragraph") {
1150                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1151                         } else if (name == "prefs") {
1152                                 owner->getDialogs().update(name, string());
1153                         }
1154                         break;
1155                 }
1156
1157                 case LFUN_DIALOG_HIDE:
1158                         Dialogs::hide(argument, 0);
1159                         break;
1160
1161                 case LFUN_DIALOG_DISCONNECT_INSET:
1162                         owner->getDialogs().disconnect(argument);
1163                         break;
1164
1165                 case LFUN_CHILDOPEN: {
1166                         string const filename =
1167                                 MakeAbsPath(argument, owner->buffer()->filePath());
1168                         setMessage(N_("Opening child document ") +
1169                                          MakeDisplayPath(filename) + "...");
1170                         view()->savePosition(0);
1171                         string const parentfilename = owner->buffer()->fileName();
1172                         if (bufferlist.exists(filename))
1173                                 view()->setBuffer(bufferlist.getBuffer(filename));
1174                         else
1175                                 view()->loadLyXFile(filename);
1176                         // Set the parent name of the child document.
1177                         // This makes insertion of citations and references in the child work,
1178                         // when the target is in the parent or another child document.
1179                         owner->buffer()->setParentName(parentfilename);
1180                         break;
1181                 }
1182
1183                 case LFUN_TOGGLECURSORFOLLOW:
1184                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1185                         break;
1186
1187                 case LFUN_KMAP_OFF:
1188                         owner->getIntl().KeyMapOn(false);
1189                         break;
1190
1191                 case LFUN_KMAP_PRIM:
1192                         owner->getIntl().KeyMapPrim();
1193                         break;
1194
1195                 case LFUN_KMAP_SEC:
1196                         owner->getIntl().KeyMapSec();
1197                         break;
1198
1199                 case LFUN_KMAP_TOGGLE:
1200                         owner->getIntl().ToggleKeyMap();
1201                         break;
1202
1203                 case LFUN_REPEAT: {
1204                         // repeat command
1205                         string countstr;
1206                         string rest = split(argument, countstr, ' ');
1207                         istringstream is(countstr);
1208                         int count = 0;
1209                         is >> count;
1210                         lyxerr << "repeat: count: " << count << " cmd: " << rest << endl;
1211                         for (int i = 0; i < count; ++i)
1212                                 dispatch(lyxaction.lookupFunc(rest));
1213                         break;
1214                 }
1215
1216                 case LFUN_SEQUENCE: {
1217                         // argument contains ';'-terminated commands
1218                         string arg = argument;
1219                         while (!arg.empty()) {
1220                                 string first;
1221                                 arg = split(arg, first, ';');
1222                                 dispatch(lyxaction.lookupFunc(first));
1223                         }
1224                         break;
1225                 }
1226
1227                 case LFUN_SAVEPREFERENCES: {
1228                         Path p(user_lyxdir());
1229                         lyxrc.write("preferences", false);
1230                         break;
1231                 }
1232
1233                 case LFUN_SCREEN_FONT_UPDATE:
1234                         // handle the screen font changes.
1235                         lyxrc.set_font_norm_type();
1236                         lyx_gui::update_fonts();
1237                         // All visible buffers will need resize
1238                         view()->resize();
1239                         break;
1240
1241                 case LFUN_SET_COLOR: {
1242                         string lyx_name;
1243                         string const x11_name = split(argument, lyx_name, ' ');
1244                         if (lyx_name.empty() || x11_name.empty()) {
1245                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1246                                                         " <x11_name>"));
1247                                 break;
1248                         }
1249
1250                         bool const graphicsbg_changed =
1251                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1252                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1253
1254                         if (!lcolor.setColor(lyx_name, x11_name)) {
1255                                 setErrorMessage(
1256                                         bformat(_("Set-color \"%1$s\" failed "
1257                                                                 "- color is undefined or "
1258                                                                 "may not be redefined"), lyx_name));
1259                                 break;
1260                         }
1261
1262                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1263
1264                         if (graphicsbg_changed) {
1265 #ifdef WITH_WARNINGS
1266 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1267 #endif
1268 #if 0
1269                                 lyx::graphics::GCache::get().changeDisplay(true);
1270 #endif
1271                         }
1272                         break;
1273                 }
1274
1275                 case LFUN_MESSAGE:
1276                         owner->message(argument);
1277                         break;
1278
1279                 case LFUN_TOOLTIPS_TOGGLE:
1280                         owner->getDialogs().toggleTooltips();
1281                         break;
1282
1283                 case LFUN_EXTERNAL_EDIT: {
1284                         FuncRequest fr(action, argument);
1285                         InsetExternal().dispatch(view()->cursor(), fr);
1286                         break;
1287                 }
1288
1289                 case LFUN_GRAPHICS_EDIT: {
1290                         FuncRequest fr(action, argument);
1291                         InsetGraphics().dispatch(view()->cursor(), fr);
1292                         break;
1293                 }
1294
1295                 case LFUN_ALL_INSETS_TOGGLE: {
1296                         string action;
1297                         string const name = split(argument, action, ' ');
1298                         InsetBase::Code const inset_code =
1299                                 InsetBase::translate(name);
1300
1301                         LCursor & cur = view()->cursor();
1302                         FuncRequest fr(LFUN_INSET_TOGGLE, action);
1303
1304                         InsetBase & inset = owner->buffer()->inset();
1305                         InsetIterator it  = inset_iterator_begin(inset);
1306                         InsetIterator const end = inset_iterator_end(inset);
1307                         for (; it != end; ++it) {
1308                                 if (inset_code == InsetBase::NO_CODE
1309                                     || inset_code == it->lyxCode())
1310                                         it->dispatch(cur, fr);
1311                         }
1312                         break;
1313                 }
1314
1315                 case LFUN_LANGUAGE_BUFFER: {
1316                         Buffer & buffer = *owner->buffer();
1317                         Language const * oldL = buffer.params().language;
1318                         Language const * newL = languages.getLanguage(argument);
1319                         if (!newL || oldL == newL)
1320                                 break;
1321
1322                         if (oldL->RightToLeft() == newL->RightToLeft()
1323                             && !buffer.isMultiLingual())
1324                                 buffer.changeLanguage(oldL, newL);
1325                         else
1326                                 buffer.updateDocLang(newL);
1327                         break;
1328                 }
1329
1330                 case LFUN_SAVE_AS_DEFAULT: {
1331                         string const fname =
1332                                 AddName(AddPath(user_lyxdir(), "templates/"),
1333                                         "defaults.lyx");
1334                         Buffer defaults(fname);
1335
1336                         istringstream ss(argument);
1337                         LyXLex lex(0,0);
1338                         lex.setStream(ss);
1339                         int const unknown_tokens = defaults.readHeader(lex);
1340
1341                         if (unknown_tokens != 0) {
1342                                 lyxerr << "Warning in LFUN_SAVE_AS_DEFAULT!\n"
1343                                        << unknown_tokens << " unknown token"
1344                                        << (unknown_tokens == 1 ? "" : "s")
1345                                        << endl;
1346                         }
1347
1348                         if (defaults.writeFile(defaults.fileName()))
1349                                 setMessage(_("Document defaults saved in ")
1350                                            + MakeDisplayPath(fname));
1351                         else
1352                                 setErrorMessage(_("Unable to save document defaults"));
1353                         break;
1354                 }
1355
1356                 case LFUN_BUFFERPARAMS_APPLY: {
1357                         biblio::CiteEngine const engine =
1358                                 owner->buffer()->params().cite_engine;
1359
1360                         istringstream ss(argument);
1361                         LyXLex lex(0,0);
1362                         lex.setStream(ss);
1363                         int const unknown_tokens =
1364                                 owner->buffer()->readHeader(lex);
1365
1366                         if (unknown_tokens != 0) {
1367                                 lyxerr << "Warning in LFUN_BUFFERPARAMS_APPLY!\n"
1368                                        << unknown_tokens << " unknown token"
1369                                        << (unknown_tokens == 1 ? "" : "s")
1370                                        << endl;
1371                         }
1372                         if (engine == owner->buffer()->params().cite_engine)
1373                                 break;
1374
1375                         LCursor & cur = view()->cursor();
1376                         FuncRequest fr(LFUN_INSET_REFRESH);
1377
1378                         InsetBase & inset = owner->buffer()->inset();
1379                         InsetIterator it  = inset_iterator_begin(inset);
1380                         InsetIterator const end = inset_iterator_end(inset);
1381                         for (; it != end; ++it)
1382                                 if (it->lyxCode() == InsetBase::CITE_CODE)
1383                                         it->dispatch(cur, fr);
1384                         break;
1385                 }
1386
1387                 case LFUN_TEXTCLASS_APPLY: {
1388                         Buffer * buffer = owner->buffer();
1389
1390                         lyx::textclass_type const old_class =
1391                                 buffer->params().textclass;
1392
1393                         loadTextclass(argument);
1394
1395                         std::pair<bool, lyx::textclass_type> const tc_pair =
1396                                 textclasslist.NumberOfClass(argument);
1397
1398                         if (!tc_pair.first)
1399                                 break;
1400
1401                         lyx::textclass_type const new_class = tc_pair.second;
1402                         if (old_class == new_class)
1403                                 // nothing to do
1404                                 break;
1405
1406                         owner->message(_("Converting document to new document class..."));
1407                         ErrorList el;
1408                         lyx::cap::SwitchLayoutsBetweenClasses(
1409                                 old_class, new_class,
1410                                 buffer->paragraphs(), el);
1411
1412                         bufferErrors(*buffer, el);
1413                         view()->showErrorList(_("Class switch"));
1414                         break;
1415                 }
1416
1417                 case LFUN_TEXTCLASS_LOAD:
1418                         loadTextclass(argument);
1419                         break;
1420
1421                 case LFUN_LYXRC_APPLY: {
1422                         istringstream ss(argument);
1423                         bool const success = lyxrc.read(ss) == 0;
1424
1425                         if (!success) {
1426                                 lyxerr << "Warning in LFUN_LYXRC_APPLY!\n"
1427                                        << "Unable to read lyxrc data"
1428                                        << endl;
1429                         }
1430                         break;
1431                 }
1432
1433                 default: {
1434                         update = false;
1435                         view()->cursor().dispatch(cmd);
1436                         if (view()->cursor().result().dispatched())
1437                                 update |= view()->cursor().result().update();
1438                         else
1439                                 update |= view()->dispatch(cmd);
1440
1441                         break;
1442                 }
1443                 }
1444
1445                 if (view()->available()) {
1446                         // Redraw screen unless explicitly told otherwise.
1447                         // This also initializes the position cache for all insets
1448                         // in (at least partially) visible top-level paragraphs.
1449                         if (update)
1450                                 view()->update();
1451
1452                         // fitCursor() needs valid inset position. The previous call to
1453                         // update() makes sure we have such even for freshly created
1454                         // insets.
1455                         if (view()->fitCursor())
1456                                 view()->update();
1457                         // if we executed a mutating lfun, mark the buffer as dirty
1458                         if (getStatus(cmd).enabled()
1459                                         && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1460                                         && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1461                                 view()->buffer()->markDirty();
1462                 }
1463
1464                 if (view()->cursor().inTexted()) {
1465                         view()->owner()->updateLayoutChoice();
1466                         sendDispatchMessage(getMessage(), cmd, verbose);
1467                 }
1468         }
1469 }
1470
1471
1472 void LyXFunc::sendDispatchMessage(string const & msg,
1473                                   FuncRequest const & cmd, bool verbose)
1474 {
1475         owner->updateMenubar();
1476         owner->updateToolbars();
1477
1478         if (cmd.action == LFUN_SELFINSERT || !verbose) {
1479                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1480                 if (!msg.empty())
1481                         owner->message(msg);
1482                 return;
1483         }
1484
1485         string dispatch_msg = msg;
1486         if (!dispatch_msg.empty())
1487                 dispatch_msg += ' ';
1488
1489         string comname = lyxaction.getActionName(cmd.action);
1490
1491         bool argsadded = false;
1492
1493         if (!cmd.argument.empty()) {
1494                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1495                         comname += ' ' + cmd.argument;
1496                         argsadded = true;
1497                 }
1498         }
1499
1500         string const shortcuts = toplevel_keymap->printbindings(cmd);
1501
1502         if (!shortcuts.empty()) {
1503                 comname += ": " + shortcuts;
1504         } else if (!argsadded && !cmd.argument.empty()) {
1505                 comname += ' ' + cmd.argument;
1506         }
1507
1508         if (!comname.empty()) {
1509                 comname = rtrim(comname);
1510                 dispatch_msg += '(' + comname + ')';
1511         }
1512
1513         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1514         if (!dispatch_msg.empty())
1515                 owner->message(dispatch_msg);
1516 }
1517
1518
1519 void LyXFunc::setupLocalKeymap()
1520 {
1521         keyseq.stdmap = toplevel_keymap.get();
1522         keyseq.curmap = toplevel_keymap.get();
1523         cancel_meta_seq.stdmap = toplevel_keymap.get();
1524         cancel_meta_seq.curmap = toplevel_keymap.get();
1525 }
1526
1527
1528 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1529 {
1530         string initpath = lyxrc.document_path;
1531         string filename(name);
1532
1533         if (view()->available()) {
1534                 string const trypath = owner->buffer()->filePath();
1535                 // If directory is writeable, use this as default.
1536                 if (IsDirWriteable(trypath))
1537                         initpath = trypath;
1538         }
1539
1540         static int newfile_number;
1541
1542         if (filename.empty()) {
1543                 filename = AddName(lyxrc.document_path,
1544                             "newfile" + tostr(++newfile_number) + ".lyx");
1545                 FileInfo fi(filename);
1546                 while (bufferlist.exists(filename) || fi.readable()) {
1547                         ++newfile_number;
1548                         filename = AddName(lyxrc.document_path,
1549                                     "newfile" + tostr(newfile_number) +
1550                                     ".lyx");
1551                         fi.newFile(filename);
1552                 }
1553         }
1554
1555         // The template stuff
1556         string templname;
1557         if (fromTemplate) {
1558                 FileDialog fileDlg(_("Select template file"),
1559                         LFUN_SELECT_FILE_SYNC,
1560                         make_pair(string(_("Documents|#o#O")),
1561                                   string(lyxrc.document_path)),
1562                         make_pair(string(_("Templates|#T#t")),
1563                                   string(lyxrc.template_path)));
1564
1565                 FileDialog::Result result =
1566                         fileDlg.open(lyxrc.template_path,
1567                                      FileFilterList(_("LyX Documents (*.lyx)")),
1568                                      string());
1569
1570                 if (result.first == FileDialog::Later)
1571                         return;
1572                 if (result.second.empty())
1573                         return;
1574                 templname = result.second;
1575         }
1576
1577         view()->newFile(filename, templname, !name.empty());
1578 }
1579
1580
1581 void LyXFunc::open(string const & fname)
1582 {
1583         string initpath = lyxrc.document_path;
1584
1585         if (view()->available()) {
1586                 string const trypath = owner->buffer()->filePath();
1587                 // If directory is writeable, use this as default.
1588                 if (IsDirWriteable(trypath))
1589                         initpath = trypath;
1590         }
1591
1592         string filename;
1593
1594         if (fname.empty()) {
1595                 FileDialog fileDlg(_("Select document to open"),
1596                         LFUN_FILE_OPEN,
1597                         make_pair(string(_("Documents|#o#O")),
1598                                   string(lyxrc.document_path)),
1599                         make_pair(string(_("Examples|#E#e")),
1600                                   string(AddPath(system_lyxdir(), "examples"))));
1601
1602                 FileDialog::Result result =
1603                         fileDlg.open(initpath,
1604                                      FileFilterList(_("LyX Documents (*.lyx)")),
1605                                      string());
1606
1607                 if (result.first == FileDialog::Later)
1608                         return;
1609
1610                 filename = result.second;
1611
1612                 // check selected filename
1613                 if (filename.empty()) {
1614                         owner->message(_("Canceled."));
1615                         return;
1616                 }
1617         } else
1618                 filename = fname;
1619
1620         // get absolute path of file and add ".lyx" to the filename if
1621         // necessary
1622         string const fullpath = FileSearch(string(), filename, "lyx");
1623         if (!fullpath.empty()) {
1624                 filename = fullpath;
1625         }
1626
1627         string const disp_fn(MakeDisplayPath(filename));
1628
1629         // if the file doesn't exist, let the user create one
1630         FileInfo const f(filename, true);
1631         if (!f.exist()) {
1632                 // the user specifically chose this name. Believe them.
1633                 view()->newFile(filename, "", true);
1634                 return;
1635         }
1636
1637         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1638
1639         string str2;
1640         if (view()->loadLyXFile(filename)) {
1641                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1642         } else {
1643                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1644         }
1645         owner->message(str2);
1646 }
1647
1648
1649 void LyXFunc::doImport(string const & argument)
1650 {
1651         string format;
1652         string filename = split(argument, format, ' ');
1653
1654         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1655                             << " file: " << filename << endl;
1656
1657         // need user interaction
1658         if (filename.empty()) {
1659                 string initpath = lyxrc.document_path;
1660
1661                 if (view()->available()) {
1662                         string const trypath = owner->buffer()->filePath();
1663                         // If directory is writeable, use this as default.
1664                         if (IsDirWriteable(trypath))
1665                                 initpath = trypath;
1666                 }
1667
1668                 string const text = bformat(_("Select %1$s file to import"),
1669                         formats.prettyName(format));
1670
1671                 FileDialog fileDlg(text,
1672                         LFUN_IMPORT,
1673                         make_pair(string(_("Documents|#o#O")),
1674                                   string(lyxrc.document_path)),
1675                         make_pair(string(_("Examples|#E#e")),
1676                                   string(AddPath(system_lyxdir(), "examples"))));
1677
1678                 string const filter = formats.prettyName(format)
1679                         + " (*." + formats.extension(format) + ')';
1680
1681                 FileDialog::Result result =
1682                         fileDlg.open(initpath,
1683                                      FileFilterList(filter),
1684                                      string());
1685
1686                 if (result.first == FileDialog::Later)
1687                         return;
1688
1689                 filename = result.second;
1690
1691                 // check selected filename
1692                 if (filename.empty())
1693                         owner->message(_("Canceled."));
1694         }
1695
1696         if (filename.empty())
1697                 return;
1698
1699         // get absolute path of file
1700         filename = MakeAbsPath(filename);
1701
1702         string const lyxfile = ChangeExtension(filename, ".lyx");
1703
1704         // Check if the document already is open
1705         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1706                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1707                         owner->message(_("Canceled."));
1708                         return;
1709                 }
1710         }
1711
1712         // if the file exists already, and we didn't do
1713         // -i lyx thefile.lyx, warn
1714         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1715                 string const file = MakeDisplayPath(lyxfile, 30);
1716
1717                 string text = bformat(_("The document %1$s already exists.\n\n"
1718                         "Do you want to over-write that document?"), file);
1719                 int const ret = Alert::prompt(_("Over-write document?"),
1720                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1721
1722                 if (ret == 1) {
1723                         owner->message(_("Canceled."));
1724                         return;
1725                 }
1726         }
1727
1728         Importer::Import(owner, filename, format);
1729 }
1730
1731
1732 void LyXFunc::closeBuffer()
1733 {
1734         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1735                 if (bufferlist.empty()) {
1736                         // need this otherwise SEGV may occur while
1737                         // trying to set variables that don't exist
1738                         // since there's no current buffer
1739                         owner->getDialogs().hideBufferDependent();
1740                 } else {
1741                         view()->setBuffer(bufferlist.first());
1742                 }
1743         }
1744 }
1745
1746
1747 // Each "owner" should have it's own message method. lyxview and
1748 // the minibuffer would use the minibuffer, but lyxserver would
1749 // send an ERROR signal to its client.  Alejandro 970603
1750 // This function is bit problematic when it comes to NLS, to make the
1751 // lyx servers client be language indepenent we must not translate
1752 // strings sent to this func.
1753 void LyXFunc::setErrorMessage(string const & m) const
1754 {
1755         dispatch_buffer = m;
1756         errorstat = true;
1757 }
1758
1759
1760 void LyXFunc::setMessage(string const & m) const
1761 {
1762         dispatch_buffer = m;
1763 }
1764
1765
1766 void LyXFunc::setStatusMessage(string const & m) const
1767 {
1768         status_buffer = m;
1769 }
1770
1771
1772 string const LyXFunc::viewStatusMessage()
1773 {
1774         // When meta-fake key is pressed, show the key sequence so far + "M-".
1775         if (wasMetaKey())
1776                 return keyseq.print() + "M-";
1777
1778         // Else, when a non-complete key sequence is pressed,
1779         // show the available options.
1780         if (keyseq.length() > 0 && !keyseq.deleted())
1781                 return keyseq.printOptions();
1782
1783         if (!view()->available())
1784                 return _("Welcome to LyX!");
1785
1786         return view()->cursor().currentState();
1787 }
1788
1789
1790 BufferView * LyXFunc::view() const
1791 {
1792         BOOST_ASSERT(owner);
1793         return owner->view().get();
1794 }
1795
1796
1797 bool LyXFunc::wasMetaKey() const
1798 {
1799         return (meta_fake_bit != key_modifier::none);
1800 }