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