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