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