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