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