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