]> git.lyx.org Git - features.git/blob - src/lyxfunc.C
introduce namespace lyx::support
[features.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         {
1255                 // servercmd: argument must be <file>:<template>
1256                 Buffer * tmpbuf = NewFile(argument);
1257                 if (tmpbuf)
1258                         view()->buffer(tmpbuf);
1259         }
1260         break;
1261
1262         case LFUN_FILE_OPEN:
1263                 open(argument);
1264                 break;
1265
1266         case LFUN_LAYOUT_TABULAR:
1267             if (view()->theLockingInset()) {
1268                 if (view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1269                     InsetTabular * inset = static_cast<InsetTabular *>
1270                         (view()->theLockingInset());
1271                     inset->openLayoutDialog(view());
1272                 } else if (view()->theLockingInset()->
1273                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1274                     InsetTabular * inset = static_cast<InsetTabular *>(
1275                         view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1276                     inset->openLayoutDialog(view());
1277                 }
1278             }
1279             break;
1280
1281         case LFUN_DROP_LAYOUTS_CHOICE:
1282                 owner->getToolbar().openLayoutList();
1283                 break;
1284
1285         case LFUN_MENU_OPEN_BY_NAME:
1286                 owner->getMenubar().openByName(argument);
1287                 break; // RVDK_PATCH_5
1288
1289         // --- lyxserver commands ----------------------------
1290
1291
1292         case LFUN_GETNAME:
1293                 setMessage(owner->buffer()->fileName());
1294                 lyxerr[Debug::INFO] << "FNAME["
1295                                << owner->buffer()->fileName()
1296                                << "] " << endl;
1297                 break;
1298
1299         case LFUN_NOTIFY:
1300         {
1301                 dispatch_buffer = keyseq.print();
1302                 lyxserver->notifyClient(dispatch_buffer);
1303         }
1304         break;
1305
1306         case LFUN_GOTOFILEROW:
1307         {
1308                 string file_name;
1309                 int row;
1310                 istringstream istr(argument.c_str());
1311                 istr >> file_name >> row;
1312                 // Must replace extension of the file to be .lyx and get full path
1313                 string const s(ChangeExtension(file_name, ".lyx"));
1314
1315                 // Either change buffer or load the file
1316                 if (bufferlist.exists(s)) {
1317                         view()->buffer(bufferlist.getBuffer(s));
1318                 } else {
1319                         view()->loadLyXFile(s);
1320                 }
1321
1322                 view()->setCursorFromRow(row);
1323
1324                 view()->center();
1325                 // see BufferView_pimpl::center()
1326                 view()->updateScrollbar();
1327         }
1328         break;
1329
1330         case LFUN_GOTO_PARAGRAPH:
1331         {
1332                 istringstream istr(argument.c_str());
1333
1334                 int id;
1335                 istr >> id;
1336                 ParIterator par = owner->buffer()->getParFromID(id);
1337                 if (par == owner->buffer()->par_iterator_end()) {
1338                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1339                                             << id << ']' << endl;
1340                         break;
1341                 } else {
1342                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1343                                             << " found." << endl;
1344                 }
1345
1346                 if (view()->theLockingInset())
1347                         view()->unlockInset(view()->theLockingInset());
1348                 if (par->inInset()) {
1349                         FuncRequest cmd(view(), LFUN_INSET_EDIT, "left");
1350                         par->inInset()->localDispatch(cmd);
1351                 }
1352                 // Set the cursor
1353                 view()->getLyXText()->setCursor(par.pit(), 0);
1354                 view()->switchKeyMap();
1355                 owner->view_state_changed();
1356
1357                 view()->center();
1358                 // see BufferView_pimpl::center()
1359                 view()->updateScrollbar();
1360         }
1361         break;
1362
1363         // --- insert characters ----------------------------------------
1364
1365         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1366         case LFUN_MATH_EXTERN:
1367         case LFUN_MATH_NUMBER:
1368         case LFUN_MATH_NONUMBER:
1369         case LFUN_MATH_LIMITS:
1370         {
1371                 setErrorMessage(N_("This is only allowed in math mode!"));
1372         }
1373         break;
1374
1375         // passthrough hat and underscore outside mathed:
1376         case LFUN_SUBSCRIPT:
1377                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1378                 break;
1379         case LFUN_SUPERSCRIPT:
1380                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1381                 break;
1382
1383         case LFUN_DIALOG_SHOW: {
1384                 string const name = ev.getArg(0);
1385                 string data = trim(ev.argument.substr(name.size()));
1386
1387                 if (name == "character") {
1388                         data = freefont2string();
1389                         if (!data.empty())
1390                                 owner->getDialogs().show("character", data);
1391                 } else if (name == "document")
1392                         owner->getDialogs().showDocument();
1393                 else if (name == "findreplace")
1394                         owner->getDialogs().showSearch();
1395                 else if (name == "forks")
1396                         owner->getDialogs().showForks();
1397                 else if (name == "preamble")
1398                         owner->getDialogs().showPreamble();
1399                 else if (name == "preferences")
1400                         owner->getDialogs().showPreferences();
1401                 else if (name == "print")
1402                         owner->getDialogs().showPrint();
1403                 else if (name == "spellchecker")
1404                         owner->getDialogs().showSpellchecker();
1405                 else
1406                         owner->getDialogs().show(name, data);
1407                 break;
1408         }
1409
1410         case LFUN_DIALOG_SHOW_NEW_INSET: {
1411                 string const & name = argument;
1412                 string data;
1413                 if (name == "bibitem" ||
1414                     name == "bibtex" ||
1415                     name == "include" ||
1416                     name == "index" ||
1417                     name == "ref" ||
1418                     name == "toc" ||
1419                     name == "url") {
1420                         InsetCommandParams p(name);
1421                         data = InsetCommandMailer::params2string(name, p);
1422                 } else if (name == "citation") {
1423                         InsetCommandParams p("cite");
1424                         data = InsetCommandMailer::params2string(name, p);
1425                 }
1426                 owner->getDialogs().show(name, data, 0);
1427         }
1428         break;
1429
1430         case LFUN_DIALOG_SHOW_NEXT_INSET: {
1431         }
1432         break;
1433
1434         case LFUN_DIALOG_UPDATE: {
1435                 string const & name = argument;
1436                 // Can only update a dialog connected to an existing inset
1437                 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1438                 if (inset) {
1439                         FuncRequest fr(view(), LFUN_INSET_DIALOG_UPDATE,
1440                                        ev.argument);
1441                         inset->localDispatch(fr);
1442                 } else if (name == "paragraph") {
1443                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1444                 }
1445         }
1446         break;
1447
1448         case LFUN_DIALOG_HIDE:
1449                 Dialogs::hide(argument, 0);
1450                 break;
1451
1452         case LFUN_DIALOG_DISCONNECT_INSET:
1453                 owner->getDialogs().disconnect(argument);
1454                 break;
1455
1456         case LFUN_CHILDOPEN:
1457         {
1458                 string const filename =
1459                         MakeAbsPath(argument,
1460                                     owner->buffer()->filePath());
1461                 setMessage(N_("Opening child document ") +
1462                            MakeDisplayPath(filename) + "...");
1463                 view()->savePosition(0);
1464                 if (bufferlist.exists(filename))
1465                         view()->buffer(bufferlist.getBuffer(filename));
1466                 else
1467                         view()->loadLyXFile(filename);
1468         }
1469         break;
1470
1471         case LFUN_TOGGLECURSORFOLLOW:
1472                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1473                 break;
1474
1475         case LFUN_KMAP_OFF:
1476                 owner->getIntl().KeyMapOn(false);
1477                 break;
1478
1479         case LFUN_KMAP_PRIM:
1480                 owner->getIntl().KeyMapPrim();
1481                 break;
1482
1483         case LFUN_KMAP_SEC:
1484                 owner->getIntl().KeyMapSec();
1485                 break;
1486
1487         case LFUN_KMAP_TOGGLE:
1488                 owner->getIntl().ToggleKeyMap();
1489                 break;
1490
1491         case LFUN_SEQUENCE:
1492         {
1493                 // argument contains ';'-terminated commands
1494                 while (!argument.empty()) {
1495                         string first;
1496                         argument = split(argument, first, ';');
1497                         dispatch(first);
1498                 }
1499         }
1500         break;
1501
1502         case LFUN_SAVEPREFERENCES:
1503         {
1504                 Path p(user_lyxdir);
1505                 lyxrc.write("preferences");
1506         }
1507         break;
1508
1509         case LFUN_SCREEN_FONT_UPDATE:
1510         {
1511                 // handle the screen font changes.
1512                 lyxrc.set_font_norm_type();
1513                 lyx_gui::update_fonts();
1514                 // We also need to empty the textcache so that
1515                 // the buffer will be formatted correctly after
1516                 // a zoom change.
1517                 textcache.clear();
1518                 // Of course we should only do the resize and the textcache.clear
1519                 // if values really changed...but not very important right now. (Lgb)
1520                 // All visible buffers will need resize
1521                 view()->resize();
1522                 view()->repaint();
1523         }
1524         break;
1525
1526         case LFUN_SET_COLOR:
1527         {
1528                 string lyx_name;
1529                 string const x11_name = split(argument, lyx_name, ' ');
1530                 if (lyx_name.empty() || x11_name.empty()) {
1531                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1532                                                 " <x11_name>"));
1533                         break;
1534                         }
1535
1536                 bool const graphicsbg_changed =
1537                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1538                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1539
1540                 if (!lcolor.setColor(lyx_name, x11_name)) {
1541                         setErrorMessage(
1542                                 bformat(_("Set-color \"%1$s\" failed "
1543                                                   "- color is undefined or "
1544                                                   "may not be redefined"), lyx_name));
1545                         break;
1546                 }
1547
1548                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1549
1550                 if (graphicsbg_changed) {
1551 #ifdef WITH_WARNINGS
1552 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1553 #endif
1554 #if 0
1555                         grfx::GCache & gc = grfx::GCache::get();
1556                         gc.changeDisplay(true);
1557 #endif
1558                 }
1559
1560                 view()->repaint();
1561                 break;
1562         }
1563
1564         case LFUN_MESSAGE:
1565                 owner->message(argument);
1566                 break;
1567
1568         case LFUN_FORKS_KILL:
1569         {
1570                 if (!isStrInt(argument))
1571                         break;
1572
1573                 pid_t const pid = strToInt(argument);
1574                 ForkedcallsController & fcc = ForkedcallsController::get();
1575                 fcc.kill(pid);
1576                 break;
1577         }
1578
1579         case LFUN_TOOLTIPS_TOGGLE:
1580                 owner->getDialogs().toggleTooltips();
1581                 break;
1582
1583         case LFUN_EXTERNAL_EDIT: {
1584                 InsetExternal()
1585                         .localDispatch(FuncRequest(view(), action, argument));
1586                 break;
1587         }
1588
1589         default:
1590                 // Then if it was none of the above
1591                 // Trying the BufferView::pimpl dispatch:
1592                 if (!view()->dispatch(ev))
1593                         lyxerr << "A truly unknown func ["
1594                                << lyxaction.getActionName(ev.action) << "]!"
1595                                << endl;
1596                 break;
1597         } // end of switch
1598
1599 exit_with_message:
1600
1601         view()->owner()->updateLayoutChoice();
1602
1603         if (view()->available()) {
1604                 view()->fitCursor();
1605
1606                 // If we executed a mutating lfun, mark the buffer as dirty
1607                 if (!lyxaction.funcHasFlag(ev.action, LyXAction::NoBuffer)
1608                     && !lyxaction.funcHasFlag(ev.action, LyXAction::ReadOnly))
1609                         view()->buffer()->markDirty();
1610         }
1611
1612         sendDispatchMessage(getMessage(), ev, verbose);
1613 }
1614
1615
1616 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1617 {
1618         owner->updateMenubar();
1619         owner->updateToolbar();
1620
1621         if (ev.action == LFUN_SELFINSERT || !verbose) {
1622                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1623                 if (!msg.empty())
1624                         owner->message(msg);
1625                 return;
1626         }
1627
1628         string dispatch_msg = msg;
1629         if (!dispatch_msg.empty())
1630                 dispatch_msg += ' ';
1631
1632         string comname = lyxaction.getActionName(ev.action);
1633
1634         int pseudoaction = ev.action;
1635         bool argsadded = false;
1636
1637         if (!ev.argument.empty()) {
1638                 // the pseudoaction is useful for the bindings
1639                 pseudoaction = lyxaction.searchActionArg(ev.action, ev.argument);
1640
1641                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
1642                         pseudoaction = ev.action;
1643                 } else {
1644                         comname += ' ' + ev.argument;
1645                         argsadded = true;
1646                 }
1647         }
1648
1649         string const shortcuts = toplevel_keymap->findbinding(pseudoaction);
1650
1651         if (!shortcuts.empty()) {
1652                 comname += ": " + shortcuts;
1653         } else if (!argsadded && !ev.argument.empty()) {
1654                 comname += ' ' + ev.argument;
1655         }
1656
1657         if (!comname.empty()) {
1658                 comname = rtrim(comname);
1659                 dispatch_msg += '(' + comname + ')';
1660         }
1661
1662         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1663         if (!dispatch_msg.empty())
1664                 owner->message(dispatch_msg);
1665 }
1666
1667
1668 void LyXFunc::setupLocalKeymap()
1669 {
1670         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1671         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1672 }
1673
1674
1675 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1676 {
1677         string initpath = lyxrc.document_path;
1678         string filename(name);
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         static int newfile_number;
1688
1689         if (filename.empty()) {
1690                 filename = AddName(lyxrc.document_path,
1691                             "newfile" + tostr(++newfile_number) + ".lyx");
1692                 FileInfo fi(filename);
1693                 while (bufferlist.exists(filename) || fi.readable()) {
1694                         ++newfile_number;
1695                         filename = AddName(lyxrc.document_path,
1696                                     "newfile" + tostr(newfile_number) +
1697                                     ".lyx");
1698                         fi.newFile(filename);
1699                 }
1700         }
1701
1702         // The template stuff
1703         string templname;
1704         if (fromTemplate) {
1705                 FileDialog fileDlg(_("Select template file"),
1706                         LFUN_SELECT_FILE_SYNC,
1707                         make_pair(string(_("Documents|#o#O")),
1708                                   string(lyxrc.document_path)),
1709                         make_pair(string(_("Templates|#T#t")),
1710                                   string(lyxrc.template_path)));
1711
1712                 FileDialog::Result result =
1713                         fileDlg.open(lyxrc.template_path,
1714                                        _("*.lyx| LyX Documents (*.lyx)"));
1715
1716                 if (result.first == FileDialog::Later)
1717                         return;
1718
1719                 string const fname = result.second;
1720
1721                 if (fname.empty())
1722                         return;
1723                 templname = fname;
1724         }
1725
1726         view()->buffer(newFile(filename, templname, !name.empty()));
1727 }
1728
1729
1730 void LyXFunc::open(string const & fname)
1731 {
1732         string initpath = lyxrc.document_path;
1733
1734         if (view()->available()) {
1735                 string const trypath = owner->buffer()->filePath();
1736                 // If directory is writeable, use this as default.
1737                 if (IsDirWriteable(trypath))
1738                         initpath = trypath;
1739         }
1740
1741         string filename;
1742
1743         if (fname.empty()) {
1744                 FileDialog fileDlg(_("Select document to open"),
1745                         LFUN_FILE_OPEN,
1746                         make_pair(string(_("Documents|#o#O")),
1747                                   string(lyxrc.document_path)),
1748                         make_pair(string(_("Examples|#E#e")),
1749                                   string(AddPath(system_lyxdir, "examples"))));
1750
1751                 FileDialog::Result result =
1752                         fileDlg.open(initpath,
1753                                        _("*.lyx| LyX Documents (*.lyx)"));
1754
1755                 if (result.first == FileDialog::Later)
1756                         return;
1757
1758                 filename = result.second;
1759
1760                 // check selected filename
1761                 if (filename.empty()) {
1762                         owner->message(_("Canceled."));
1763                         return;
1764                 }
1765         } else
1766                 filename = fname;
1767
1768         // get absolute path of file and add ".lyx" to the filename if
1769         // necessary
1770         string const fullpath = FileSearch(string(), filename, "lyx");
1771         if (!fullpath.empty()) {
1772                 filename = fullpath;
1773         }
1774
1775         string const disp_fn(MakeDisplayPath(filename));
1776
1777         // if the file doesn't exist, let the user create one
1778         FileInfo const f(filename, true);
1779         if (!f.exist()) {
1780                 // the user specifically chose this name. Believe them.
1781                 Buffer * buffer =  newFile(filename, "", true);
1782                 view()->buffer(buffer);
1783                 return;
1784         }
1785
1786         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1787
1788         string str2;
1789         if (view()->loadLyXFile(filename)) {
1790                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1791         } else {
1792                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1793         }
1794         owner->message(str2);
1795 }
1796
1797
1798 void LyXFunc::doImport(string const & argument)
1799 {
1800         string format;
1801         string filename = split(argument, format, ' ');
1802
1803         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1804                             << " file: " << filename << endl;
1805
1806         // need user interaction
1807         if (filename.empty()) {
1808                 string initpath = lyxrc.document_path;
1809
1810                 if (view()->available()) {
1811                         string const trypath = owner->buffer()->filePath();
1812                         // If directory is writeable, use this as default.
1813                         if (IsDirWriteable(trypath))
1814                                 initpath = trypath;
1815                 }
1816
1817                 string const text = bformat(_("Select %1$s file to import"),
1818                         formats.prettyName(format));
1819
1820                 FileDialog fileDlg(text,
1821                         LFUN_IMPORT,
1822                         make_pair(string(_("Documents|#o#O")),
1823                                   string(lyxrc.document_path)),
1824                         make_pair(string(_("Examples|#E#e")),
1825                                   string(AddPath(system_lyxdir, "examples"))));
1826
1827                 string const extension = "*." + formats.extension(format)
1828                         + "| " + formats.prettyName(format)
1829                         + " (*." + formats.extension(format) + ')';
1830
1831                 FileDialog::Result result = fileDlg.open(initpath,
1832                                                            extension);
1833
1834                 if (result.first == FileDialog::Later)
1835                         return;
1836
1837                 filename = result.second;
1838
1839                 // check selected filename
1840                 if (filename.empty())
1841                         owner->message(_("Canceled."));
1842         }
1843
1844         if (filename.empty())
1845                 return;
1846
1847         // get absolute path of file
1848         filename = MakeAbsPath(filename);
1849
1850         string const lyxfile = ChangeExtension(filename, ".lyx");
1851
1852         // Check if the document already is open
1853         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1854                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1855                         owner->message(_("Canceled."));
1856                         return;
1857                 }
1858         }
1859
1860         // if the file exists already, and we didn't do
1861         // -i lyx thefile.lyx, warn
1862         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1863                 string const file = MakeDisplayPath(lyxfile, 30);
1864
1865                 string text = bformat(_("The document %1$s already exists.\n\n"
1866                         "Do you want to over-write that document?"), file);
1867                 int const ret = Alert::prompt(_("Over-write document?"),
1868                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1869
1870                 if (ret == 1) {
1871                         owner->message(_("Canceled."));
1872                         return;
1873                 }
1874         }
1875
1876         Importer::Import(owner, filename, format);
1877 }
1878
1879
1880 void LyXFunc::closeBuffer()
1881 {
1882         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1883                 if (bufferlist.empty()) {
1884                         // need this otherwise SEGV may occur while trying to
1885                         // set variables that don't exist
1886                         // since there's no current buffer
1887                         owner->getDialogs().hideBufferDependent();
1888                 } else {
1889                         view()->buffer(bufferlist.first());
1890                 }
1891         }
1892 }
1893
1894
1895 // Each "owner" should have it's own message method. lyxview and
1896 // the minibuffer would use the minibuffer, but lyxserver would
1897 // send an ERROR signal to its client.  Alejandro 970603
1898 // This func is bit problematic when it comes to NLS, to make the
1899 // lyx servers client be language indepenent we must not translate
1900 // strings sent to this func.
1901 void LyXFunc::setErrorMessage(string const & m) const
1902 {
1903         dispatch_buffer = m;
1904         errorstat = true;
1905 }
1906
1907
1908 void LyXFunc::setMessage(string const & m) const
1909 {
1910         dispatch_buffer = m;
1911 }
1912
1913
1914 void LyXFunc::setStatusMessage(string const & m) const
1915 {
1916         status_buffer = m;
1917 }
1918
1919
1920 string const LyXFunc::view_status_message()
1921 {
1922         // When meta-fake key is pressed, show the key sequence so far + "M-".
1923         if (wasMetaKey()) {
1924                 return keyseq.print() + "M-";
1925         }
1926
1927         // Else, when a non-complete key sequence is pressed,
1928         // show the available options.
1929         if (keyseq.length() > 0 && !keyseq.deleted()) {
1930                 return keyseq.printOptions();
1931         }
1932
1933         if (!view()->available())
1934                 return _("Welcome to LyX!");
1935
1936         return currentState(view());
1937 }
1938
1939
1940 BufferView * LyXFunc::view() const
1941 {
1942         Assert(owner);
1943         return owner->view().get();
1944 }