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