]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
Michael Schmitt's collapse status patch
[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                 case LFUN_DIALOG_SHOW: {
1197                         string const name = func.getArg(0);
1198                         string data = trim(func.argument.substr(name.size()));
1199
1200                         if (name == "character") {
1201                                 data = freefont2string();
1202                                 if (!data.empty())
1203                                         owner->getDialogs().show("character", data);
1204                         }
1205                         else if (name == "document")
1206                                 owner->getDialogs().showDocument();
1207                         else if (name == "findreplace")
1208                                 owner->getDialogs().showSearch();
1209                         else if (name == "forks")
1210                                 owner->getDialogs().showForks();
1211                         else if (name == "preamble")
1212                                 owner->getDialogs().showPreamble();
1213                         else if (name == "preferences")
1214                                 owner->getDialogs().showPreferences();
1215                         else if (name == "print")
1216                                 owner->getDialogs().showPrint();
1217                         else if (name == "spellchecker")
1218                                 owner->getDialogs().showSpellchecker();
1219
1220                         else if (name == "latexlog") {
1221                                 pair<Buffer::LogType, string> const logfile =
1222                                         owner->buffer()->getLogName();
1223                                 switch (logfile.first) {
1224                                 case Buffer::latexlog:
1225                                         data = "latex ";
1226                                         break;
1227                                 case Buffer::buildlog:
1228                                         data = "literate ";
1229                                         break;
1230                                 }
1231                                 data += logfile.second;
1232                                 owner->getDialogs().show("log", data);
1233                         }
1234                         else if (name == "vclog") {
1235                                 string const data = "vc " +
1236                                         owner->buffer()->lyxvc().getLogFile();
1237                                 owner->getDialogs().show("log", data);
1238                         }
1239                         else
1240                                 owner->getDialogs().show(name, data);
1241                         break;
1242                 }
1243
1244                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1245                         string const name = func.getArg(0);
1246                         string data = trim(func.argument.substr(name.size()));
1247                         if (name == "bibitem" ||
1248                             name == "bibtex" ||
1249                             name == "include" ||
1250                             name == "index" ||
1251                             name == "label" ||
1252                             name == "ref" ||
1253                             name == "toc" ||
1254                             name == "url") {
1255                                 InsetCommandParams p(name);
1256                                 data = InsetCommandMailer::params2string(name, p);
1257                         } else if (name == "box") {
1258                                 // \c data == "Boxed" || "Frameless" etc
1259                                 InsetBoxParams p(data);
1260                                 data = InsetBoxMailer::params2string(p);
1261                         } else if (name == "branch") {
1262                                 InsetBranchParams p;
1263                                 data = InsetBranchMailer::params2string(p);
1264                         } else if (name == "citation") {
1265                                 InsetCommandParams p("cite");
1266                                 data = InsetCommandMailer::params2string(name, p);
1267                         } else if (name == "ert") {
1268                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1269                         } else if (name == "external") {
1270                                 InsetExternalParams p;
1271                                 Buffer const & buffer = *owner->buffer();
1272                                 data = InsetExternalMailer::params2string(p, buffer);
1273                         } else if (name == "float") {
1274                                 InsetFloatParams p;
1275                                 data = InsetFloatMailer::params2string(p);
1276                         } else if (name == "graphics") {
1277                                 InsetGraphicsParams p;
1278                                 Buffer const & buffer = *owner->buffer();
1279                                 data = InsetGraphicsMailer::params2string(p, buffer);
1280                         } else if (name == "minipage") {
1281                                 InsetMinipage::Params p;
1282                                 data = InsetMinipageMailer::params2string(p);
1283                         } else if (name == "note") {
1284                                 InsetNoteParams p;
1285                                 data = InsetNoteMailer::params2string(p);
1286                         } else if (name == "vspace") {
1287                                 VSpace space;
1288                                 data = InsetVSpaceMailer::params2string(space);
1289                         } else if (name == "wrap") {
1290                                 InsetWrapParams p;
1291                                 data = InsetWrapMailer::params2string(p);
1292                         }
1293                         owner->getDialogs().show(name, data, 0);
1294                         break;
1295                 }
1296
1297                 case LFUN_DIALOG_SHOW_NEXT_INSET:
1298                         break;
1299
1300                 case LFUN_INSET_DIALOG_SHOW: {
1301                         InsetOld * inset = view()->getLyXText()->getInset();
1302                         if (inset)
1303                                 inset->dispatch(FuncRequest(view(), LFUN_INSET_DIALOG_SHOW));
1304                         break;
1305                 }
1306
1307                 case LFUN_DIALOG_UPDATE: {
1308                         string const & name = argument;
1309                         // Can only update a dialog connected to an existing inset
1310                         InsetBase * inset = owner->getDialogs().getOpenInset(name);
1311                         if (inset) {
1312                                 FuncRequest fr(view(), LFUN_INSET_DIALOG_UPDATE,
1313                                                                  func.argument);
1314                                 inset->dispatch(fr);
1315                         } else if (name == "paragraph") {
1316                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1317                         }
1318                         break;
1319                 }
1320
1321                 case LFUN_DIALOG_HIDE:
1322                         Dialogs::hide(argument, 0);
1323                         break;
1324
1325                 case LFUN_DIALOG_DISCONNECT_INSET:
1326                         owner->getDialogs().disconnect(argument);
1327                         break;
1328
1329                 case LFUN_CHILDOPEN: {
1330                         string const filename =
1331                                 MakeAbsPath(argument, owner->buffer()->filePath());
1332                         setMessage(N_("Opening child document ") +
1333                                          MakeDisplayPath(filename) + "...");
1334                         view()->savePosition(0);
1335                         string const parentfilename = owner->buffer()->fileName();
1336                         if (bufferlist.exists(filename))
1337                                 view()->buffer(bufferlist.getBuffer(filename));
1338                         else
1339                                 view()->loadLyXFile(filename);
1340                         // Set the parent name of the child document.
1341                         // This makes insertion of citations and references in the child work,
1342                         // when the target is in the parent or another child document.
1343                         owner->buffer()->setParentName(parentfilename);
1344                         break;
1345                 }
1346
1347                 case LFUN_TOGGLECURSORFOLLOW:
1348                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1349                         break;
1350
1351                 case LFUN_KMAP_OFF:
1352                         owner->getIntl().KeyMapOn(false);
1353                         break;
1354
1355                 case LFUN_KMAP_PRIM:
1356                         owner->getIntl().KeyMapPrim();
1357                         break;
1358
1359                 case LFUN_KMAP_SEC:
1360                         owner->getIntl().KeyMapSec();
1361                         break;
1362
1363                 case LFUN_KMAP_TOGGLE:
1364                         owner->getIntl().ToggleKeyMap();
1365                         break;
1366
1367                 case LFUN_REPEAT: {
1368                         // repeat command
1369                         string countstr;
1370                         argument = split(argument, countstr, ' ');
1371                         istringstream is(countstr);
1372                         int count = 0;
1373                         is >> count;
1374                         lyxerr << "repeat: count: " << count << " cmd: " << argument << endl;
1375                         for (int i = 0; i < count; ++i)
1376                                 dispatch(lyxaction.lookupFunc(argument));
1377                         break;
1378                 }
1379
1380                 case LFUN_SEQUENCE:
1381                         // argument contains ';'-terminated commands
1382                         while (!argument.empty()) {
1383                                 string first;
1384                                 argument = split(argument, first, ';');
1385                                 dispatch(lyxaction.lookupFunc(first));
1386                         }
1387                         break;
1388
1389                 case LFUN_SAVEPREFERENCES: {
1390                         Path p(user_lyxdir());
1391                         lyxrc.write("preferences");
1392                         break;
1393                 }
1394
1395                 case LFUN_SCREEN_FONT_UPDATE:
1396                         // handle the screen font changes.
1397                         lyxrc.set_font_norm_type();
1398                         lyx_gui::update_fonts();
1399                         // All visible buffers will need resize
1400                         view()->resize();
1401                         break;
1402
1403                 case LFUN_SET_COLOR: {
1404                         string lyx_name;
1405                         string const x11_name = split(argument, lyx_name, ' ');
1406                         if (lyx_name.empty() || x11_name.empty()) {
1407                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1408                                                         " <x11_name>"));
1409                                 break;
1410                         }
1411
1412                         bool const graphicsbg_changed =
1413                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1414                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1415
1416                         if (!lcolor.setColor(lyx_name, x11_name)) {
1417                                 setErrorMessage(
1418                                         bformat(_("Set-color \"%1$s\" failed "
1419                                                                 "- color is undefined or "
1420                                                                 "may not be redefined"), lyx_name));
1421                                 break;
1422                         }
1423
1424                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1425
1426                         if (graphicsbg_changed) {
1427 #ifdef WITH_WARNINGS
1428 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1429 #endif
1430 #if 0
1431                                 lyx::graphics::GCache::get().changeDisplay(true);
1432 #endif
1433                         }
1434                         break;
1435                 }
1436
1437                 case LFUN_MESSAGE:
1438                         owner->message(argument);
1439                         break;
1440
1441                 case LFUN_FORKS_KILL:
1442                         if (isStrInt(argument))
1443                                 ForkedcallsController::get().kill(strToInt(argument));
1444                         break;
1445
1446                 case LFUN_TOOLTIPS_TOGGLE:
1447                         owner->getDialogs().toggleTooltips();
1448                         break;
1449
1450                 case LFUN_EXTERNAL_EDIT:
1451                         InsetExternal().dispatch(FuncRequest(view(), action, argument));
1452                         break;
1453
1454                 default: {
1455                                 DispatchResult result =
1456                                         view()->cursor().dispatch(FuncRequest(func, view()));
1457                                 if (result.dispatched())
1458                                         lyxerr << "dispatched by Cursor::dispatch()" << endl;
1459                                 else
1460                                         lyxerr << "### NOT DISPATCHED BY Cursor::dispatch() ###" << endl;
1461                                 break;
1462                         }
1463                 }
1464         }
1465
1466         view()->owner()->updateLayoutChoice();
1467
1468         if (view()->available()) {
1469                 view()->fitCursor();
1470                 view()->update();
1471                 view()->cursor().updatePos();
1472                 // if we executed a mutating lfun, mark the buffer as dirty
1473                 if (!getStatus(func).disabled()
1474                     && !lyxaction.funcHasFlag(func.action, LyXAction::NoBuffer)
1475                     && !lyxaction.funcHasFlag(func.action, LyXAction::ReadOnly))
1476                         view()->buffer()->markDirty();
1477         }
1478
1479         sendDispatchMessage(getMessage(), func, verbose);
1480 }
1481
1482
1483 void LyXFunc::sendDispatchMessage(string const & msg,
1484                                   FuncRequest const & func, bool verbose)
1485 {
1486         owner->updateMenubar();
1487         owner->updateToolbar();
1488
1489         if (func.action == LFUN_SELFINSERT || !verbose) {
1490                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1491                 if (!msg.empty())
1492                         owner->message(msg);
1493                 return;
1494         }
1495
1496         string dispatch_msg = msg;
1497         if (!dispatch_msg.empty())
1498                 dispatch_msg += ' ';
1499
1500         string comname = lyxaction.getActionName(func.action);
1501
1502         bool argsadded = false;
1503
1504         if (!func.argument.empty()) {
1505                 if (func.action != LFUN_UNKNOWN_ACTION) {
1506                         comname += ' ' + func.argument;
1507                         argsadded = true;
1508                 }
1509         }
1510
1511         string const shortcuts = toplevel_keymap->findbinding(func);
1512
1513         if (!shortcuts.empty()) {
1514                 comname += ": " + shortcuts;
1515         } else if (!argsadded && !func.argument.empty()) {
1516                 comname += ' ' + func.argument;
1517         }
1518
1519         if (!comname.empty()) {
1520                 comname = rtrim(comname);
1521                 dispatch_msg += '(' + comname + ')';
1522         }
1523
1524         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1525         if (!dispatch_msg.empty())
1526                 owner->message(dispatch_msg);
1527 }
1528
1529
1530 void LyXFunc::setupLocalKeymap()
1531 {
1532         keyseq.stdmap = toplevel_keymap.get();
1533         keyseq.curmap = toplevel_keymap.get();
1534         cancel_meta_seq.stdmap = toplevel_keymap.get();
1535         cancel_meta_seq.curmap = toplevel_keymap.get();
1536 }
1537
1538
1539 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1540 {
1541         string initpath = lyxrc.document_path;
1542         string filename(name);
1543
1544         if (view()->available()) {
1545                 string const trypath = owner->buffer()->filePath();
1546                 // If directory is writeable, use this as default.
1547                 if (IsDirWriteable(trypath))
1548                         initpath = trypath;
1549         }
1550
1551         static int newfile_number;
1552
1553         if (filename.empty()) {
1554                 filename = AddName(lyxrc.document_path,
1555                             "newfile" + tostr(++newfile_number) + ".lyx");
1556                 FileInfo fi(filename);
1557                 while (bufferlist.exists(filename) || fi.readable()) {
1558                         ++newfile_number;
1559                         filename = AddName(lyxrc.document_path,
1560                                     "newfile" + tostr(newfile_number) +
1561                                     ".lyx");
1562                         fi.newFile(filename);
1563                 }
1564         }
1565
1566         // The template stuff
1567         string templname;
1568         if (fromTemplate) {
1569                 FileDialog fileDlg(_("Select template file"),
1570                         LFUN_SELECT_FILE_SYNC,
1571                         make_pair(string(_("Documents|#o#O")),
1572                                   string(lyxrc.document_path)),
1573                         make_pair(string(_("Templates|#T#t")),
1574                                   string(lyxrc.template_path)));
1575
1576                 FileDialog::Result result =
1577                         fileDlg.open(lyxrc.template_path,
1578                                        _("*.lyx| LyX Documents (*.lyx)"));
1579
1580                 if (result.first == FileDialog::Later)
1581                         return;
1582                 if (result.second.empty())
1583                         return;
1584                 templname = result.second;
1585         }
1586
1587         view()->newFile(filename, templname, !name.empty());
1588 }
1589
1590
1591 void LyXFunc::open(string const & fname)
1592 {
1593         string initpath = lyxrc.document_path;
1594
1595         if (view()->available()) {
1596                 string const trypath = owner->buffer()->filePath();
1597                 // If directory is writeable, use this as default.
1598                 if (IsDirWriteable(trypath))
1599                         initpath = trypath;
1600         }
1601
1602         string filename;
1603
1604         if (fname.empty()) {
1605                 FileDialog fileDlg(_("Select document to open"),
1606                         LFUN_FILE_OPEN,
1607                         make_pair(string(_("Documents|#o#O")),
1608                                   string(lyxrc.document_path)),
1609                         make_pair(string(_("Examples|#E#e")),
1610                                   string(AddPath(system_lyxdir(), "examples"))));
1611
1612                 FileDialog::Result result =
1613                         fileDlg.open(initpath,
1614                                        _("*.lyx| LyX Documents (*.lyx)"));
1615
1616                 if (result.first == FileDialog::Later)
1617                         return;
1618
1619                 filename = result.second;
1620
1621                 // check selected filename
1622                 if (filename.empty()) {
1623                         owner->message(_("Canceled."));
1624                         return;
1625                 }
1626         } else
1627                 filename = fname;
1628
1629         // get absolute path of file and add ".lyx" to the filename if
1630         // necessary
1631         string const fullpath = FileSearch(string(), filename, "lyx");
1632         if (!fullpath.empty()) {
1633                 filename = fullpath;
1634         }
1635
1636         string const disp_fn(MakeDisplayPath(filename));
1637
1638         // if the file doesn't exist, let the user create one
1639         FileInfo const f(filename, true);
1640         if (!f.exist()) {
1641                 // the user specifically chose this name. Believe them.
1642                 view()->newFile(filename, "", true);
1643                 return;
1644         }
1645
1646         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1647
1648         string str2;
1649         if (view()->loadLyXFile(filename)) {
1650                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1651         } else {
1652                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1653         }
1654         owner->message(str2);
1655 }
1656
1657
1658 void LyXFunc::doImport(string const & argument)
1659 {
1660         string format;
1661         string filename = split(argument, format, ' ');
1662
1663         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1664                             << " file: " << filename << endl;
1665
1666         // need user interaction
1667         if (filename.empty()) {
1668                 string initpath = lyxrc.document_path;
1669
1670                 if (view()->available()) {
1671                         string const trypath = owner->buffer()->filePath();
1672                         // If directory is writeable, use this as default.
1673                         if (IsDirWriteable(trypath))
1674                                 initpath = trypath;
1675                 }
1676
1677                 string const text = bformat(_("Select %1$s file to import"),
1678                         formats.prettyName(format));
1679
1680                 FileDialog fileDlg(text,
1681                         LFUN_IMPORT,
1682                         make_pair(string(_("Documents|#o#O")),
1683                                   string(lyxrc.document_path)),
1684                         make_pair(string(_("Examples|#E#e")),
1685                                   string(AddPath(system_lyxdir(), "examples"))));
1686
1687                 string const extension = "*." + formats.extension(format)
1688                         + "| " + formats.prettyName(format)
1689                         + " (*." + formats.extension(format) + ')';
1690
1691                 FileDialog::Result result = fileDlg.open(initpath,
1692                                                            extension);
1693
1694                 if (result.first == FileDialog::Later)
1695                         return;
1696
1697                 filename = result.second;
1698
1699                 // check selected filename
1700                 if (filename.empty())
1701                         owner->message(_("Canceled."));
1702         }
1703
1704         if (filename.empty())
1705                 return;
1706
1707         // get absolute path of file
1708         filename = MakeAbsPath(filename);
1709
1710         string const lyxfile = ChangeExtension(filename, ".lyx");
1711
1712         // Check if the document already is open
1713         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1714                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1715                         owner->message(_("Canceled."));
1716                         return;
1717                 }
1718         }
1719
1720         // if the file exists already, and we didn't do
1721         // -i lyx thefile.lyx, warn
1722         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1723                 string const file = MakeDisplayPath(lyxfile, 30);
1724
1725                 string text = bformat(_("The document %1$s already exists.\n\n"
1726                         "Do you want to over-write that document?"), file);
1727                 int const ret = Alert::prompt(_("Over-write document?"),
1728                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1729
1730                 if (ret == 1) {
1731                         owner->message(_("Canceled."));
1732                         return;
1733                 }
1734         }
1735
1736         Importer::Import(owner, filename, format);
1737 }
1738
1739
1740 void LyXFunc::closeBuffer()
1741 {
1742         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1743                 if (bufferlist.empty()) {
1744                         // need this otherwise SEGV may occur while
1745                         // trying to set variables that don't exist
1746                         // since there's no current buffer
1747                         owner->getDialogs().hideBufferDependent();
1748                 } else {
1749                         view()->buffer(bufferlist.first());
1750                 }
1751         }
1752 }
1753
1754
1755 // Each "owner" should have it's own message method. lyxview and
1756 // the minibuffer would use the minibuffer, but lyxserver would
1757 // send an ERROR signal to its client.  Alejandro 970603
1758 // This func is bit problematic when it comes to NLS, to make the
1759 // lyx servers client be language indepenent we must not translate
1760 // strings sent to this func.
1761 void LyXFunc::setErrorMessage(string const & m) const
1762 {
1763         dispatch_buffer = m;
1764         errorstat = true;
1765 }
1766
1767
1768 void LyXFunc::setMessage(string const & m) const
1769 {
1770         dispatch_buffer = m;
1771 }
1772
1773
1774 void LyXFunc::setStatusMessage(string const & m) const
1775 {
1776         status_buffer = m;
1777 }
1778
1779
1780 string const LyXFunc::view_status_message()
1781 {
1782         // When meta-fake key is pressed, show the key sequence so far + "M-".
1783         if (wasMetaKey()) {
1784                 return keyseq.print() + "M-";
1785         }
1786
1787         // Else, when a non-complete key sequence is pressed,
1788         // show the available options.
1789         if (keyseq.length() > 0 && !keyseq.deleted()) {
1790                 return keyseq.printOptions();
1791         }
1792
1793         if (!view()->available())
1794                 return _("Welcome to LyX!");
1795
1796         return currentState(view());
1797 }
1798
1799
1800 BufferView * LyXFunc::view() const
1801 {
1802         BOOST_ASSERT(owner);
1803         return owner->view().get();
1804 }
1805
1806
1807 bool LyXFunc::wasMetaKey() const
1808 {
1809         return (meta_fake_bit != key_modifier::none);
1810 }