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