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