]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
*** empty log message ***
[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                                 if (TEXT()->cursor.irow() != TEXT()->rows().begin()) {
916 #if 1
917                                         TEXT()->setCursorFromCoordinates(
918                                                 TEXT()->cursor.ix() + inset_x,
919                                                 TEXT()->cursor.iy() -
920                                                 TEXT()->cursor.irow()->baseline() - 1);
921                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
922 #else
923                                         TEXT()->cursorUp(view());
924 #endif
925                                         moveCursorUpdate(true, false);
926                                 } else {
927                                         view()->update(TEXT(), BufferView::SELECT);
928                                 }
929                                 owner->clearMessage();
930                                 goto exit_with_message;
931                         } else if (result == FINISHED_DOWN) {
932                                 if (boost::next(TEXT()->cursor.irow()) != TEXT()->rows().end()) {
933 #if 1
934                                         TEXT()->setCursorFromCoordinates(
935                                                 TEXT()->cursor.ix() + inset_x,
936                                                 TEXT()->cursor.iy() -
937                                                 TEXT()->cursor.irow()->baseline() +
938                                                 TEXT()->cursor.irow()->height() + 1);
939                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
940 #else
941                                         TEXT()->cursorDown(view());
942 #endif
943                                 } else {
944                                         TEXT()->cursorRight(view());
945                                 }
946                                 moveCursorUpdate(true, false);
947                                 owner->clearMessage();
948                                 goto exit_with_message;
949                         }
950 #warning I am not sure this is still right, please have a look! (Jug 20020417)
951                         else { // result == UNDISPATCHED
952                                 //setMessage(N_("Text mode"));
953                                 switch (action) {
954                                 case LFUN_UNKNOWN_ACTION:
955                                 case LFUN_BREAKPARAGRAPH:
956                                 case LFUN_BREAKLINE:
957                                         TEXT()->cursorRight(view());
958                                         view()->switchKeyMap();
959                                         owner->view_state_changed();
960                                         break;
961                                 case LFUN_RIGHT:
962                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
963                                                 TEXT()->cursorRight(view());
964                                                 moveCursorUpdate(true, false);
965                                                 owner->view_state_changed();
966                                         }
967                                         goto exit_with_message;
968                                 case LFUN_LEFT:
969                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
970                                                 TEXT()->cursorRight(view());
971                                                 moveCursorUpdate(true, false);
972                                                 owner->view_state_changed();
973                                         }
974                                         goto exit_with_message;
975                                 case LFUN_DOWN:
976                                         if (boost::next(TEXT()->cursorRow()) != TEXT()->rows().end())
977                                                 TEXT()->cursorDown(view());
978                                         else
979                                                 TEXT()->cursorRight(view());
980                                         moveCursorUpdate(true, false);
981                                         owner->view_state_changed();
982                                         goto exit_with_message;
983                                 default:
984                                         break;
985                                 }
986                         }
987                 }
988         }
989
990         switch (action) {
991
992         case LFUN_ESCAPE:
993         {
994                 if (!view()->available()) break;
995                 // this function should be used always [asierra060396]
996                 UpdatableInset * tli =
997                         view()->theLockingInset();
998                 if (tli) {
999                         UpdatableInset * lock = tli->getLockingInset();
1000
1001                         if (tli == lock) {
1002                                 view()->unlockInset(tli);
1003                                 TEXT()->cursorRight(view());
1004                                 moveCursorUpdate(true, false);
1005                                 owner->view_state_changed();
1006                         } else {
1007                                 tli->unlockInsetInInset(view(),
1008                                                         lock,
1009                                                         true);
1010                         }
1011                         finishUndo();
1012                         // Tell the paragraph dialog that we changed paragraph
1013                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1014                 }
1015         }
1016         break;
1017
1018                 // --- Misc -------------------------------------------
1019         case LFUN_WORDFINDFORWARD  :
1020         case LFUN_WORDFINDBACKWARD : {
1021                 static string last_search;
1022                 string searched_string;
1023
1024                 if (!argument.empty()) {
1025                         last_search = argument;
1026                         searched_string = argument;
1027                 } else {
1028                         searched_string = last_search;
1029                 }
1030                 bool fw = (action == LFUN_WORDFINDFORWARD);
1031                 if (!searched_string.empty()) {
1032                         lyxfind::LyXFind(view(), searched_string, fw);
1033                 }
1034         }
1035         break;
1036
1037         case LFUN_PREFIX:
1038         {
1039                 if (view()->available() && !view()->theLockingInset()) {
1040                         view()->update(TEXT(), BufferView::SELECT);
1041                 }
1042                 owner->message(keyseq.printOptions());
1043         }
1044         break;
1045
1046         // --- Misc -------------------------------------------
1047         case LFUN_EXEC_COMMAND:
1048                 owner->focus_command_buffer();
1049                 break;
1050
1051         case LFUN_CANCEL:                   // RVDK_PATCH_5
1052                 keyseq.reset();
1053                 meta_fake_bit = key_modifier::none;
1054                 if (view()->available())
1055                         // cancel any selection
1056                         dispatch(LFUN_MARK_OFF);
1057                 setMessage(N_("Cancel"));
1058                 break;
1059
1060         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1061         {
1062                 meta_fake_bit = key_modifier::alt;
1063                 setMessage(keyseq.print());
1064         }
1065         break;
1066
1067         case LFUN_READ_ONLY_TOGGLE:
1068                 if (owner->buffer()->lyxvc.inUse()) {
1069                         owner->buffer()->lyxvc.toggleReadOnly();
1070                 } else {
1071                         owner->buffer()->setReadonly(
1072                                 !owner->buffer()->isReadonly());
1073                 }
1074                 break;
1075
1076         case LFUN_CENTER: // this is center and redraw.
1077                 view()->center();
1078                 break;
1079
1080                 // --- Menus -----------------------------------------------
1081         case LFUN_MENUNEW:
1082                 menuNew(argument, false);
1083                 break;
1084
1085         case LFUN_MENUNEWTMPLT:
1086                 menuNew(argument, true);
1087                 break;
1088
1089         case LFUN_CLOSEBUFFER:
1090                 closeBuffer();
1091                 break;
1092
1093         case LFUN_MENUWRITE:
1094                 if (!owner->buffer()->isUnnamed()) {
1095                         string const str = bformat(_("Saving document %1$s..."),
1096                            MakeDisplayPath(owner->buffer()->fileName()));
1097                         owner->message(str);
1098                         MenuWrite(owner->buffer());
1099                         owner->message(str + _(" done."));
1100                 } else
1101                         WriteAs(owner->buffer());
1102                 break;
1103
1104         case LFUN_WRITEAS:
1105                 WriteAs(owner->buffer(), argument);
1106                 break;
1107
1108         case LFUN_MENURELOAD: {
1109                 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
1110                 string text = bformat(_("Any changes will be lost. Are you sure "
1111                         "you want to revert to the saved version of the document %1$s?"), file);
1112                 int const ret = Alert::prompt(_("Revert to saved document?"),
1113                         text, 0, 1, _("&Revert"), _("&Cancel"));
1114
1115                 if (ret == 0)
1116                         view()->reload();
1117                 break;
1118         }
1119
1120         case LFUN_UPDATE:
1121                 Exporter::Export(owner->buffer(), argument, true);
1122                 view()->showErrorList(BufferFormat(*owner->buffer()));
1123                 break;
1124
1125         case LFUN_PREVIEW:
1126                 Exporter::Preview(owner->buffer(), argument);
1127                 view()->showErrorList(BufferFormat(*owner->buffer()));
1128                 break;
1129
1130         case LFUN_BUILDPROG:
1131                 Exporter::Export(owner->buffer(), "program", true);
1132                 view()->showErrorList(_("Build"));
1133                 break;
1134
1135         case LFUN_RUNCHKTEX:
1136                 owner->buffer()->runChktex();
1137                 view()->showErrorList(_("ChkTeX"));
1138                 break;
1139
1140         case LFUN_EXPORT:
1141                 if (argument == "custom")
1142                         owner->getDialogs().showSendto();
1143                 else {
1144                         Exporter::Export(owner->buffer(), argument, false);
1145                         view()->showErrorList(BufferFormat(*owner->buffer()));
1146                 }
1147                 break;
1148
1149         case LFUN_IMPORT:
1150                 doImport(argument);
1151                 break;
1152
1153         case LFUN_QUIT:
1154                 QuitLyX();
1155                 break;
1156
1157         case LFUN_TOCVIEW:
1158         {
1159                 InsetCommandParams p("tableofcontents");
1160                 string const data = InsetCommandMailer::params2string("toc", p);
1161                 owner->getDialogs().show("toc", data, 0);
1162                 break;
1163         }
1164
1165         case LFUN_AUTOSAVE:
1166                 AutoSave(view());
1167                 break;
1168
1169         case LFUN_UNDO:
1170                 view()->undo();
1171                 break;
1172
1173         case LFUN_REDO:
1174                 view()->redo();
1175                 break;
1176
1177         case LFUN_DEPTH_MIN:
1178                 changeDepth(view(), TEXT(false), DEC_DEPTH, false);
1179                 owner->view_state_changed();
1180                 break;
1181
1182         case LFUN_DEPTH_PLUS:
1183                 changeDepth(view(), TEXT(false), INC_DEPTH, false);
1184                 owner->view_state_changed();
1185                 break;
1186
1187         case LFUN_FREEFONT_APPLY:
1188                 apply_freefont(view());
1189                 break;
1190
1191         case LFUN_FREEFONT_UPDATE:
1192                 update_and_apply_freefont(view(), argument);
1193                 break;
1194
1195         case LFUN_RECONFIGURE:
1196                 Reconfigure(view());
1197                 break;
1198
1199 #if 0
1200         case LFUN_FLOATSOPERATE:
1201                 if (argument == "openfoot")
1202                         view()->allFloats(1,0);
1203                 else if (argument == "closefoot")
1204                         view()->allFloats(0,0);
1205                 else if (argument == "openfig")
1206                         view()->allFloats(1,1);
1207                 else if (argument == "closefig")
1208                         view()->allFloats(0,1);
1209                 break;
1210 #else
1211 #ifdef WITH_WARNINGS
1212 //#warning Find another implementation here (or another lyxfunc)!
1213 #endif
1214 #endif
1215         case LFUN_HELP_OPEN:
1216         {
1217                 string const arg = argument;
1218                 if (arg.empty()) {
1219                         setErrorMessage(N_("Missing argument"));
1220                         break;
1221                 }
1222                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1223                 if (fname.empty()) {
1224                         lyxerr << "LyX: unable to find documentation file `"
1225                                << arg << "'. Bad installation?" << endl;
1226                         break;
1227                 }
1228                 owner->message(bformat(_("Opening help file %1$s..."),
1229                         MakeDisplayPath(fname)));
1230                 view()->loadLyXFile(fname, false);
1231                 break;
1232         }
1233
1234                 // --- version control -------------------------------
1235         case LFUN_VC_REGISTER:
1236         {
1237                 if (!ensureBufferClean(view()))
1238                         break;
1239                 if (!owner->buffer()->lyxvc.inUse()) {
1240                         owner->buffer()->lyxvc.registrer();
1241                         view()->reload();
1242                 }
1243         }
1244         break;
1245
1246         case LFUN_VC_CHECKIN:
1247         {
1248                 if (!ensureBufferClean(view()))
1249                         break;
1250                 if (owner->buffer()->lyxvc.inUse()
1251                     && !owner->buffer()->isReadonly()) {
1252                         owner->buffer()->lyxvc.checkIn();
1253                         view()->reload();
1254                 }
1255         }
1256         break;
1257
1258         case LFUN_VC_CHECKOUT:
1259         {
1260                 if (!ensureBufferClean(view()))
1261                         break;
1262                 if (owner->buffer()->lyxvc.inUse()
1263                     && owner->buffer()->isReadonly()) {
1264                         owner->buffer()->lyxvc.checkOut();
1265                         view()->reload();
1266                 }
1267         }
1268         break;
1269
1270         case LFUN_VC_REVERT:
1271         {
1272                 owner->buffer()->lyxvc.revert();
1273                 view()->reload();
1274         }
1275         break;
1276
1277         case LFUN_VC_UNDO:
1278         {
1279                 owner->buffer()->lyxvc.undoLast();
1280                 view()->reload();
1281         }
1282         break;
1283
1284         // --- buffers ----------------------------------------
1285
1286         case LFUN_SWITCHBUFFER:
1287                 view()->buffer(bufferlist.getBuffer(argument));
1288                 break;
1289
1290         case LFUN_FILE_NEW:
1291                 NewFile(view(), argument);
1292                 break;
1293
1294         case LFUN_FILE_OPEN:
1295                 open(argument);
1296                 break;
1297
1298         case LFUN_LAYOUT_TABULAR:
1299             if (view()->theLockingInset()) {
1300                 if (view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1301                     InsetTabular * inset = static_cast<InsetTabular *>
1302                         (view()->theLockingInset());
1303                     inset->openLayoutDialog(view());
1304                 } else if (view()->theLockingInset()->
1305                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1306                     InsetTabular * inset = static_cast<InsetTabular *>(
1307                         view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1308                     inset->openLayoutDialog(view());
1309                 }
1310             }
1311             break;
1312
1313         case LFUN_DROP_LAYOUTS_CHOICE:
1314                 owner->getToolbar().openLayoutList();
1315                 break;
1316
1317         case LFUN_MENU_OPEN_BY_NAME:
1318                 owner->getMenubar().openByName(argument);
1319                 break; // RVDK_PATCH_5
1320
1321         // --- lyxserver commands ----------------------------
1322
1323
1324         case LFUN_GETNAME:
1325                 setMessage(owner->buffer()->fileName());
1326                 lyxerr[Debug::INFO] << "FNAME["
1327                                << owner->buffer()->fileName()
1328                                << "] " << endl;
1329                 break;
1330
1331         case LFUN_NOTIFY:
1332         {
1333                 dispatch_buffer = keyseq.print();
1334                 lyxserver->notifyClient(dispatch_buffer);
1335         }
1336         break;
1337
1338         case LFUN_GOTOFILEROW:
1339         {
1340                 string file_name;
1341                 int row;
1342                 istringstream istr(argument.c_str());
1343                 istr >> file_name >> row;
1344                 // Must replace extension of the file to be .lyx and get full path
1345                 string const s(ChangeExtension(file_name, ".lyx"));
1346
1347                 // Either change buffer or load the file
1348                 if (bufferlist.exists(s)) {
1349                         view()->buffer(bufferlist.getBuffer(s));
1350                 } else {
1351                         view()->loadLyXFile(s);
1352                 }
1353
1354                 view()->setCursorFromRow(row);
1355
1356                 view()->center();
1357                 // see BufferView_pimpl::center()
1358                 view()->updateScrollbar();
1359         }
1360         break;
1361
1362         case LFUN_GOTO_PARAGRAPH:
1363         {
1364                 istringstream istr(argument.c_str());
1365
1366                 int id;
1367                 istr >> id;
1368                 ParIterator par = owner->buffer()->getParFromID(id);
1369                 if (par == owner->buffer()->par_iterator_end()) {
1370                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1371                                             << id << ']' << endl;
1372                         break;
1373                 } else {
1374                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1375                                             << " found." << endl;
1376                 }
1377
1378                 if (view()->theLockingInset())
1379                         view()->unlockInset(view()->theLockingInset());
1380                 if (par->inInset()) {
1381                         FuncRequest cmd(view(), LFUN_INSET_EDIT, "left");
1382                         par->inInset()->localDispatch(cmd);
1383                 }
1384                 // Set the cursor
1385                 view()->getLyXText()->setCursor(par.pit(), 0);
1386                 view()->switchKeyMap();
1387                 owner->view_state_changed();
1388
1389                 view()->center();
1390                 // see BufferView_pimpl::center()
1391                 view()->updateScrollbar();
1392         }
1393         break;
1394
1395         // --- insert characters ----------------------------------------
1396
1397         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1398         case LFUN_MATH_EXTERN:
1399         case LFUN_MATH_NUMBER:
1400         case LFUN_MATH_NONUMBER:
1401         case LFUN_MATH_LIMITS:
1402         {
1403                 setErrorMessage(N_("This is only allowed in math mode!"));
1404         }
1405         break;
1406
1407         // passthrough hat and underscore outside mathed:
1408         case LFUN_SUBSCRIPT:
1409                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1410                 break;
1411         case LFUN_SUPERSCRIPT:
1412                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1413                 break;
1414
1415         case LFUN_DIALOG_SHOW: {
1416                 string const name = ev.getArg(0);
1417                 string data = trim(ev.argument.substr(name.size()));
1418
1419                 if (name == "character") {
1420                         data = freefont2string();
1421                         if (!data.empty())
1422                                 owner->getDialogs().show("character", data);
1423                 } else if (name == "document")
1424                         owner->getDialogs().showDocument();
1425                 else if (name == "findreplace")
1426                         owner->getDialogs().showSearch();
1427                 else if (name == "forks")
1428                         owner->getDialogs().showForks();
1429                 else if (name == "preamble")
1430                         owner->getDialogs().showPreamble();
1431                 else if (name == "preferences")
1432                         owner->getDialogs().showPreferences();
1433                 else if (name == "print")
1434                         owner->getDialogs().showPrint();
1435                 else if (name == "spellchecker")
1436                         owner->getDialogs().showSpellchecker();
1437                 else
1438                         owner->getDialogs().show(name, data);
1439                 break;
1440         }
1441
1442         case LFUN_DIALOG_SHOW_NEW_INSET: {
1443                 string const & name = argument;
1444                 string data;
1445                 if (name == "bibitem" ||
1446                     name == "bibtex" ||
1447                     name == "include" ||
1448                     name == "index" ||
1449                     name == "ref" ||
1450                     name == "toc" ||
1451                     name == "url") {
1452                         InsetCommandParams p(name);
1453                         data = InsetCommandMailer::params2string(name, p);
1454                 } else if (name == "citation") {
1455                         InsetCommandParams p("cite");
1456                         data = InsetCommandMailer::params2string(name, p);
1457                 }
1458                 owner->getDialogs().show(name, data, 0);
1459         }
1460         break;
1461
1462         case LFUN_DIALOG_SHOW_NEXT_INSET: {
1463         }
1464         break;
1465
1466         case LFUN_DIALOG_UPDATE: {
1467                 string const & name = argument;
1468                 // Can only update a dialog connected to an existing inset
1469                 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1470                 if (inset) {
1471                         FuncRequest fr(view(), LFUN_INSET_DIALOG_UPDATE,
1472                                        ev.argument);
1473                         inset->localDispatch(fr);
1474                 } else if (name == "paragraph") {
1475                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1476                 }
1477         }
1478         break;
1479
1480         case LFUN_DIALOG_HIDE:
1481                 Dialogs::hide(argument, 0);
1482                 break;
1483
1484         case LFUN_DIALOG_DISCONNECT_INSET:
1485                 owner->getDialogs().disconnect(argument);
1486                 break;
1487
1488         case LFUN_CHILDOPEN:
1489         {
1490                 string const filename =
1491                         MakeAbsPath(argument,
1492                                     owner->buffer()->filePath());
1493                 setMessage(N_("Opening child document ") +
1494                            MakeDisplayPath(filename) + "...");
1495                 view()->savePosition(0);
1496                 if (bufferlist.exists(filename))
1497                         view()->buffer(bufferlist.getBuffer(filename));
1498                 else
1499                         view()->loadLyXFile(filename);
1500         }
1501         break;
1502
1503         case LFUN_TOGGLECURSORFOLLOW:
1504                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1505                 break;
1506
1507         case LFUN_KMAP_OFF:
1508                 owner->getIntl().KeyMapOn(false);
1509                 break;
1510
1511         case LFUN_KMAP_PRIM:
1512                 owner->getIntl().KeyMapPrim();
1513                 break;
1514
1515         case LFUN_KMAP_SEC:
1516                 owner->getIntl().KeyMapSec();
1517                 break;
1518
1519         case LFUN_KMAP_TOGGLE:
1520                 owner->getIntl().ToggleKeyMap();
1521                 break;
1522
1523         case LFUN_SEQUENCE:
1524         {
1525                 // argument contains ';'-terminated commands
1526                 while (!argument.empty()) {
1527                         string first;
1528                         argument = split(argument, first, ';');
1529                         dispatch(first);
1530                 }
1531         }
1532         break;
1533
1534         case LFUN_SAVEPREFERENCES:
1535         {
1536                 Path p(user_lyxdir);
1537                 lyxrc.write("preferences");
1538         }
1539         break;
1540
1541         case LFUN_SCREEN_FONT_UPDATE:
1542         {
1543                 // handle the screen font changes.
1544                 lyxrc.set_font_norm_type();
1545                 lyx_gui::update_fonts();
1546                 // We also need to empty the textcache so that
1547                 // the buffer will be formatted correctly after
1548                 // a zoom change.
1549                 textcache.clear();
1550                 // Of course we should only do the resize and the textcache.clear
1551                 // if values really changed...but not very important right now. (Lgb)
1552                 // All visible buffers will need resize
1553                 view()->resize();
1554                 view()->repaint();
1555         }
1556         break;
1557
1558         case LFUN_SET_COLOR:
1559         {
1560                 string lyx_name;
1561                 string const x11_name = split(argument, lyx_name, ' ');
1562                 if (lyx_name.empty() || x11_name.empty()) {
1563                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1564                                                 " <x11_name>"));
1565                         break;
1566                         }
1567
1568                 bool const graphicsbg_changed =
1569                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1570                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1571
1572                 if (!lcolor.setColor(lyx_name, x11_name)) {
1573                         setErrorMessage(
1574                                 bformat(_("Set-color \"%1$s\" failed "
1575                                                   "- color is undefined or "
1576                                                   "may not be redefined"), lyx_name));
1577                         break;
1578                 }
1579
1580                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1581
1582                 if (graphicsbg_changed) {
1583 #ifdef WITH_WARNINGS
1584 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1585 #endif
1586 #if 0
1587                         grfx::GCache & gc = grfx::GCache::get();
1588                         gc.changeDisplay(true);
1589 #endif
1590                 }
1591
1592                 view()->repaint();
1593                 break;
1594         }
1595
1596         case LFUN_MESSAGE:
1597                 owner->message(argument);
1598                 break;
1599
1600         case LFUN_FORKS_KILL:
1601         {
1602                 if (!isStrInt(argument))
1603                         break;
1604
1605                 pid_t const pid = strToInt(argument);
1606                 ForkedcallsController & fcc = ForkedcallsController::get();
1607                 fcc.kill(pid);
1608                 break;
1609         }
1610
1611         case LFUN_TOOLTIPS_TOGGLE:
1612                 owner->getDialogs().toggleTooltips();
1613                 break;
1614
1615         case LFUN_EXTERNAL_EDIT: {
1616                 InsetExternal()
1617                         .localDispatch(FuncRequest(view(), action, argument));
1618                 break;
1619         }
1620
1621         default:
1622                 // Then if it was none of the above
1623                 // Trying the BufferView::pimpl dispatch:
1624                 if (!view()->dispatch(ev))
1625                         lyxerr << "A truly unknown func ["
1626                                << lyxaction.getActionName(ev.action) << "]!"
1627                                << endl;
1628                 break;
1629         } // end of switch
1630
1631 exit_with_message:
1632
1633         view()->owner()->updateLayoutChoice();
1634
1635         if (view()->available()) {
1636                 view()->fitCursor();
1637
1638                 // If we executed a mutating lfun, mark the buffer as dirty
1639                 if (!lyxaction.funcHasFlag(ev.action, LyXAction::NoBuffer)
1640                     && !lyxaction.funcHasFlag(ev.action, LyXAction::ReadOnly))
1641                         view()->buffer()->markDirty();
1642         }
1643
1644         sendDispatchMessage(getMessage(), ev, verbose);
1645 }
1646
1647
1648 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1649 {
1650         owner->updateMenubar();
1651         owner->updateToolbar();
1652
1653         if (ev.action == LFUN_SELFINSERT || !verbose) {
1654                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1655                 if (!msg.empty())
1656                         owner->message(msg);
1657                 return;
1658         }
1659
1660         string dispatch_msg = msg;
1661         if (!dispatch_msg.empty())
1662                 dispatch_msg += ' ';
1663
1664         string comname = lyxaction.getActionName(ev.action);
1665
1666         int pseudoaction = ev.action;
1667         bool argsadded = false;
1668
1669         if (!ev.argument.empty()) {
1670                 // the pseudoaction is useful for the bindings
1671                 pseudoaction = lyxaction.searchActionArg(ev.action, ev.argument);
1672
1673                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
1674                         pseudoaction = ev.action;
1675                 } else {
1676                         comname += ' ' + ev.argument;
1677                         argsadded = true;
1678                 }
1679         }
1680
1681         string const shortcuts = toplevel_keymap->findbinding(pseudoaction);
1682
1683         if (!shortcuts.empty()) {
1684                 comname += ": " + shortcuts;
1685         } else if (!argsadded && !ev.argument.empty()) {
1686                 comname += ' ' + ev.argument;
1687         }
1688
1689         if (!comname.empty()) {
1690                 comname = rtrim(comname);
1691                 dispatch_msg += '(' + comname + ')';
1692         }
1693
1694         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1695         if (!dispatch_msg.empty())
1696                 owner->message(dispatch_msg);
1697 }
1698
1699
1700 void LyXFunc::setupLocalKeymap()
1701 {
1702         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1703         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1704 }
1705
1706
1707 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1708 {
1709         string initpath = lyxrc.document_path;
1710         string filename(name);
1711
1712         if (view()->available()) {
1713                 string const trypath = owner->buffer()->filePath();
1714                 // If directory is writeable, use this as default.
1715                 if (IsDirWriteable(trypath))
1716                         initpath = trypath;
1717         }
1718
1719         static int newfile_number;
1720
1721         if (filename.empty()) {
1722                 filename = AddName(lyxrc.document_path,
1723                             "newfile" + tostr(++newfile_number) + ".lyx");
1724                 FileInfo fi(filename);
1725                 while (bufferlist.exists(filename) || fi.readable()) {
1726                         ++newfile_number;
1727                         filename = AddName(lyxrc.document_path,
1728                                     "newfile" + tostr(newfile_number) +
1729                                     ".lyx");
1730                         fi.newFile(filename);
1731                 }
1732         }
1733
1734         // The template stuff
1735         string templname;
1736         if (fromTemplate) {
1737                 FileDialog fileDlg(_("Select template file"),
1738                         LFUN_SELECT_FILE_SYNC,
1739                         make_pair(string(_("Documents|#o#O")),
1740                                   string(lyxrc.document_path)),
1741                         make_pair(string(_("Templates|#T#t")),
1742                                   string(lyxrc.template_path)));
1743
1744                 FileDialog::Result result =
1745                         fileDlg.open(lyxrc.template_path,
1746                                        _("*.lyx| LyX Documents (*.lyx)"));
1747
1748                 if (result.first == FileDialog::Later)
1749                         return;
1750
1751                 string const fname = result.second;
1752
1753                 if (fname.empty())
1754                         return;
1755                 templname = fname;
1756         }
1757
1758         view()->newFile(filename, templname, !name.empty());
1759 }
1760
1761
1762 void LyXFunc::open(string const & fname)
1763 {
1764         string initpath = lyxrc.document_path;
1765
1766         if (view()->available()) {
1767                 string const trypath = owner->buffer()->filePath();
1768                 // If directory is writeable, use this as default.
1769                 if (IsDirWriteable(trypath))
1770                         initpath = trypath;
1771         }
1772
1773         string filename;
1774
1775         if (fname.empty()) {
1776                 FileDialog fileDlg(_("Select document to open"),
1777                         LFUN_FILE_OPEN,
1778                         make_pair(string(_("Documents|#o#O")),
1779                                   string(lyxrc.document_path)),
1780                         make_pair(string(_("Examples|#E#e")),
1781                                   string(AddPath(system_lyxdir, "examples"))));
1782
1783                 FileDialog::Result result =
1784                         fileDlg.open(initpath,
1785                                        _("*.lyx| LyX Documents (*.lyx)"));
1786
1787                 if (result.first == FileDialog::Later)
1788                         return;
1789
1790                 filename = result.second;
1791
1792                 // check selected filename
1793                 if (filename.empty()) {
1794                         owner->message(_("Canceled."));
1795                         return;
1796                 }
1797         } else
1798                 filename = fname;
1799
1800         // get absolute path of file and add ".lyx" to the filename if
1801         // necessary
1802         string const fullpath = FileSearch(string(), filename, "lyx");
1803         if (!fullpath.empty()) {
1804                 filename = fullpath;
1805         }
1806
1807         string const disp_fn(MakeDisplayPath(filename));
1808
1809         // if the file doesn't exist, let the user create one
1810         FileInfo const f(filename, true);
1811         if (!f.exist()) {
1812                 // the user specifically chose this name. Believe them.
1813                 view()->newFile(filename, "", true);
1814                 return;
1815         }
1816
1817         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1818
1819         string str2;
1820         if (view()->loadLyXFile(filename)) {
1821                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1822         } else {
1823                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1824         }
1825         owner->message(str2);
1826 }
1827
1828
1829 void LyXFunc::doImport(string const & argument)
1830 {
1831         string format;
1832         string filename = split(argument, format, ' ');
1833
1834         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1835                             << " file: " << filename << endl;
1836
1837         // need user interaction
1838         if (filename.empty()) {
1839                 string initpath = lyxrc.document_path;
1840
1841                 if (view()->available()) {
1842                         string const trypath = owner->buffer()->filePath();
1843                         // If directory is writeable, use this as default.
1844                         if (IsDirWriteable(trypath))
1845                                 initpath = trypath;
1846                 }
1847
1848                 string const text = bformat(_("Select %1$s file to import"),
1849                         formats.prettyName(format));
1850
1851                 FileDialog fileDlg(text,
1852                         LFUN_IMPORT,
1853                         make_pair(string(_("Documents|#o#O")),
1854                                   string(lyxrc.document_path)),
1855                         make_pair(string(_("Examples|#E#e")),
1856                                   string(AddPath(system_lyxdir, "examples"))));
1857
1858                 string const extension = "*." + formats.extension(format)
1859                         + "| " + formats.prettyName(format)
1860                         + " (*." + formats.extension(format) + ')';
1861
1862                 FileDialog::Result result = fileDlg.open(initpath,
1863                                                            extension);
1864
1865                 if (result.first == FileDialog::Later)
1866                         return;
1867
1868                 filename = result.second;
1869
1870                 // check selected filename
1871                 if (filename.empty())
1872                         owner->message(_("Canceled."));
1873         }
1874
1875         if (filename.empty())
1876                 return;
1877
1878         // get absolute path of file
1879         filename = MakeAbsPath(filename);
1880
1881         string const lyxfile = ChangeExtension(filename, ".lyx");
1882
1883         // Check if the document already is open
1884         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1885                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1886                         owner->message(_("Canceled."));
1887                         return;
1888                 }
1889         }
1890
1891         // if the file exists already, and we didn't do
1892         // -i lyx thefile.lyx, warn
1893         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1894                 string const file = MakeDisplayPath(lyxfile, 30);
1895
1896                 string text = bformat(_("The document %1$s already exists.\n\n"
1897                         "Do you want to over-write that document?"), file);
1898                 int const ret = Alert::prompt(_("Over-write document?"),
1899                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1900
1901                 if (ret == 1) {
1902                         owner->message(_("Canceled."));
1903                         return;
1904                 }
1905         }
1906
1907         Importer::Import(owner, filename, format);
1908 }
1909
1910
1911 void LyXFunc::closeBuffer()
1912 {
1913         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1914                 if (bufferlist.empty()) {
1915                         // need this otherwise SEGV may occur while 
1916                         // trying to set variables that don't exist
1917                         // since there's no current buffer
1918                         owner->getDialogs().hideBufferDependent();
1919                 } else {
1920                         view()->buffer(bufferlist.first());
1921                 }
1922         }
1923 }
1924
1925
1926 // Each "owner" should have it's own message method. lyxview and
1927 // the minibuffer would use the minibuffer, but lyxserver would
1928 // send an ERROR signal to its client.  Alejandro 970603
1929 // This func is bit problematic when it comes to NLS, to make the
1930 // lyx servers client be language indepenent we must not translate
1931 // strings sent to this func.
1932 void LyXFunc::setErrorMessage(string const & m) const
1933 {
1934         dispatch_buffer = m;
1935         errorstat = true;
1936 }
1937
1938
1939 void LyXFunc::setMessage(string const & m) const
1940 {
1941         dispatch_buffer = m;
1942 }
1943
1944
1945 void LyXFunc::setStatusMessage(string const & m) const
1946 {
1947         status_buffer = m;
1948 }
1949
1950
1951 string const LyXFunc::view_status_message()
1952 {
1953         // When meta-fake key is pressed, show the key sequence so far + "M-".
1954         if (wasMetaKey()) {
1955                 return keyseq.print() + "M-";
1956         }
1957
1958         // Else, when a non-complete key sequence is pressed,
1959         // show the available options.
1960         if (keyseq.length() > 0 && !keyseq.deleted()) {
1961                 return keyseq.printOptions();
1962         }
1963
1964         if (!view()->available())
1965                 return _("Welcome to LyX!");
1966
1967         return currentState(view());
1968 }
1969
1970
1971 BufferView * LyXFunc::view() const
1972 {
1973         Assert(owner);
1974         return owner->view().get();
1975 }