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