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