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