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