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