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