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