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