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