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