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