]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
Compile fix.
[lyx.git] / src / lyxfunc.C
1 /**
2  * \file lyxfunc.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Allan Rae
13  * \author Dekel Tsur
14  * \author Martin Vermeer
15  * \author Jürgen Vigna
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "lyxfunc.h"
23
24 #include "BranchList.h"
25 #include "buffer.h"
26 #include "buffer_funcs.h"
27 #include "bufferlist.h"
28 #include "bufferparams.h"
29 #include "BufferView.h"
30 #include "cursor.h"
31 #include "debug.h"
32 #include "encoding.h"
33 #include "exporter.h"
34 #include "format.h"
35 #include "funcrequest.h"
36 #include "gettext.h"
37 #include "importer.h"
38 #include "intl.h"
39 #include "iterators.h"
40 #include "kbmap.h"
41 #include "LColor.h"
42 #include "lyx_cb.h"
43 #include "LyXAction.h"
44 #include "lyxfind.h"
45 #include "lyxrc.h"
46 #include "lyxrow.h"
47 #include "lyxserver.h"
48 #include "lyxvc.h"
49 #include "paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "TextCache.h"
52 #include "undo_funcs.h"
53
54 #include "insets/insetcommand.h"
55 #include "insets/insetexternal.h"
56 #include "insets/insettabular.h"
57
58 #include "mathed/math_cursor.h"
59
60 #include "frontends/Alert.h"
61 #include "frontends/Dialogs.h"
62 #include "frontends/FileDialog.h"
63 #include "frontends/lyx_gui.h"
64 #include "frontends/LyXKeySym.h"
65 #include "frontends/LyXView.h"
66 #include "frontends/Menubar.h"
67 #include "frontends/Toolbar.h"
68
69 #include "support/FileInfo.h"
70 #include "support/filetools.h"
71 #include "support/forkedcontr.h"
72 #include "support/path.h"
73 #include "support/path_defines.h"
74 #include "support/tostr.h"
75
76 #include "support/std_sstream.h"
77
78 using bv_funcs::apply_freefont;
79 using bv_funcs::changeDepth;
80 using bv_funcs::currentState;
81 using bv_funcs::DEC_DEPTH;
82 using bv_funcs::freefont2string;
83 using bv_funcs::INC_DEPTH;
84 using bv_funcs::update_and_apply_freefont;
85
86 using lyx::support::AddName;
87 using lyx::support::AddPath;
88 using lyx::support::bformat;
89 using lyx::support::ChangeExtension;
90 using lyx::support::FileInfo;
91 using lyx::support::FileSearch;
92 using lyx::support::ForkedcallsController;
93 using lyx::support::i18nLibFileSearch;
94 using lyx::support::IsDirWriteable;
95 using lyx::support::IsFileReadable;
96 using lyx::support::isStrInt;
97 using lyx::support::MakeAbsPath;
98 using lyx::support::MakeDisplayPath;
99 using lyx::support::Path;
100 using lyx::support::rtrim;
101 using lyx::support::split;
102 using lyx::support::strToInt;
103 using lyx::support::strToUnsignedInt;
104 using lyx::support::system_lyxdir;
105 using lyx::support::token;
106 using lyx::support::trim;
107 using lyx::support::user_lyxdir;
108
109 using std::endl;
110 using std::make_pair;
111
112 using std::istringstream;
113
114
115 extern BufferList bufferlist;
116 extern LyXServer * lyxserver;
117 extern bool selection_possible;
118
119 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
120
121 // (alkis)
122 extern tex_accent_struct get_accent(kb_action action);
123
124 extern void ShowLatexLog();
125
126
127 LyXFunc::LyXFunc(LyXView * o)
128         : owner(o),
129         encoded_last_key(0),
130         keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
131         cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
132         meta_fake_bit(key_modifier::none)
133 {
134 }
135
136
137 void LyXFunc::moveCursorUpdate()
138 {
139         LyXText * lt = view()->text;
140         if (lt->selection.mark())
141                 lt->setSelection();
142         view()->update();
143         view()->switchKeyMap();
144 }
145
146
147 void LyXFunc::handleKeyFunc(kb_action action)
148 {
149         char c = encoded_last_key;
150
151         if (keyseq.length()) {
152                 c = 0;
153         }
154
155         owner->getIntl().getTransManager()
156                 .deadkey(c, get_accent(action).accent, view()->getLyXText());
157         // Need to clear, in case the minibuffer calls these
158         // actions
159         keyseq.clear();
160         // copied verbatim from do_accent_char
161         view()->update();
162         view()->getLyXText()->selection.cursor = view()->getLyXText()->cursor;
163 }
164
165
166 void LyXFunc::processKeySym(LyXKeySymPtr keysym,
167                             key_modifier::state state)
168 {
169         string argument;
170
171         if (lyxerr.debugging(Debug::KEY)) {
172                 lyxerr << "KeySym is "
173                        << keysym->getSymbolName()
174                        << endl;
175         }
176
177         // Do nothing if we have nothing (JMarc)
178         if (!keysym->isOK()) {
179                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
180                                    << endl;
181                 return;
182         }
183
184         if (keysym->isModifier()) {
185                 lyxerr[Debug::KEY] << "isModifier true" << endl;
186                 return;
187         }
188
189         Encoding const * encoding = view()->getEncoding();
190
191         encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
192
193         // Do a one-deep top-level lookup for
194         // cancel and meta-fake keys. RVDK_PATCH_5
195         cancel_meta_seq.reset();
196
197         int action = cancel_meta_seq.addkey(keysym, state);
198         lyxerr[Debug::KEY] << "action first set to [" << action << ']' << endl;
199
200         // When not cancel or meta-fake, do the normal lookup.
201         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
202         // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
203         if ((action != LFUN_CANCEL) && (action != LFUN_META_FAKE)) {
204                 // remove Caps Lock and Mod2 as a modifiers
205                 action = keyseq.addkey(keysym, (state | meta_fake_bit));
206                 lyxerr[Debug::KEY] << "action now set to ["
207                         << action << ']' << endl;
208         }
209
210         // Dont remove this unless you know what you are doing.
211         meta_fake_bit = key_modifier::none;
212
213         // can this happen now ?
214         if (action == LFUN_NOACTION) {
215                 action = LFUN_PREFIX;
216         }
217
218         if (lyxerr.debugging(Debug::KEY)) {
219                 lyxerr << "Key [action="
220                        << action << "]["
221                        << keyseq.print() << ']'
222                        << endl;
223         }
224
225         // already here we know if it any point in going further
226         // why not return already here if action == -1 and
227         // num_bytes == 0? (Lgb)
228
229         if (keyseq.length() > 1) {
230                 owner->message(keyseq.print());
231         }
232
233
234         // Maybe user can only reach the key via holding down shift.
235         // Let's see. But only if shift is the only modifier
236         if (action == LFUN_UNKNOWN_ACTION && state == key_modifier::shift) {
237                 lyxerr[Debug::KEY] << "Trying without shift" << endl;
238                 action = keyseq.addkey(keysym, key_modifier::none);
239                 lyxerr[Debug::KEY] << "Action now " << action << endl;
240         }
241
242         if (action == LFUN_UNKNOWN_ACTION) {
243                 // Hmm, we didn't match any of the keysequences. See
244                 // if it's normal insertable text not already covered
245                 // by a binding
246                 if (keysym->isText() && keyseq.length() == 1) {
247                         lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
248                         action = LFUN_SELFINSERT;
249                 } else {
250                         lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
251                         owner->message(_("Unknown function."));
252                         return;
253                 }
254         }
255
256         if (action == LFUN_SELFINSERT) {
257                 if (encoded_last_key != 0) {
258                         string arg;
259                         arg += encoded_last_key;
260
261                         dispatch(FuncRequest(view(), LFUN_SELFINSERT, arg));
262
263                         lyxerr[Debug::KEY] << "SelfInsert arg[`"
264                                    << argument << "']" << endl;
265                 }
266         } else {
267                 dispatch(FuncRequest(kb_action(action)));
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                 flag = getStatus(FuncRequest(lyxaction.LookupFunc(token(ev.argument, ';', 0))));
807         }
808
809         return flag;
810 }
811
812
813 void LyXFunc::dispatch(string const & s, bool verbose)
814 {
815         int const action = lyxaction.LookupFunc(s);
816
817         if (action == LFUN_UNKNOWN_ACTION) {
818                 owner->message(bformat(_("Unknown function (%1$s)"), s));
819                 return;
820         }
821
822         dispatch(FuncRequest(kb_action(action)), verbose);
823 }
824
825
826 namespace {
827         bool ensureBufferClean(BufferView * bv) {
828
829                 Buffer & buf = *bv->buffer();
830                 if (buf.isClean())
831                         return true;
832
833                 string const file = MakeDisplayPath(buf.fileName(), 30);
834                 string text = bformat(_("The document %1$s has unsaved "
835                                         "changes.\n\nDo you want to save "
836                                         "the document?"), file);
837                 int const ret = Alert::prompt(_("Save changed document?"),
838                                               text, 0, 1, _("&Save"),
839                                               _("&Cancel"));
840
841                 if (ret == 0)
842                         bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
843
844                 return buf.isClean();
845         }
846
847 } //namespace anon
848
849
850 void LyXFunc::dispatch(FuncRequest const & ev, bool verbose)
851 {
852         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: action[" << ev.action
853                               <<"] arg[" << ev.argument << ']' << endl;
854
855         // we have not done anything wrong yet.
856         errorstat = false;
857         dispatch_buffer.erase();
858
859 #ifdef NEW_DISPATCHER
860         // We try do call the most specific dispatcher first:
861         //  1. the lockinginset's dispatch
862         //  2. the bufferview's dispatch
863         //  3. the lyxview's dispatch
864 #endif
865
866         selection_possible = false;
867
868         string argument = ev.argument;
869         kb_action action = ev.action;
870
871         // We cannot use this function here
872         if (getStatus(ev).disabled()) {
873                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
874                        << lyxaction.getActionName(action)
875                        << " [" << action << "] is disabled at this location"
876                        << endl;
877                 setErrorMessage(getStatusMessage());
878                 goto exit_with_message;
879         }
880
881         if (view()->available())
882                 view()->hideCursor();
883
884 #if 1
885         {
886                 Cursor cursor;
887                 buildCursor(cursor, *view());
888                 if (cursor.dispatch(FuncRequest(ev, view())) == DISPATCHED) {
889                         lyxerr << "dispatched by Cursor::dispatch()\n";
890                         goto exit_with_message;
891                 }
892         }
893 #endif
894
895
896         if (view()->available() && view()->theLockingInset()) {
897                 InsetOld::RESULT result;
898                 if (action > 1 || (action == LFUN_UNKNOWN_ACTION &&
899                                      !keyseq.deleted()))
900                 {
901                         UpdatableInset * inset = view()->theLockingInset();
902 #if 1
903                         int inset_x;
904                         int dummy_y;
905                         inset->getCursorPos(view(), inset_x, dummy_y);
906 #endif
907                         if ((action == LFUN_UNKNOWN_ACTION)
908                             && argument.empty()) {
909                                 argument = encoded_last_key;
910                         }
911
912                         // the insets can't try to handle this,
913                         // a table cell in the dummy position will
914                         // lock its insettext, the insettext will
915                         // pass it the bufferview, and succeed,
916                         // so it will stay not locked. Not good
917                         // if we've just done LFUN_ESCAPE (which
918                         // injects an LFUN_PARAGRAPH_UPDATE)
919                         if (action == LFUN_PARAGRAPH_UPDATE) {
920                                 view()->dispatch(ev);
921                                 goto exit_with_message;
922                         }
923
924                         // Undo/Redo is a bit tricky for insets.
925                         if (action == LFUN_UNDO) {
926                                 view()->undo();
927                                 goto exit_with_message;
928                         } else if (action == LFUN_REDO) {
929                                 view()->redo();
930                                 goto exit_with_message;
931                         } else if (((result=inset->
932                                      // Hand-over to inset's own dispatch:
933                                      localDispatch(FuncRequest(view(), action, argument))) ==
934                                     DISPATCHED) ||
935                                    (result == DISPATCHED_NOUPDATE))
936                                 goto exit_with_message;
937                                         // If UNDISPATCHED, just soldier on
938                         else if (result == FINISHED) {
939                                 owner->clearMessage();
940                                 goto exit_with_message;
941                                 // We do not need special RTL handling here:
942                                 // FINISHED means that the cursor should be
943                                 // one position after the inset.
944                         } else if (result == FINISHED_RIGHT) {
945                                 view()->text->cursorRight(view());
946                                 moveCursorUpdate();
947                                 owner->clearMessage();
948                                 goto exit_with_message;
949                         } else if (result == FINISHED_UP) {
950                                 RowList::iterator const irow = view()->text->cursorIRow();
951                                 if (irow != view()->text->firstRow()) {
952 #if 1
953                                         view()->text->setCursorFromCoordinates(
954                                                 view()->text->cursor.x() + inset_x,
955                                                 view()->text->cursor.y() -
956                                                 irow->baseline() - 1);
957                                         view()->text->cursor.x_fix(view()->text->cursor.x());
958 #else
959                                         view()->text->cursorUp(view());
960 #endif
961                                         moveCursorUpdate();
962                                 } else {
963                                         view()->update();
964                                 }
965                                 owner->clearMessage();
966                                 goto exit_with_message;
967                         } else if (result == FINISHED_DOWN) {
968                                 RowList::iterator const irow = view()->text->cursorIRow();
969                                 if (irow != view()->text->lastRow()) {
970 #if 1
971                                         view()->text->setCursorFromCoordinates(
972                                                 view()->text->cursor.x() + inset_x,
973                                                 view()->text->cursor.y() -
974                                                 irow->baseline() +
975                                                 irow->height() + 1);
976                                         view()->text->cursor.x_fix(view()->text->cursor.x());
977 #else
978                                         view()->text->cursorDown(view());
979 #endif
980                                 } else {
981                                         view()->text->cursorRight(view());
982                                 }
983                                 moveCursorUpdate();
984                                 owner->clearMessage();
985                                 goto exit_with_message;
986                         }
987 #warning I am not sure this is still right, please have a look! (Jug 20020417)
988                         else { // result == UNDISPATCHED
989                                 //setMessage(N_("Text mode"));
990                                 switch (action) {
991                                 case LFUN_UNKNOWN_ACTION:
992                                 case LFUN_BREAKPARAGRAPH:
993                                 case LFUN_BREAKLINE:
994                                         view()->text->cursorRight(view());
995                                         view()->switchKeyMap();
996                                         owner->view_state_changed();
997                                         break;
998                                 case LFUN_RIGHT:
999                                         if (!view()->text->cursor.par()->isRightToLeftPar(owner->buffer()->params())) {
1000                                                 view()->text->cursorRight(view());
1001                                                 moveCursorUpdate();
1002                                                 owner->view_state_changed();
1003                                         }
1004                                         goto exit_with_message;
1005                                 case LFUN_LEFT:
1006                                         if (view()->text->cursor.par()->isRightToLeftPar(owner->buffer()->params())) {
1007                                                 view()->text->cursorRight(view());
1008                                                 moveCursorUpdate();
1009                                                 owner->view_state_changed();
1010                                         }
1011                                         goto exit_with_message;
1012                                 case LFUN_DOWN:
1013                                         if (view()->text->cursorRow() != view()->text->lastRow())
1014                                                 view()->text->cursorDown(view());
1015                                         else
1016                                                 view()->text->cursorRight(view());
1017                                         moveCursorUpdate();
1018                                         owner->view_state_changed();
1019                                         goto exit_with_message;
1020                                 default:
1021                                         break;
1022                                 }
1023                         }
1024                 }
1025         }
1026
1027         switch (action) {
1028
1029         case LFUN_ESCAPE: {
1030                 if (!view()->available())
1031                         break;
1032                 // this function should be used always [asierra060396]
1033                 UpdatableInset * tli = view()->theLockingInset();
1034                 if (tli) {
1035                         UpdatableInset * lock = tli->getLockingInset();
1036
1037                         if (tli == lock) {
1038                                 view()->unlockInset(tli);
1039                                 view()->text->cursorRight(view());
1040                                 moveCursorUpdate();
1041                                 owner->view_state_changed();
1042                         } else {
1043                                 tli->unlockInsetInInset(view(), lock, true);
1044                         }
1045                         finishUndo();
1046                         // Tell the paragraph dialog that we changed paragraph
1047                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1048                 }
1049                 break;
1050         }
1051
1052         case LFUN_WORDFINDFORWARD:
1053         case LFUN_WORDFINDBACKWARD: {
1054                 static string last_search;
1055                 string searched_string;
1056
1057                 if (!argument.empty()) {
1058                         last_search = argument;
1059                         searched_string = argument;
1060                 } else {
1061                         searched_string = last_search;
1062                 }
1063                 bool fw = (action == LFUN_WORDFINDFORWARD);
1064                 if (!searched_string.empty())
1065                         lyx::find::find(view(), searched_string, fw);
1066                 break;
1067         }
1068
1069         case LFUN_PREFIX:
1070                 if (view()->available() && !view()->theLockingInset())
1071                         view()->update();
1072                 owner->message(keyseq.printOptions());
1073                 break;
1074
1075         // --- Misc -------------------------------------------
1076         case LFUN_EXEC_COMMAND:
1077                 owner->focus_command_buffer();
1078                 break;
1079
1080         case LFUN_CANCEL:
1081                 keyseq.reset();
1082                 meta_fake_bit = key_modifier::none;
1083                 if (view()->available())
1084                         // cancel any selection
1085                         dispatch(FuncRequest(LFUN_MARK_OFF));
1086                 setMessage(N_("Cancel"));
1087                 break;
1088
1089         case LFUN_META_FAKE:
1090                 meta_fake_bit = key_modifier::alt;
1091                 setMessage(keyseq.print());
1092                 break;
1093
1094         case LFUN_READ_ONLY_TOGGLE:
1095                 if (owner->buffer()->lyxvc().inUse())
1096                         owner->buffer()->lyxvc().toggleReadOnly();
1097                 else
1098                         owner->buffer()->setReadonly(
1099                                 !owner->buffer()->isReadonly());
1100                 break;
1101
1102         case LFUN_CENTER: // this is center and redraw.
1103                 view()->center();
1104                 break;
1105
1106                 // --- Menus -----------------------------------------------
1107         case LFUN_MENUNEW:
1108                 menuNew(argument, false);
1109                 break;
1110
1111         case LFUN_MENUNEWTMPLT:
1112                 menuNew(argument, true);
1113                 break;
1114
1115         case LFUN_CLOSEBUFFER:
1116                 closeBuffer();
1117                 break;
1118
1119         case LFUN_MENUWRITE:
1120                 if (!owner->buffer()->isUnnamed()) {
1121                         string const str = bformat(_("Saving document %1$s..."),
1122                            MakeDisplayPath(owner->buffer()->fileName()));
1123                         owner->message(str);
1124                         MenuWrite(owner->buffer());
1125                         owner->message(str + _(" done."));
1126                 } else
1127                         WriteAs(owner->buffer());
1128                 break;
1129
1130         case LFUN_WRITEAS:
1131                 WriteAs(owner->buffer(), argument);
1132                 break;
1133
1134         case LFUN_MENURELOAD: {
1135                 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
1136                 string text = bformat(_("Any changes will be lost. Are you sure "
1137                         "you want to revert to the saved version of the document %1$s?"), file);
1138                 int const ret = Alert::prompt(_("Revert to saved document?"),
1139                         text, 0, 1, _("&Revert"), _("&Cancel"));
1140
1141                 if (ret == 0)
1142                         view()->reload();
1143                 break;
1144         }
1145
1146         case LFUN_UPDATE:
1147                 Exporter::Export(owner->buffer(), argument, true);
1148                 view()->showErrorList(BufferFormat(*owner->buffer()));
1149                 break;
1150
1151         case LFUN_PREVIEW:
1152                 Exporter::Preview(owner->buffer(), argument);
1153                 view()->showErrorList(BufferFormat(*owner->buffer()));
1154                 break;
1155
1156         case LFUN_BUILDPROG:
1157                 Exporter::Export(owner->buffer(), "program", true);
1158                 view()->showErrorList(_("Build"));
1159                 break;
1160
1161         case LFUN_RUNCHKTEX:
1162                 owner->buffer()->runChktex();
1163                 view()->showErrorList(_("ChkTeX"));
1164                 break;
1165
1166         case LFUN_EXPORT:
1167                 if (argument == "custom")
1168                         owner->getDialogs().showSendto();
1169                 else {
1170                         Exporter::Export(owner->buffer(), argument, false);
1171                         view()->showErrorList(BufferFormat(*owner->buffer()));
1172                 }
1173                 break;
1174
1175         case LFUN_IMPORT:
1176                 doImport(argument);
1177                 break;
1178
1179         case LFUN_QUIT:
1180                 QuitLyX();
1181                 break;
1182
1183         case LFUN_TOCVIEW:
1184         {
1185                 InsetCommandParams p("tableofcontents");
1186                 string const data = InsetCommandMailer::params2string("toc", p);
1187                 owner->getDialogs().show("toc", data, 0);
1188                 break;
1189         }
1190
1191         case LFUN_AUTOSAVE:
1192                 AutoSave(view());
1193                 break;
1194
1195         case LFUN_UNDO:
1196                 view()->undo();
1197                 break;
1198
1199         case LFUN_REDO:
1200                 view()->redo();
1201                 break;
1202
1203         case LFUN_DEPTH_MIN:
1204                 changeDepth(view(), view()->getLyXText(), DEC_DEPTH, false);
1205                 owner->view_state_changed();
1206                 break;
1207
1208         case LFUN_DEPTH_PLUS:
1209                 changeDepth(view(), view()->getLyXText(), INC_DEPTH, false);
1210                 owner->view_state_changed();
1211                 break;
1212
1213         case LFUN_FREEFONT_APPLY:
1214                 apply_freefont(view());
1215                 break;
1216
1217         case LFUN_FREEFONT_UPDATE:
1218                 update_and_apply_freefont(view(), argument);
1219                 break;
1220
1221         case LFUN_RECONFIGURE:
1222                 Reconfigure(view());
1223                 break;
1224
1225 #if 0
1226         case LFUN_FLOATSOPERATE:
1227                 if (argument == "openfoot")
1228                         view()->allFloats(1,0);
1229                 else if (argument == "closefoot")
1230                         view()->allFloats(0,0);
1231                 else if (argument == "openfig")
1232                         view()->allFloats(1,1);
1233                 else if (argument == "closefig")
1234                         view()->allFloats(0,1);
1235                 break;
1236 #else
1237 #ifdef WITH_WARNINGS
1238 //#warning Find another implementation here (or another lyxfunc)!
1239 #endif
1240 #endif
1241         case LFUN_HELP_OPEN:
1242         {
1243                 string const arg = argument;
1244                 if (arg.empty()) {
1245                         setErrorMessage(N_("Missing argument"));
1246                         break;
1247                 }
1248                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1249                 if (fname.empty()) {
1250                         lyxerr << "LyX: unable to find documentation file `"
1251                                << arg << "'. Bad installation?" << endl;
1252                         break;
1253                 }
1254                 owner->message(bformat(_("Opening help file %1$s..."),
1255                         MakeDisplayPath(fname)));
1256                 view()->loadLyXFile(fname, false);
1257                 break;
1258         }
1259
1260                 // --- version control -------------------------------
1261         case LFUN_VC_REGISTER:
1262         {
1263                 if (!ensureBufferClean(view()))
1264                         break;
1265                 if (!owner->buffer()->lyxvc().inUse()) {
1266                         owner->buffer()->lyxvc().registrer();
1267                         view()->reload();
1268                 }
1269         }
1270         break;
1271
1272         case LFUN_VC_CHECKIN:
1273         {
1274                 if (!ensureBufferClean(view()))
1275                         break;
1276                 if (owner->buffer()->lyxvc().inUse()
1277                     && !owner->buffer()->isReadonly()) {
1278                         owner->buffer()->lyxvc().checkIn();
1279                         view()->reload();
1280                 }
1281         }
1282         break;
1283
1284         case LFUN_VC_CHECKOUT:
1285         {
1286                 if (!ensureBufferClean(view()))
1287                         break;
1288                 if (owner->buffer()->lyxvc().inUse()
1289                     && owner->buffer()->isReadonly()) {
1290                         owner->buffer()->lyxvc().checkOut();
1291                         view()->reload();
1292                 }
1293         }
1294         break;
1295
1296         case LFUN_VC_REVERT:
1297         {
1298                 owner->buffer()->lyxvc().revert();
1299                 view()->reload();
1300         }
1301         break;
1302
1303         case LFUN_VC_UNDO:
1304         {
1305                 owner->buffer()->lyxvc().undoLast();
1306                 view()->reload();
1307         }
1308         break;
1309
1310         // --- buffers ----------------------------------------
1311
1312         case LFUN_SWITCHBUFFER:
1313                 view()->buffer(bufferlist.getBuffer(argument));
1314                 break;
1315
1316         case LFUN_FILE_NEW:
1317                 NewFile(view(), argument);
1318                 break;
1319
1320         case LFUN_FILE_OPEN:
1321                 open(argument);
1322                 break;
1323
1324         case LFUN_LAYOUT_TABULAR:
1325             if (view()->theLockingInset()) {
1326                 if (view()->theLockingInset()->lyxCode()== InsetOld::TABULAR_CODE) {
1327                     InsetTabular * inset = static_cast<InsetTabular *>
1328                         (view()->theLockingInset());
1329                     inset->openLayoutDialog(view());
1330                 } else if (view()->theLockingInset()->
1331                            getFirstLockingInsetOfType(InsetOld::TABULAR_CODE)!=0) {
1332                     InsetTabular * inset = static_cast<InsetTabular *>(
1333                         view()->theLockingInset()->getFirstLockingInsetOfType(InsetOld::TABULAR_CODE));
1334                     inset->openLayoutDialog(view());
1335                 }
1336             }
1337             break;
1338
1339         case LFUN_DROP_LAYOUTS_CHOICE:
1340                 owner->getToolbar().openLayoutList();
1341                 break;
1342
1343         case LFUN_MENU_OPEN_BY_NAME:
1344                 owner->getMenubar().openByName(argument);
1345                 break; // RVDK_PATCH_5
1346
1347         // --- lyxserver commands ----------------------------
1348
1349
1350         case LFUN_GETNAME:
1351                 setMessage(owner->buffer()->fileName());
1352                 lyxerr[Debug::INFO] << "FNAME["
1353                                << owner->buffer()->fileName()
1354                                << "] " << endl;
1355                 break;
1356
1357         case LFUN_NOTIFY:
1358         {
1359                 dispatch_buffer = keyseq.print();
1360                 lyxserver->notifyClient(dispatch_buffer);
1361         }
1362         break;
1363
1364         case LFUN_GOTOFILEROW:
1365         {
1366                 string file_name;
1367                 int row;
1368                 istringstream istr(argument.c_str());
1369                 istr >> file_name >> row;
1370                 // Must replace extension of the file to be .lyx and get full path
1371                 string const s(ChangeExtension(file_name, ".lyx"));
1372
1373                 // Either change buffer or load the file
1374                 if (bufferlist.exists(s)) {
1375                         view()->buffer(bufferlist.getBuffer(s));
1376                 } else {
1377                         view()->loadLyXFile(s);
1378                 }
1379
1380                 view()->setCursorFromRow(row);
1381
1382                 view()->center();
1383                 // see BufferView_pimpl::center()
1384                 view()->updateScrollbar();
1385         }
1386         break;
1387
1388         case LFUN_GOTO_PARAGRAPH:
1389         {
1390                 istringstream istr(argument.c_str());
1391
1392                 int id;
1393                 istr >> id;
1394                 ParIterator par = owner->buffer()->getParFromID(id);
1395                 if (par == owner->buffer()->par_iterator_end()) {
1396                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1397                                             << id << ']' << endl;
1398                         break;
1399                 } else {
1400                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1401                                             << " found." << endl;
1402                 }
1403
1404                 if (view()->theLockingInset())
1405                         view()->unlockInset(view()->theLockingInset());
1406                 if (par->inInset()) {
1407                         FuncRequest cmd(view(), LFUN_INSET_EDIT, "left");
1408                         par->inInset()->localDispatch(cmd);
1409                 }
1410                 // Set the cursor
1411                 view()->getLyXText()->setCursor(par.pit(), 0);
1412                 view()->switchKeyMap();
1413                 owner->view_state_changed();
1414
1415                 view()->center();
1416                 // see BufferView_pimpl::center()
1417                 view()->updateScrollbar();
1418         }
1419         break;
1420
1421         // --- insert characters ----------------------------------------
1422
1423         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1424         case LFUN_MATH_EXTERN:
1425         case LFUN_MATH_NUMBER:
1426         case LFUN_MATH_NONUMBER:
1427         case LFUN_MATH_LIMITS:
1428         {
1429                 setErrorMessage(N_("This is only allowed in math mode!"));
1430         }
1431         break;
1432
1433         // passthrough hat and underscore outside mathed:
1434         case LFUN_SUBSCRIPT:
1435                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1436                 break;
1437         case LFUN_SUPERSCRIPT:
1438                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1439                 break;
1440
1441         case LFUN_DIALOG_SHOW: {
1442                 string const name = ev.getArg(0);
1443                 string data = trim(ev.argument.substr(name.size()));
1444
1445                 if (name == "character") {
1446                         data = freefont2string();
1447                         if (!data.empty())
1448                                 owner->getDialogs().show("character", data);
1449                 } else if (name == "document")
1450                         owner->getDialogs().showDocument();
1451                 else if (name == "findreplace")
1452                         owner->getDialogs().showSearch();
1453                 else if (name == "forks")
1454                         owner->getDialogs().showForks();
1455                 else if (name == "preamble")
1456                         owner->getDialogs().showPreamble();
1457                 else if (name == "preferences")
1458                         owner->getDialogs().showPreferences();
1459                 else if (name == "print")
1460                         owner->getDialogs().showPrint();
1461                 else if (name == "spellchecker")
1462                         owner->getDialogs().showSpellchecker();
1463                 else
1464                         owner->getDialogs().show(name, data);
1465                 break;
1466         }
1467
1468         case LFUN_DIALOG_SHOW_NEW_INSET: {
1469                 string const & name = argument;
1470                 string data;
1471                 if (name == "bibitem" ||
1472                     name == "bibtex" ||
1473                     name == "include" ||
1474                     name == "index" ||
1475                     name == "ref" ||
1476                     name == "toc" ||
1477                     name == "url") {
1478                         InsetCommandParams p(name);
1479                         data = InsetCommandMailer::params2string(name, p);
1480                 } else if (name == "citation") {
1481                         InsetCommandParams p("cite");
1482                         data = InsetCommandMailer::params2string(name, p);
1483                 }
1484                 owner->getDialogs().show(name, data, 0);
1485         }
1486         break;
1487
1488         case LFUN_DIALOG_SHOW_NEXT_INSET: {
1489         }
1490         break;
1491
1492         case LFUN_INSET_DIALOG_SHOW: {
1493                 LyXText * lt = view()->getLyXText();
1494                 InsetOld * inset = lt->getInset();
1495                 if (inset) {
1496                         FuncRequest cmd(view(), LFUN_INSET_DIALOG_SHOW);
1497                         inset->localDispatch(cmd);
1498                 }
1499         }
1500         break;
1501
1502         case LFUN_DIALOG_UPDATE: {
1503                 string const & name = argument;
1504                 // Can only update a dialog connected to an existing inset
1505                 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1506                 if (inset) {
1507                         FuncRequest fr(view(), LFUN_INSET_DIALOG_UPDATE,
1508                                        ev.argument);
1509                         inset->localDispatch(fr);
1510                 } else if (name == "paragraph") {
1511                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1512                 }
1513         }
1514         break;
1515
1516         case LFUN_DIALOG_HIDE:
1517                 Dialogs::hide(argument, 0);
1518                 break;
1519
1520         case LFUN_DIALOG_DISCONNECT_INSET:
1521                 owner->getDialogs().disconnect(argument);
1522                 break;
1523
1524         case LFUN_CHILDOPEN:
1525         {
1526                 string const filename =
1527                         MakeAbsPath(argument,
1528                                     owner->buffer()->filePath());
1529                 setMessage(N_("Opening child document ") +
1530                            MakeDisplayPath(filename) + "...");
1531                 view()->savePosition(0);
1532                 if (bufferlist.exists(filename))
1533                         view()->buffer(bufferlist.getBuffer(filename));
1534                 else
1535                         view()->loadLyXFile(filename);
1536         }
1537         break;
1538
1539         case LFUN_TOGGLECURSORFOLLOW:
1540                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1541                 break;
1542
1543         case LFUN_KMAP_OFF:
1544                 owner->getIntl().KeyMapOn(false);
1545                 break;
1546
1547         case LFUN_KMAP_PRIM:
1548                 owner->getIntl().KeyMapPrim();
1549                 break;
1550
1551         case LFUN_KMAP_SEC:
1552                 owner->getIntl().KeyMapSec();
1553                 break;
1554
1555         case LFUN_KMAP_TOGGLE:
1556                 owner->getIntl().ToggleKeyMap();
1557                 break;
1558
1559         case LFUN_SEQUENCE:
1560         {
1561                 // argument contains ';'-terminated commands
1562                 while (!argument.empty()) {
1563                         string first;
1564                         argument = split(argument, first, ';');
1565                         dispatch(first);
1566                 }
1567         }
1568         break;
1569
1570         case LFUN_SAVEPREFERENCES:
1571         {
1572                 Path p(user_lyxdir());
1573                 lyxrc.write("preferences");
1574         }
1575         break;
1576
1577         case LFUN_SCREEN_FONT_UPDATE:
1578         {
1579                 // handle the screen font changes.
1580                 lyxrc.set_font_norm_type();
1581                 lyx_gui::update_fonts();
1582                 // We also need to empty the textcache so that
1583                 // the buffer will be formatted correctly after
1584                 // a zoom change.
1585                 textcache.clear();
1586                 // Of course we should only do the resize and the textcache.clear
1587                 // if values really changed...but not very important right now. (Lgb)
1588                 // All visible buffers will need resize
1589                 view()->resize();
1590                 view()->update();
1591         }
1592         break;
1593
1594         case LFUN_SET_COLOR:
1595         {
1596                 string lyx_name;
1597                 string const x11_name = split(argument, lyx_name, ' ');
1598                 if (lyx_name.empty() || x11_name.empty()) {
1599                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1600                                                 " <x11_name>"));
1601                         break;
1602                         }
1603
1604                 bool const graphicsbg_changed =
1605                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1606                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1607
1608                 if (!lcolor.setColor(lyx_name, x11_name)) {
1609                         setErrorMessage(
1610                                 bformat(_("Set-color \"%1$s\" failed "
1611                                                   "- color is undefined or "
1612                                                   "may not be redefined"), lyx_name));
1613                         break;
1614                 }
1615
1616                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1617
1618                 if (graphicsbg_changed) {
1619 #ifdef WITH_WARNINGS
1620 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1621 #endif
1622 #if 0
1623                         lyx::graphics::GCache & gc =
1624                                 lyx::graphics::GCache::get();
1625                         gc.changeDisplay(true);
1626 #endif
1627                 }
1628
1629                 view()->update();
1630                 break;
1631         }
1632
1633         case LFUN_MESSAGE:
1634                 owner->message(argument);
1635                 break;
1636
1637         case LFUN_FORKS_KILL:
1638         {
1639                 if (!isStrInt(argument))
1640                         break;
1641
1642                 pid_t const pid = strToInt(argument);
1643                 ForkedcallsController & fcc = ForkedcallsController::get();
1644                 fcc.kill(pid);
1645                 break;
1646         }
1647
1648         case LFUN_TOOLTIPS_TOGGLE:
1649                 owner->getDialogs().toggleTooltips();
1650                 break;
1651
1652         case LFUN_EXTERNAL_EDIT: {
1653                 InsetExternal()
1654                         .localDispatch(FuncRequest(view(), action, argument));
1655                 break;
1656         }
1657
1658         default:
1659                 // Then if it was none of the above
1660                 // Trying the BufferView::pimpl dispatch:
1661                 if (!view()->dispatch(ev))
1662                         lyxerr << "A truly unknown func ["
1663                                << lyxaction.getActionName(ev.action) << "]!"
1664                                << endl;
1665                 break;
1666         } // end of switch
1667
1668 exit_with_message:
1669
1670         view()->owner()->updateLayoutChoice();
1671
1672         if (view()->available()) {
1673                 if (view()->fitCursor()) {
1674                         //lyxerr << "LyXFunc->fitCursor->update" << endl;
1675                         view()->update();
1676                 }
1677
1678                 // If we executed a mutating lfun, mark the buffer as dirty
1679                 if (!getStatus(ev).disabled()
1680                     && !lyxaction.funcHasFlag(ev.action, LyXAction::NoBuffer)
1681                     && !lyxaction.funcHasFlag(ev.action, LyXAction::ReadOnly))
1682                         view()->buffer()->markDirty();
1683         }
1684
1685         sendDispatchMessage(getMessage(), ev, verbose);
1686 }
1687
1688
1689 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1690 {
1691         owner->updateMenubar();
1692         owner->updateToolbar();
1693
1694         if (ev.action == LFUN_SELFINSERT || !verbose) {
1695                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1696                 if (!msg.empty())
1697                         owner->message(msg);
1698                 return;
1699         }
1700
1701         string dispatch_msg = msg;
1702         if (!dispatch_msg.empty())
1703                 dispatch_msg += ' ';
1704
1705         string comname = lyxaction.getActionName(ev.action);
1706
1707         bool argsadded = false;
1708
1709         if (!ev.argument.empty()) {
1710                 if (ev.action != LFUN_UNKNOWN_ACTION) {
1711                         comname += ' ' + ev.argument;
1712                         argsadded = true;
1713                 }
1714         }
1715
1716         string const shortcuts = toplevel_keymap->findbinding(ev.action);
1717
1718         if (!shortcuts.empty()) {
1719                 comname += ": " + shortcuts;
1720         } else if (!argsadded && !ev.argument.empty()) {
1721                 comname += ' ' + ev.argument;
1722         }
1723
1724         if (!comname.empty()) {
1725                 comname = rtrim(comname);
1726                 dispatch_msg += '(' + comname + ')';
1727         }
1728
1729         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1730         if (!dispatch_msg.empty())
1731                 owner->message(dispatch_msg);
1732 }
1733
1734
1735 void LyXFunc::setupLocalKeymap()
1736 {
1737         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1738         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1739 }
1740
1741
1742 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1743 {
1744         string initpath = lyxrc.document_path;
1745         string filename(name);
1746
1747         if (view()->available()) {
1748                 string const trypath = owner->buffer()->filePath();
1749                 // If directory is writeable, use this as default.
1750                 if (IsDirWriteable(trypath))
1751                         initpath = trypath;
1752         }
1753
1754         static int newfile_number;
1755
1756         if (filename.empty()) {
1757                 filename = AddName(lyxrc.document_path,
1758                             "newfile" + tostr(++newfile_number) + ".lyx");
1759                 FileInfo fi(filename);
1760                 while (bufferlist.exists(filename) || fi.readable()) {
1761                         ++newfile_number;
1762                         filename = AddName(lyxrc.document_path,
1763                                     "newfile" + tostr(newfile_number) +
1764                                     ".lyx");
1765                         fi.newFile(filename);
1766                 }
1767         }
1768
1769         // The template stuff
1770         string templname;
1771         if (fromTemplate) {
1772                 FileDialog fileDlg(_("Select template file"),
1773                         LFUN_SELECT_FILE_SYNC,
1774                         make_pair(string(_("Documents|#o#O")),
1775                                   string(lyxrc.document_path)),
1776                         make_pair(string(_("Templates|#T#t")),
1777                                   string(lyxrc.template_path)));
1778
1779                 FileDialog::Result result =
1780                         fileDlg.open(lyxrc.template_path,
1781                                        _("*.lyx| LyX Documents (*.lyx)"));
1782
1783                 if (result.first == FileDialog::Later)
1784                         return;
1785
1786                 string const fname = result.second;
1787
1788                 if (fname.empty())
1789                         return;
1790                 templname = fname;
1791         }
1792
1793         view()->newFile(filename, templname, !name.empty());
1794 }
1795
1796
1797 void LyXFunc::open(string const & fname)
1798 {
1799         string initpath = lyxrc.document_path;
1800
1801         if (view()->available()) {
1802                 string const trypath = owner->buffer()->filePath();
1803                 // If directory is writeable, use this as default.
1804                 if (IsDirWriteable(trypath))
1805                         initpath = trypath;
1806         }
1807
1808         string filename;
1809
1810         if (fname.empty()) {
1811                 FileDialog fileDlg(_("Select document to open"),
1812                         LFUN_FILE_OPEN,
1813                         make_pair(string(_("Documents|#o#O")),
1814                                   string(lyxrc.document_path)),
1815                         make_pair(string(_("Examples|#E#e")),
1816                                   string(AddPath(system_lyxdir(), "examples"))));
1817
1818                 FileDialog::Result result =
1819                         fileDlg.open(initpath,
1820                                        _("*.lyx| LyX Documents (*.lyx)"));
1821
1822                 if (result.first == FileDialog::Later)
1823                         return;
1824
1825                 filename = result.second;
1826
1827                 // check selected filename
1828                 if (filename.empty()) {
1829                         owner->message(_("Canceled."));
1830                         return;
1831                 }
1832         } else
1833                 filename = fname;
1834
1835         // get absolute path of file and add ".lyx" to the filename if
1836         // necessary
1837         string const fullpath = FileSearch(string(), filename, "lyx");
1838         if (!fullpath.empty()) {
1839                 filename = fullpath;
1840         }
1841
1842         string const disp_fn(MakeDisplayPath(filename));
1843
1844         // if the file doesn't exist, let the user create one
1845         FileInfo const f(filename, true);
1846         if (!f.exist()) {
1847                 // the user specifically chose this name. Believe them.
1848                 view()->newFile(filename, "", true);
1849                 return;
1850         }
1851
1852         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1853
1854         string str2;
1855         if (view()->loadLyXFile(filename)) {
1856                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1857         } else {
1858                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1859         }
1860         owner->message(str2);
1861 }
1862
1863
1864 void LyXFunc::doImport(string const & argument)
1865 {
1866         string format;
1867         string filename = split(argument, format, ' ');
1868
1869         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1870                             << " file: " << filename << endl;
1871
1872         // need user interaction
1873         if (filename.empty()) {
1874                 string initpath = lyxrc.document_path;
1875
1876                 if (view()->available()) {
1877                         string const trypath = owner->buffer()->filePath();
1878                         // If directory is writeable, use this as default.
1879                         if (IsDirWriteable(trypath))
1880                                 initpath = trypath;
1881                 }
1882
1883                 string const text = bformat(_("Select %1$s file to import"),
1884                         formats.prettyName(format));
1885
1886                 FileDialog fileDlg(text,
1887                         LFUN_IMPORT,
1888                         make_pair(string(_("Documents|#o#O")),
1889                                   string(lyxrc.document_path)),
1890                         make_pair(string(_("Examples|#E#e")),
1891                                   string(AddPath(system_lyxdir(), "examples"))));
1892
1893                 string const extension = "*." + formats.extension(format)
1894                         + "| " + formats.prettyName(format)
1895                         + " (*." + formats.extension(format) + ')';
1896
1897                 FileDialog::Result result = fileDlg.open(initpath,
1898                                                            extension);
1899
1900                 if (result.first == FileDialog::Later)
1901                         return;
1902
1903                 filename = result.second;
1904
1905                 // check selected filename
1906                 if (filename.empty())
1907                         owner->message(_("Canceled."));
1908         }
1909
1910         if (filename.empty())
1911                 return;
1912
1913         // get absolute path of file
1914         filename = MakeAbsPath(filename);
1915
1916         string const lyxfile = ChangeExtension(filename, ".lyx");
1917
1918         // Check if the document already is open
1919         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1920                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1921                         owner->message(_("Canceled."));
1922                         return;
1923                 }
1924         }
1925
1926         // if the file exists already, and we didn't do
1927         // -i lyx thefile.lyx, warn
1928         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1929                 string const file = MakeDisplayPath(lyxfile, 30);
1930
1931                 string text = bformat(_("The document %1$s already exists.\n\n"
1932                         "Do you want to over-write that document?"), file);
1933                 int const ret = Alert::prompt(_("Over-write document?"),
1934                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1935
1936                 if (ret == 1) {
1937                         owner->message(_("Canceled."));
1938                         return;
1939                 }
1940         }
1941
1942         Importer::Import(owner, filename, format);
1943 }
1944
1945
1946 void LyXFunc::closeBuffer()
1947 {
1948         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1949                 if (bufferlist.empty()) {
1950                         // need this otherwise SEGV may occur while
1951                         // trying to set variables that don't exist
1952                         // since there's no current buffer
1953                         owner->getDialogs().hideBufferDependent();
1954                 } else {
1955                         view()->buffer(bufferlist.first());
1956                 }
1957         }
1958 }
1959
1960
1961 // Each "owner" should have it's own message method. lyxview and
1962 // the minibuffer would use the minibuffer, but lyxserver would
1963 // send an ERROR signal to its client.  Alejandro 970603
1964 // This func is bit problematic when it comes to NLS, to make the
1965 // lyx servers client be language indepenent we must not translate
1966 // strings sent to this func.
1967 void LyXFunc::setErrorMessage(string const & m) const
1968 {
1969         dispatch_buffer = m;
1970         errorstat = true;
1971 }
1972
1973
1974 void LyXFunc::setMessage(string const & m) const
1975 {
1976         dispatch_buffer = m;
1977 }
1978
1979
1980 void LyXFunc::setStatusMessage(string const & m) const
1981 {
1982         status_buffer = m;
1983 }
1984
1985
1986 string const LyXFunc::view_status_message()
1987 {
1988         // When meta-fake key is pressed, show the key sequence so far + "M-".
1989         if (wasMetaKey()) {
1990                 return keyseq.print() + "M-";
1991         }
1992
1993         // Else, when a non-complete key sequence is pressed,
1994         // show the available options.
1995         if (keyseq.length() > 0 && !keyseq.deleted()) {
1996                 return keyseq.printOptions();
1997         }
1998
1999         if (!view()->available())
2000                 return _("Welcome to LyX!");
2001
2002         return currentState(view());
2003 }
2004
2005
2006 BufferView * LyXFunc::view() const
2007 {
2008         BOOST_ASSERT(owner);
2009         return owner->view().get();
2010 }
2011
2012
2013 bool LyXFunc::wasMetaKey() const
2014 {
2015         return (meta_fake_bit != key_modifier::none);
2016 }