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