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