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