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