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