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