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