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