]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
The QNote dialog
[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                         default:
519                                 break;
520                 }
521                 break;
522         }
523
524         case LFUN_MATH_MUTATE:
525                 if (mathcursor)
526                         //flag.setOnOff(mathcursor->formula()->hullType() == ev.argument);
527                         flag.setOnOff(false);
528                 else
529                         disable = true;
530                 break;
531
532         // we just need to be in math mode to enable that
533         case LFUN_MATH_SIZE:
534         case LFUN_MATH_SPACE:
535         case LFUN_MATH_LIMITS:
536         case LFUN_MATH_NONUMBER:
537         case LFUN_MATH_NUMBER:
538         case LFUN_MATH_EXTERN:
539                 disable = !mathcursor;
540                 break;
541
542         case LFUN_DIALOG_SHOW: {
543                 string const name = ev.getArg(0);
544                 if (!buf) {
545                         disable = !(name == "aboutlyx" ||
546                                     name == "file" ||
547                                     name == "forks" ||
548                                     name == "preferences" ||
549                                     name == "texinfo");
550                         break;
551                 }
552
553                 if (name == "print") {
554                         disable = !Exporter::IsExportable(buf, "dvi") ||
555                                 lyxrc.print_command == "none";
556                 } else if (name == "character") {
557                         UpdatableInset * tli = view()->theLockingInset();
558                         disable = tli && tli->lyxCode() == Inset::ERT_CODE;
559                 } else if (name == "vclog") {
560                         disable = !buf->lyxvc.inUse();
561                 } else if (name == "latexlog") {
562                         disable = !IsFileReadable(buf->getLogName().second);
563                 }
564                 break;
565         }
566
567         default:
568                 break;
569         }
570
571         // the functions which insert insets
572         Inset::Code code = Inset::NO_CODE;
573         switch (ev.action) {
574         case LFUN_DIALOG_SHOW_NEW_INSET:
575                 if (ev.argument == "bibitem")
576                         code = Inset::BIBITEM_CODE;
577                 else if (ev.argument == "bibtex")
578                         code = Inset::BIBTEX_CODE;
579                 else if (ev.argument == "citation")
580                         code = Inset::CITE_CODE;
581                 else if (ev.argument == "ert")
582                         code = Inset::ERT_CODE;
583                 else if (ev.argument == "external")
584                         code = Inset::EXTERNAL_CODE;
585                 else if (ev.argument == "float")
586                         code = Inset::FLOAT_CODE;
587                 else if (ev.argument == "graphics")
588                         code = Inset::GRAPHICS_CODE;
589                 else if (ev.argument == "include")
590                         code = Inset::INCLUDE_CODE;
591                 else if (ev.argument == "index")
592                         code = Inset::INDEX_CODE;
593                 else if (ev.argument == "label")
594                         code = Inset::LABEL_CODE;
595                 else if (ev.argument == "minipage")
596                         code = Inset::MINIPAGE_CODE;
597                 else if (ev.argument == "ref")
598                         code = Inset::REF_CODE;
599                 else if (ev.argument == "toc")
600                         code = Inset::TOC_CODE;
601                 else if (ev.argument == "url")
602                         code = Inset::URL_CODE;
603                 else if (ev.argument == "wrap")
604                         code = Inset::WRAP_CODE;
605                 break;
606
607         case LFUN_INSET_ERT:
608                 code = Inset::ERT_CODE;
609                 break;
610         case LFUN_INSET_FOOTNOTE:
611                 code = Inset::FOOT_CODE;
612                 break;
613         case LFUN_TABULAR_INSERT:
614                 code = Inset::TABULAR_CODE;
615                 break;
616         case LFUN_INSET_MARGINAL:
617                 code = Inset::MARGIN_CODE;
618                 break;
619         case LFUN_INSET_MINIPAGE:
620                 code = Inset::MINIPAGE_CODE;
621                 break;
622         case LFUN_INSET_FLOAT:
623         case LFUN_INSET_WIDE_FLOAT:
624                 code = Inset::FLOAT_CODE;
625                 break;
626         case LFUN_INSET_WRAP:
627                 code = Inset::WRAP_CODE;
628                 break;
629         case LFUN_FLOAT_LIST:
630                 code = Inset::FLOAT_LIST_CODE;
631                 break;
632 #if 0
633         case LFUN_INSET_LIST:
634                 code = Inset::LIST_CODE;
635                 break;
636         case LFUN_INSET_THEOREM:
637                 code = Inset::THEOREM_CODE;
638                 break;
639 #endif
640         case LFUN_INSET_CAPTION:
641                 code = Inset::CAPTION_CODE;
642                 break;
643         case LFUN_INSERT_NOTE:
644                 code = Inset::NOTE_CODE;
645                 break;
646         case LFUN_INSERT_LABEL:
647                 code = Inset::LABEL_CODE;
648                 break;
649         case LFUN_INSET_OPTARG:
650                 code = Inset::OPTARG_CODE;
651                 break;
652         case LFUN_ENVIRONMENT_INSERT:
653                 code = Inset::MINIPAGE_CODE;
654                 break;
655         case LFUN_INDEX_INSERT:
656                 code = Inset::INDEX_CODE;
657                 break;
658         case LFUN_INDEX_PRINT:
659                 code = Inset::INDEX_PRINT_CODE;
660                 break;
661         case LFUN_TOC_INSERT:
662                 code = Inset::TOC_CODE;
663                 break;
664         case LFUN_HTMLURL:
665         case LFUN_URL:
666                 code = Inset::URL_CODE;
667                 break;
668         case LFUN_QUOTE:
669                 // always allow this, since we will inset a raw quote
670                 // if an inset is not allowed.
671                 break;
672         case LFUN_HYPHENATION:
673         case LFUN_LIGATURE_BREAK:
674         case LFUN_HFILL:
675         case LFUN_MENU_SEPARATOR:
676         case LFUN_LDOTS:
677         case LFUN_END_OF_SENTENCE:
678                 code = Inset::SPECIALCHAR_CODE;
679                 break;
680         case LFUN_SPACE_INSERT:
681                 // slight hack: we know this is allowed in math mode
682                 if (!mathcursor)
683                         code = Inset::SPACE_CODE;
684                 break;
685         default:
686                 break;
687         }
688         if (code != Inset::NO_CODE && tli && !tli->insetAllowed(code))
689                 disable = true;
690
691         if (disable)
692                 flag.disabled(true);
693
694         // A few general toggles
695         switch (ev.action) {
696         case LFUN_TOOLTIPS_TOGGLE:
697                 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
698                 break;
699
700         case LFUN_READ_ONLY_TOGGLE:
701                 flag.setOnOff(buf->isReadonly());
702                 break;
703         case LFUN_APPENDIX:
704                 flag.setOnOff(TEXT(false)->cursor.par()->params().startOfAppendix());
705                 break;
706         case LFUN_SWITCHBUFFER:
707                 // toggle on the current buffer, but do not toggle off
708                 // the other ones (is that a good idea?)
709                 if (ev.argument == buf->fileName())
710                         flag.setOnOff(true);
711                 break;
712         case LFUN_TRACK_CHANGES:
713                 flag.setOnOff(buf->params.tracking_changes);
714                 break;
715         default:
716                 break;
717         }
718
719         // the font related toggles
720         if (!mathcursor) {
721                 LyXFont const & font = TEXT(false)->real_current_font;
722                 switch (ev.action) {
723                 case LFUN_EMPH:
724                         flag.setOnOff(font.emph() == LyXFont::ON);
725                         break;
726                 case LFUN_NOUN:
727                         flag.setOnOff(font.noun() == LyXFont::ON);
728                         break;
729                 case LFUN_BOLD:
730                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
731                         break;
732                 case LFUN_SANS:
733                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
734                         break;
735                 case LFUN_ROMAN:
736                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
737                         break;
738                 case LFUN_CODE:
739                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
740                         break;
741                 default:
742                         break;
743                 }
744         } else {
745                 string tc = mathcursor->getLastCode();
746                 switch (ev.action) {
747                 case LFUN_BOLD:
748                         flag.setOnOff(tc == "mathbf");
749                         break;
750                 case LFUN_SANS:
751                         flag.setOnOff(tc == "mathsf");
752                         break;
753                 case LFUN_EMPH:
754                         flag.setOnOff(tc == "mathcal");
755                         break;
756                 case LFUN_ROMAN:
757                         flag.setOnOff(tc == "mathrm");
758                         break;
759                 case LFUN_CODE:
760                         flag.setOnOff(tc == "mathtt");
761                         break;
762                 case LFUN_NOUN:
763                         flag.setOnOff(tc == "mathbb");
764                         break;
765                 case LFUN_DEFAULT:
766                         flag.setOnOff(tc == "mathnormal");
767                         break;
768                 default:
769                         break;
770                 }
771         }
772
773         // this one is difficult to get right. As a half-baked
774         // solution, we consider only the first action of the sequence
775         if (ev.action == LFUN_SEQUENCE) {
776                 // argument contains ';'-terminated commands
777                 flag = getStatus(lyxaction.LookupFunc(token(ev.argument, ';', 0)));
778         }
779
780         return flag;
781 }
782
783
784 void LyXFunc::dispatch(string const & s, bool verbose)
785 {
786         int const action = lyxaction.LookupFunc(s);
787
788         if (action == LFUN_UNKNOWN_ACTION) {
789                 owner->message(bformat(_("Unknown function (%1$s)"), s));
790                 return;
791         }
792
793         dispatch(action, verbose);
794 }
795
796
797 void LyXFunc::dispatch(int ac, bool verbose)
798 {
799         dispatch(lyxaction.retrieveActionArg(ac), verbose);
800 }
801
802 namespace {
803         bool ensureBufferClean(BufferView * bv) {
804
805                 Buffer & buf = *bv->buffer();
806                 if (buf.isClean())
807                         return true;
808                 
809                 string const file = MakeDisplayPath(buf.fileName(), 30);
810                 string text = bformat(_("The document %1$s has unsaved "
811                                         "changes.\n\nDo you want to save "
812                                         "the document?"), file);
813                 int const ret = Alert::prompt(_("Save changed document?"),
814                                               text, 0, 1, _("&Save"), 
815                                               _("&Cancel"));
816
817                 if (ret == 0) 
818                         bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
819
820                 return buf.isClean();
821         }
822 } //namespace anon
823
824 void LyXFunc::dispatch(FuncRequest const & ev, bool verbose)
825 {
826         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: action[" << ev.action
827                               <<"] arg[" << ev.argument << ']' << endl;
828
829         // we have not done anything wrong yet.
830         errorstat = false;
831         dispatch_buffer.erase();
832
833 #ifdef NEW_DISPATCHER
834         // We try do call the most specific dispatcher first:
835         //  1. the lockinginset's dispatch
836         //  2. the bufferview's dispatch
837         //  3. the lyxview's dispatch
838 #endif
839
840         selection_possible = false;
841
842         string argument = ev.argument;
843         kb_action action = ev.action;
844
845         // We cannot use this function here
846         if (getStatus(ev).disabled()) {
847                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
848                        << lyxaction.getActionName(action)
849                        << " [" << action << "] is disabled at this location"
850                        << endl;
851                 setErrorMessage(getStatusMessage());
852                 goto exit_with_message;
853         }
854
855         if (view()->available())
856                 view()->hideCursor();
857
858         if (view()->available() && view()->theLockingInset()) {
859                 Inset::RESULT result;
860                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
861                                      (!keyseq.deleted())))
862                 {
863                         UpdatableInset * inset = view()->theLockingInset();
864 #if 1
865                         int inset_x;
866                         int dummy_y;
867                         inset->getCursorPos(view(), inset_x, dummy_y);
868 #endif
869                         if ((action == LFUN_UNKNOWN_ACTION)
870                             && argument.empty()) {
871                                 argument = encoded_last_key;
872                         }
873
874                         // the insets can't try to handle this,
875                         // a table cell in the dummy position will
876                         // lock its insettext, the insettext will
877                         // pass it the bufferview, and succeed,
878                         // so it will stay not locked. Not good
879                         // if we've just done LFUN_ESCAPE (which
880                         // injects an LFUN_PARAGRAPH_UPDATE)
881                         if (action == LFUN_PARAGRAPH_UPDATE) {
882                                 view()->dispatch(ev);
883                                 goto exit_with_message;
884                         }
885
886                         // Undo/Redo is a bit tricky for insets.
887                         if (action == LFUN_UNDO) {
888                                 view()->undo();
889                                 goto exit_with_message;
890                         } else if (action == LFUN_REDO) {
891                                 view()->redo();
892                                 goto exit_with_message;
893                         } else if (((result=inset->
894                                      // Hand-over to inset's own dispatch:
895                                      localDispatch(FuncRequest(view(), action, argument))) ==
896                                     DISPATCHED) ||
897                                    (result == DISPATCHED_NOUPDATE))
898                                 goto exit_with_message;
899                                         // If UNDISPATCHED, just soldier on
900                         else if (result == FINISHED) {
901                                 owner->clearMessage();
902                                 goto exit_with_message;
903                                 // We do not need special RTL handling here:
904                                 // FINISHED means that the cursor should be
905                                 // one position after the inset.
906                         } else if (result == FINISHED_RIGHT) {
907                                 TEXT()->cursorRight(view());
908                                 moveCursorUpdate(true, false);
909                                 owner->clearMessage();
910                                 goto exit_with_message;
911                         } else if (result == FINISHED_UP) {
912                                 if (TEXT()->cursor.irow() != TEXT()->rows().begin()) {
913 #if 1
914                                         TEXT()->setCursorFromCoordinates(
915                                                 TEXT()->cursor.ix() + inset_x,
916                                                 TEXT()->cursor.iy() -
917                                                 TEXT()->cursor.irow()->baseline() - 1);
918                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
919 #else
920                                         TEXT()->cursorUp(view());
921 #endif
922                                         moveCursorUpdate(true, false);
923                                 } else {
924                                         view()->update(TEXT(), BufferView::SELECT);
925                                 }
926                                 owner->clearMessage();
927                                 goto exit_with_message;
928                         } else if (result == FINISHED_DOWN) {
929                                 if (boost::next(TEXT()->cursor.irow()) != TEXT()->rows().end()) {
930 #if 1
931                                         TEXT()->setCursorFromCoordinates(
932                                                 TEXT()->cursor.ix() + inset_x,
933                                                 TEXT()->cursor.iy() -
934                                                 TEXT()->cursor.irow()->baseline() +
935                                                 TEXT()->cursor.irow()->height() + 1);
936                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
937 #else
938                                         TEXT()->cursorDown(view());
939 #endif
940                                 } else {
941                                         TEXT()->cursorRight(view());
942                                 }
943                                 moveCursorUpdate(true, false);
944                                 owner->clearMessage();
945                                 goto exit_with_message;
946                         }
947 #warning I am not sure this is still right, please have a look! (Jug 20020417)
948                         else { // result == UNDISPATCHED
949                                 //setMessage(N_("Text mode"));
950                                 switch (action) {
951                                 case LFUN_UNKNOWN_ACTION:
952                                 case LFUN_BREAKPARAGRAPH:
953                                 case LFUN_BREAKLINE:
954                                         TEXT()->cursorRight(view());
955                                         view()->switchKeyMap();
956                                         owner->view_state_changed();
957                                         break;
958                                 case LFUN_RIGHT:
959                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
960                                                 TEXT()->cursorRight(view());
961                                                 moveCursorUpdate(true, false);
962                                                 owner->view_state_changed();
963                                         }
964                                         goto exit_with_message;
965                                 case LFUN_LEFT:
966                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
967                                                 TEXT()->cursorRight(view());
968                                                 moveCursorUpdate(true, false);
969                                                 owner->view_state_changed();
970                                         }
971                                         goto exit_with_message;
972                                 case LFUN_DOWN:
973                                         if (boost::next(TEXT()->cursorRow()) != TEXT()->rows().end())
974                                                 TEXT()->cursorDown(view());
975                                         else
976                                                 TEXT()->cursorRight(view());
977                                         moveCursorUpdate(true, false);
978                                         owner->view_state_changed();
979                                         goto exit_with_message;
980                                 default:
981                                         break;
982                                 }
983                         }
984                 }
985         }
986
987         switch (action) {
988
989         case LFUN_ESCAPE:
990         {
991                 if (!view()->available()) break;
992                 // this function should be used always [asierra060396]
993                 UpdatableInset * tli =
994                         view()->theLockingInset();
995                 if (tli) {
996                         UpdatableInset * lock = tli->getLockingInset();
997
998                         if (tli == lock) {
999                                 view()->unlockInset(tli);
1000                                 TEXT()->cursorRight(view());
1001                                 moveCursorUpdate(true, false);
1002                                 owner->view_state_changed();
1003                         } else {
1004                                 tli->unlockInsetInInset(view(),
1005                                                         lock,
1006                                                         true);
1007                         }
1008                         finishUndo();
1009                         // Tell the paragraph dialog that we changed paragraph
1010                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1011                 }
1012         }
1013         break;
1014
1015                 // --- Misc -------------------------------------------
1016         case LFUN_WORDFINDFORWARD  :
1017         case LFUN_WORDFINDBACKWARD : {
1018                 static string last_search;
1019                 string searched_string;
1020
1021                 if (!argument.empty()) {
1022                         last_search = argument;
1023                         searched_string = argument;
1024                 } else {
1025                         searched_string = last_search;
1026                 }
1027                 bool fw = (action == LFUN_WORDFINDFORWARD);
1028                 if (!searched_string.empty()) {
1029                         lyxfind::LyXFind(view(), searched_string, fw);
1030                 }
1031         }
1032         break;
1033
1034         case LFUN_PREFIX:
1035         {
1036                 if (view()->available() && !view()->theLockingInset()) {
1037                         view()->update(TEXT(), BufferView::SELECT);
1038                 }
1039                 owner->message(keyseq.printOptions());
1040         }
1041         break;
1042
1043         // --- Misc -------------------------------------------
1044         case LFUN_EXEC_COMMAND:
1045                 owner->focus_command_buffer();
1046                 break;
1047
1048         case LFUN_CANCEL:                   // RVDK_PATCH_5
1049                 keyseq.reset();
1050                 meta_fake_bit = key_modifier::none;
1051                 if (view()->available())
1052                         // cancel any selection
1053                         dispatch(LFUN_MARK_OFF);
1054                 setMessage(N_("Cancel"));
1055                 break;
1056
1057         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1058         {
1059                 meta_fake_bit = key_modifier::alt;
1060                 setMessage(keyseq.print());
1061         }
1062         break;
1063
1064         case LFUN_READ_ONLY_TOGGLE:
1065                 if (owner->buffer()->lyxvc.inUse()) {
1066                         owner->buffer()->lyxvc.toggleReadOnly();
1067                 } else {
1068                         owner->buffer()->setReadonly(
1069                                 !owner->buffer()->isReadonly());
1070                 }
1071                 break;
1072
1073         case LFUN_CENTER: // this is center and redraw.
1074                 view()->center();
1075                 break;
1076
1077                 // --- Menus -----------------------------------------------
1078         case LFUN_MENUNEW:
1079                 menuNew(argument, false);
1080                 break;
1081
1082         case LFUN_MENUNEWTMPLT:
1083                 menuNew(argument, true);
1084                 break;
1085
1086         case LFUN_CLOSEBUFFER:
1087                 closeBuffer();
1088                 break;
1089
1090         case LFUN_MENUWRITE:
1091                 if (!owner->buffer()->isUnnamed()) {
1092                         string const str = bformat(_("Saving document %1$s..."),
1093                            MakeDisplayPath(owner->buffer()->fileName()));
1094                         owner->message(str);
1095                         MenuWrite(owner->buffer());
1096                         owner->message(str + _(" done."));
1097                 } else
1098                         WriteAs(owner->buffer());
1099                 break;
1100
1101         case LFUN_WRITEAS:
1102                 WriteAs(owner->buffer(), argument);
1103                 break;
1104
1105         case LFUN_MENURELOAD: {
1106                 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
1107                 string text = bformat(_("Any changes will be lost. Are you sure "
1108                         "you want to revert to the saved version of the document %1$s?"), file);
1109                 int const ret = Alert::prompt(_("Revert to saved document?"),
1110                         text, 0, 1, _("&Revert"), _("&Cancel"));
1111
1112                 if (ret == 0)
1113                         view()->reload();
1114                 break;
1115         }
1116
1117         case LFUN_UPDATE:
1118                 Exporter::Export(owner->buffer(), argument, true);
1119                 view()->showErrorList(BufferFormat(*owner->buffer()));
1120                 break;
1121
1122         case LFUN_PREVIEW:
1123                 Exporter::Preview(owner->buffer(), argument);
1124                 view()->showErrorList(BufferFormat(*owner->buffer()));
1125                 break;
1126
1127         case LFUN_BUILDPROG:
1128                 Exporter::Export(owner->buffer(), "program", true);
1129                 view()->showErrorList(_("Build"));
1130                 break;
1131
1132         case LFUN_RUNCHKTEX:
1133                 owner->buffer()->runChktex();
1134                 view()->showErrorList(_("ChkTeX"));
1135                 break;
1136
1137         case LFUN_EXPORT:
1138                 if (argument == "custom")
1139                         owner->getDialogs().showSendto();
1140                 else {
1141                         Exporter::Export(owner->buffer(), argument, false);
1142                         view()->showErrorList(BufferFormat(*owner->buffer()));
1143                 }
1144                 break;
1145
1146         case LFUN_IMPORT:
1147                 doImport(argument);
1148                 break;
1149
1150         case LFUN_QUIT:
1151                 QuitLyX();
1152                 break;
1153
1154         case LFUN_TOCVIEW:
1155         {
1156                 InsetCommandParams p("tableofcontents");
1157                 string const data = InsetCommandMailer::params2string("toc", p);
1158                 owner->getDialogs().show("toc", data, 0);
1159                 break;
1160         }
1161
1162         case LFUN_AUTOSAVE:
1163                 AutoSave(view());
1164                 break;
1165
1166         case LFUN_UNDO:
1167                 view()->undo();
1168                 break;
1169
1170         case LFUN_REDO:
1171                 view()->redo();
1172                 break;
1173
1174         case LFUN_DEPTH_MIN:
1175                 changeDepth(view(), TEXT(false), DEC_DEPTH, false);
1176                 owner->view_state_changed();
1177                 break;
1178
1179         case LFUN_DEPTH_PLUS:
1180                 changeDepth(view(), TEXT(false), INC_DEPTH, false);
1181                 owner->view_state_changed();
1182                 break;
1183
1184         case LFUN_FREEFONT_APPLY:
1185                 apply_freefont(view());
1186                 break;
1187
1188         case LFUN_FREEFONT_UPDATE:
1189                 update_and_apply_freefont(view(), argument);
1190                 break;
1191
1192         case LFUN_RECONFIGURE:
1193                 Reconfigure(view());
1194                 break;
1195
1196 #if 0
1197         case LFUN_FLOATSOPERATE:
1198                 if (argument == "openfoot")
1199                         view()->allFloats(1,0);
1200                 else if (argument == "closefoot")
1201                         view()->allFloats(0,0);
1202                 else if (argument == "openfig")
1203                         view()->allFloats(1,1);
1204                 else if (argument == "closefig")
1205                         view()->allFloats(0,1);
1206                 break;
1207 #else
1208 #ifdef WITH_WARNINGS
1209 //#warning Find another implementation here (or another lyxfunc)!
1210 #endif
1211 #endif
1212         case LFUN_HELP_OPEN:
1213         {
1214                 string const arg = argument;
1215                 if (arg.empty()) {
1216                         setErrorMessage(N_("Missing argument"));
1217                         break;
1218                 }
1219                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1220                 if (fname.empty()) {
1221                         lyxerr << "LyX: unable to find documentation file `"
1222                                << arg << "'. Bad installation?" << endl;
1223                         break;
1224                 }
1225                 owner->message(bformat(_("Opening help file %1$s..."),
1226                         MakeDisplayPath(fname)));
1227                 view()->loadLyXFile(fname, false);
1228                 break;
1229         }
1230
1231                 // --- version control -------------------------------
1232         case LFUN_VC_REGISTER:
1233         {
1234                 if (!ensureBufferClean(view()))
1235                         break;
1236                 if (!owner->buffer()->lyxvc.inUse()) {
1237                         owner->buffer()->lyxvc.registrer();
1238                         view()->reload();
1239                 }
1240         }
1241         break;
1242
1243         case LFUN_VC_CHECKIN:
1244         {
1245                 if (!ensureBufferClean(view()))
1246                         break;
1247                 if (owner->buffer()->lyxvc.inUse()
1248                     && !owner->buffer()->isReadonly()) {
1249                         owner->buffer()->lyxvc.checkIn();
1250                         view()->reload();
1251                 }
1252         }
1253         break;
1254
1255         case LFUN_VC_CHECKOUT:
1256         {
1257                 if (!ensureBufferClean(view()))
1258                         break;
1259                 if (owner->buffer()->lyxvc.inUse()
1260                     && owner->buffer()->isReadonly()) {
1261                         owner->buffer()->lyxvc.checkOut();
1262                         view()->reload();
1263                 }
1264         }
1265         break;
1266
1267         case LFUN_VC_REVERT:
1268         {
1269                 owner->buffer()->lyxvc.revert();
1270                 view()->reload();
1271         }
1272         break;
1273
1274         case LFUN_VC_UNDO:
1275         {
1276                 owner->buffer()->lyxvc.undoLast();
1277                 view()->reload();
1278         }
1279         break;
1280
1281         // --- buffers ----------------------------------------
1282
1283         case LFUN_SWITCHBUFFER:
1284                 view()->buffer(bufferlist.getBuffer(argument));
1285                 break;
1286
1287         case LFUN_FILE_NEW:
1288                 NewFile(view(), argument);
1289                 break;
1290
1291         case LFUN_FILE_OPEN:
1292                 open(argument);
1293                 break;
1294
1295         case LFUN_LAYOUT_TABULAR:
1296             if (view()->theLockingInset()) {
1297                 if (view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1298                     InsetTabular * inset = static_cast<InsetTabular *>
1299                         (view()->theLockingInset());
1300                     inset->openLayoutDialog(view());
1301                 } else if (view()->theLockingInset()->
1302                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1303                     InsetTabular * inset = static_cast<InsetTabular *>(
1304                         view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1305                     inset->openLayoutDialog(view());
1306                 }
1307             }
1308             break;
1309
1310         case LFUN_DROP_LAYOUTS_CHOICE:
1311                 owner->getToolbar().openLayoutList();
1312                 break;
1313
1314         case LFUN_MENU_OPEN_BY_NAME:
1315                 owner->getMenubar().openByName(argument);
1316                 break; // RVDK_PATCH_5
1317
1318         // --- lyxserver commands ----------------------------
1319
1320
1321         case LFUN_GETNAME:
1322                 setMessage(owner->buffer()->fileName());
1323                 lyxerr[Debug::INFO] << "FNAME["
1324                                << owner->buffer()->fileName()
1325                                << "] " << endl;
1326                 break;
1327
1328         case LFUN_NOTIFY:
1329         {
1330                 dispatch_buffer = keyseq.print();
1331                 lyxserver->notifyClient(dispatch_buffer);
1332         }
1333         break;
1334
1335         case LFUN_GOTOFILEROW:
1336         {
1337                 string file_name;
1338                 int row;
1339                 istringstream istr(argument.c_str());
1340                 istr >> file_name >> row;
1341                 // Must replace extension of the file to be .lyx and get full path
1342                 string const s(ChangeExtension(file_name, ".lyx"));
1343
1344                 // Either change buffer or load the file
1345                 if (bufferlist.exists(s)) {
1346                         view()->buffer(bufferlist.getBuffer(s));
1347                 } else {
1348                         view()->loadLyXFile(s);
1349                 }
1350
1351                 view()->setCursorFromRow(row);
1352
1353                 view()->center();
1354                 // see BufferView_pimpl::center()
1355                 view()->updateScrollbar();
1356         }
1357         break;
1358
1359         case LFUN_GOTO_PARAGRAPH:
1360         {
1361                 istringstream istr(argument.c_str());
1362
1363                 int id;
1364                 istr >> id;
1365                 ParIterator par = owner->buffer()->getParFromID(id);
1366                 if (par == owner->buffer()->par_iterator_end()) {
1367                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1368                                             << id << ']' << endl;
1369                         break;
1370                 } else {
1371                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
1372                                             << " found." << endl;
1373                 }
1374
1375                 if (view()->theLockingInset())
1376                         view()->unlockInset(view()->theLockingInset());
1377                 if (par->inInset()) {
1378                         FuncRequest cmd(view(), LFUN_INSET_EDIT, "left");
1379                         par->inInset()->localDispatch(cmd);
1380                 }
1381                 // Set the cursor
1382                 view()->getLyXText()->setCursor(par.pit(), 0);
1383                 view()->switchKeyMap();
1384                 owner->view_state_changed();
1385
1386                 view()->center();
1387                 // see BufferView_pimpl::center()
1388                 view()->updateScrollbar();
1389         }
1390         break;
1391
1392         // --- insert characters ----------------------------------------
1393
1394         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1395         case LFUN_MATH_EXTERN:
1396         case LFUN_MATH_NUMBER:
1397         case LFUN_MATH_NONUMBER:
1398         case LFUN_MATH_LIMITS:
1399         {
1400                 setErrorMessage(N_("This is only allowed in math mode!"));
1401         }
1402         break;
1403
1404         // passthrough hat and underscore outside mathed:
1405         case LFUN_SUBSCRIPT:
1406                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1407                 break;
1408         case LFUN_SUPERSCRIPT:
1409                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1410                 break;
1411
1412         case LFUN_DIALOG_SHOW: {
1413                 string const name = ev.getArg(0);
1414                 string data = trim(ev.argument.substr(name.size()));
1415
1416                 if (name == "character") {
1417                         data = freefont2string();
1418                         if (!data.empty())
1419                                 owner->getDialogs().show("character", data);
1420                 } else if (name == "document")
1421                         owner->getDialogs().showDocument();
1422                 else if (name == "findreplace")
1423                         owner->getDialogs().showSearch();
1424                 else if (name == "forks")
1425                         owner->getDialogs().showForks();
1426                 else if (name == "preamble")
1427                         owner->getDialogs().showPreamble();
1428                 else if (name == "preferences")
1429                         owner->getDialogs().showPreferences();
1430                 else if (name == "print")
1431                         owner->getDialogs().showPrint();
1432                 else if (name == "spellchecker")
1433                         owner->getDialogs().showSpellchecker();
1434                 else
1435                         owner->getDialogs().show(name, data);
1436                 break;
1437         }
1438
1439         case LFUN_DIALOG_SHOW_NEW_INSET: {
1440                 string const & name = argument;
1441                 string data;
1442                 if (name == "bibitem" ||
1443                     name == "bibtex" ||
1444                     name == "include" ||
1445                     name == "index" ||
1446                     name == "ref" ||
1447                     name == "toc" ||
1448                     name == "url") {
1449                         InsetCommandParams p(name);
1450                         data = InsetCommandMailer::params2string(name, p);
1451                 } else if (name == "citation") {
1452                         InsetCommandParams p("cite");
1453                         data = InsetCommandMailer::params2string(name, p);
1454                 }
1455                 owner->getDialogs().show(name, data, 0);
1456         }
1457         break;
1458
1459         case LFUN_DIALOG_SHOW_NEXT_INSET: {
1460         }
1461         break;
1462
1463         case LFUN_DIALOG_UPDATE: {
1464                 string const & name = argument;
1465                 // Can only update a dialog connected to an existing inset
1466                 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1467                 if (inset) {
1468                         FuncRequest fr(view(), LFUN_INSET_DIALOG_UPDATE,
1469                                        ev.argument);
1470                         inset->localDispatch(fr);
1471                 } else if (name == "paragraph") {
1472                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1473                 }
1474         }
1475         break;
1476
1477         case LFUN_DIALOG_HIDE:
1478                 Dialogs::hide(argument, 0);
1479                 break;
1480
1481         case LFUN_DIALOG_DISCONNECT_INSET:
1482                 owner->getDialogs().disconnect(argument);
1483                 break;
1484
1485         case LFUN_CHILDOPEN:
1486         {
1487                 string const filename =
1488                         MakeAbsPath(argument,
1489                                     owner->buffer()->filePath());
1490                 setMessage(N_("Opening child document ") +
1491                            MakeDisplayPath(filename) + "...");
1492                 view()->savePosition(0);
1493                 if (bufferlist.exists(filename))
1494                         view()->buffer(bufferlist.getBuffer(filename));
1495                 else
1496                         view()->loadLyXFile(filename);
1497         }
1498         break;
1499
1500         case LFUN_TOGGLECURSORFOLLOW:
1501                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1502                 break;
1503
1504         case LFUN_KMAP_OFF:
1505                 owner->getIntl().KeyMapOn(false);
1506                 break;
1507
1508         case LFUN_KMAP_PRIM:
1509                 owner->getIntl().KeyMapPrim();
1510                 break;
1511
1512         case LFUN_KMAP_SEC:
1513                 owner->getIntl().KeyMapSec();
1514                 break;
1515
1516         case LFUN_KMAP_TOGGLE:
1517                 owner->getIntl().ToggleKeyMap();
1518                 break;
1519
1520         case LFUN_SEQUENCE:
1521         {
1522                 // argument contains ';'-terminated commands
1523                 while (!argument.empty()) {
1524                         string first;
1525                         argument = split(argument, first, ';');
1526                         dispatch(first);
1527                 }
1528         }
1529         break;
1530
1531         case LFUN_SAVEPREFERENCES:
1532         {
1533                 Path p(user_lyxdir);
1534                 lyxrc.write("preferences");
1535         }
1536         break;
1537
1538         case LFUN_SCREEN_FONT_UPDATE:
1539         {
1540                 // handle the screen font changes.
1541                 lyxrc.set_font_norm_type();
1542                 lyx_gui::update_fonts();
1543                 // We also need to empty the textcache so that
1544                 // the buffer will be formatted correctly after
1545                 // a zoom change.
1546                 textcache.clear();
1547                 // Of course we should only do the resize and the textcache.clear
1548                 // if values really changed...but not very important right now. (Lgb)
1549                 // All visible buffers will need resize
1550                 view()->resize();
1551                 view()->repaint();
1552         }
1553         break;
1554
1555         case LFUN_SET_COLOR:
1556         {
1557                 string lyx_name;
1558                 string const x11_name = split(argument, lyx_name, ' ');
1559                 if (lyx_name.empty() || x11_name.empty()) {
1560                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1561                                                 " <x11_name>"));
1562                         break;
1563                         }
1564
1565                 bool const graphicsbg_changed =
1566                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1567                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1568
1569                 if (!lcolor.setColor(lyx_name, x11_name)) {
1570                         setErrorMessage(
1571                                 bformat(_("Set-color \"%1$s\" failed "
1572                                                   "- color is undefined or "
1573                                                   "may not be redefined"), lyx_name));
1574                         break;
1575                 }
1576
1577                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1578
1579                 if (graphicsbg_changed) {
1580 #ifdef WITH_WARNINGS
1581 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1582 #endif
1583 #if 0
1584                         grfx::GCache & gc = grfx::GCache::get();
1585                         gc.changeDisplay(true);
1586 #endif
1587                 }
1588
1589                 view()->repaint();
1590                 break;
1591         }
1592
1593         case LFUN_MESSAGE:
1594                 owner->message(argument);
1595                 break;
1596
1597         case LFUN_FORKS_KILL:
1598         {
1599                 if (!isStrInt(argument))
1600                         break;
1601
1602                 pid_t const pid = strToInt(argument);
1603                 ForkedcallsController & fcc = ForkedcallsController::get();
1604                 fcc.kill(pid);
1605                 break;
1606         }
1607
1608         case LFUN_TOOLTIPS_TOGGLE:
1609                 owner->getDialogs().toggleTooltips();
1610                 break;
1611
1612         case LFUN_EXTERNAL_EDIT: {
1613                 InsetExternal()
1614                         .localDispatch(FuncRequest(view(), action, argument));
1615                 break;
1616         }
1617
1618         default:
1619                 // Then if it was none of the above
1620                 // Trying the BufferView::pimpl dispatch:
1621                 if (!view()->dispatch(ev))
1622                         lyxerr << "A truly unknown func ["
1623                                << lyxaction.getActionName(ev.action) << "]!"
1624                                << endl;
1625                 break;
1626         } // end of switch
1627
1628 exit_with_message:
1629
1630         view()->owner()->updateLayoutChoice();
1631
1632         if (view()->available()) {
1633                 view()->fitCursor();
1634
1635                 // If we executed a mutating lfun, mark the buffer as dirty
1636                 if (!lyxaction.funcHasFlag(ev.action, LyXAction::NoBuffer)
1637                     && !lyxaction.funcHasFlag(ev.action, LyXAction::ReadOnly))
1638                         view()->buffer()->markDirty();
1639         }
1640
1641         sendDispatchMessage(getMessage(), ev, verbose);
1642 }
1643
1644
1645 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1646 {
1647         owner->updateMenubar();
1648         owner->updateToolbar();
1649
1650         if (ev.action == LFUN_SELFINSERT || !verbose) {
1651                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1652                 if (!msg.empty())
1653                         owner->message(msg);
1654                 return;
1655         }
1656
1657         string dispatch_msg = msg;
1658         if (!dispatch_msg.empty())
1659                 dispatch_msg += ' ';
1660
1661         string comname = lyxaction.getActionName(ev.action);
1662
1663         int pseudoaction = ev.action;
1664         bool argsadded = false;
1665
1666         if (!ev.argument.empty()) {
1667                 // the pseudoaction is useful for the bindings
1668                 pseudoaction = lyxaction.searchActionArg(ev.action, ev.argument);
1669
1670                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
1671                         pseudoaction = ev.action;
1672                 } else {
1673                         comname += ' ' + ev.argument;
1674                         argsadded = true;
1675                 }
1676         }
1677
1678         string const shortcuts = toplevel_keymap->findbinding(pseudoaction);
1679
1680         if (!shortcuts.empty()) {
1681                 comname += ": " + shortcuts;
1682         } else if (!argsadded && !ev.argument.empty()) {
1683                 comname += ' ' + ev.argument;
1684         }
1685
1686         if (!comname.empty()) {
1687                 comname = rtrim(comname);
1688                 dispatch_msg += '(' + comname + ')';
1689         }
1690
1691         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1692         if (!dispatch_msg.empty())
1693                 owner->message(dispatch_msg);
1694 }
1695
1696
1697 void LyXFunc::setupLocalKeymap()
1698 {
1699         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1700         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1701 }
1702
1703
1704 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1705 {
1706         string initpath = lyxrc.document_path;
1707         string filename(name);
1708
1709         if (view()->available()) {
1710                 string const trypath = owner->buffer()->filePath();
1711                 // If directory is writeable, use this as default.
1712                 if (IsDirWriteable(trypath))
1713                         initpath = trypath;
1714         }
1715
1716         static int newfile_number;
1717
1718         if (filename.empty()) {
1719                 filename = AddName(lyxrc.document_path,
1720                             "newfile" + tostr(++newfile_number) + ".lyx");
1721                 FileInfo fi(filename);
1722                 while (bufferlist.exists(filename) || fi.readable()) {
1723                         ++newfile_number;
1724                         filename = AddName(lyxrc.document_path,
1725                                     "newfile" + tostr(newfile_number) +
1726                                     ".lyx");
1727                         fi.newFile(filename);
1728                 }
1729         }
1730
1731         // The template stuff
1732         string templname;
1733         if (fromTemplate) {
1734                 FileDialog fileDlg(_("Select template file"),
1735                         LFUN_SELECT_FILE_SYNC,
1736                         make_pair(string(_("Documents|#o#O")),
1737                                   string(lyxrc.document_path)),
1738                         make_pair(string(_("Templates|#T#t")),
1739                                   string(lyxrc.template_path)));
1740
1741                 FileDialog::Result result =
1742                         fileDlg.open(lyxrc.template_path,
1743                                        _("*.lyx| LyX Documents (*.lyx)"));
1744
1745                 if (result.first == FileDialog::Later)
1746                         return;
1747
1748                 string const fname = result.second;
1749
1750                 if (fname.empty())
1751                         return;
1752                 templname = fname;
1753         }
1754
1755         view()->newFile(filename, templname, !name.empty());
1756 }
1757
1758
1759 void LyXFunc::open(string const & fname)
1760 {
1761         string initpath = lyxrc.document_path;
1762
1763         if (view()->available()) {
1764                 string const trypath = owner->buffer()->filePath();
1765                 // If directory is writeable, use this as default.
1766                 if (IsDirWriteable(trypath))
1767                         initpath = trypath;
1768         }
1769
1770         string filename;
1771
1772         if (fname.empty()) {
1773                 FileDialog fileDlg(_("Select document to open"),
1774                         LFUN_FILE_OPEN,
1775                         make_pair(string(_("Documents|#o#O")),
1776                                   string(lyxrc.document_path)),
1777                         make_pair(string(_("Examples|#E#e")),
1778                                   string(AddPath(system_lyxdir, "examples"))));
1779
1780                 FileDialog::Result result =
1781                         fileDlg.open(initpath,
1782                                        _("*.lyx| LyX Documents (*.lyx)"));
1783
1784                 if (result.first == FileDialog::Later)
1785                         return;
1786
1787                 filename = result.second;
1788
1789                 // check selected filename
1790                 if (filename.empty()) {
1791                         owner->message(_("Canceled."));
1792                         return;
1793                 }
1794         } else
1795                 filename = fname;
1796
1797         // get absolute path of file and add ".lyx" to the filename if
1798         // necessary
1799         string const fullpath = FileSearch(string(), filename, "lyx");
1800         if (!fullpath.empty()) {
1801                 filename = fullpath;
1802         }
1803
1804         string const disp_fn(MakeDisplayPath(filename));
1805
1806         // if the file doesn't exist, let the user create one
1807         FileInfo const f(filename, true);
1808         if (!f.exist()) {
1809                 // the user specifically chose this name. Believe them.
1810                 view()->newFile(filename, "", true);
1811                 return;
1812         }
1813
1814         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1815
1816         string str2;
1817         if (view()->loadLyXFile(filename)) {
1818                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1819         } else {
1820                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1821         }
1822         owner->message(str2);
1823 }
1824
1825
1826 void LyXFunc::doImport(string const & argument)
1827 {
1828         string format;
1829         string filename = split(argument, format, ' ');
1830
1831         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1832                             << " file: " << filename << endl;
1833
1834         // need user interaction
1835         if (filename.empty()) {
1836                 string initpath = lyxrc.document_path;
1837
1838                 if (view()->available()) {
1839                         string const trypath = owner->buffer()->filePath();
1840                         // If directory is writeable, use this as default.
1841                         if (IsDirWriteable(trypath))
1842                                 initpath = trypath;
1843                 }
1844
1845                 string const text = bformat(_("Select %1$s file to import"),
1846                         formats.prettyName(format));
1847
1848                 FileDialog fileDlg(text,
1849                         LFUN_IMPORT,
1850                         make_pair(string(_("Documents|#o#O")),
1851                                   string(lyxrc.document_path)),
1852                         make_pair(string(_("Examples|#E#e")),
1853                                   string(AddPath(system_lyxdir, "examples"))));
1854
1855                 string const extension = "*." + formats.extension(format)
1856                         + "| " + formats.prettyName(format)
1857                         + " (*." + formats.extension(format) + ')';
1858
1859                 FileDialog::Result result = fileDlg.open(initpath,
1860                                                            extension);
1861
1862                 if (result.first == FileDialog::Later)
1863                         return;
1864
1865                 filename = result.second;
1866
1867                 // check selected filename
1868                 if (filename.empty())
1869                         owner->message(_("Canceled."));
1870         }
1871
1872         if (filename.empty())
1873                 return;
1874
1875         // get absolute path of file
1876         filename = MakeAbsPath(filename);
1877
1878         string const lyxfile = ChangeExtension(filename, ".lyx");
1879
1880         // Check if the document already is open
1881         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1882                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1883                         owner->message(_("Canceled."));
1884                         return;
1885                 }
1886         }
1887
1888         // if the file exists already, and we didn't do
1889         // -i lyx thefile.lyx, warn
1890         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1891                 string const file = MakeDisplayPath(lyxfile, 30);
1892
1893                 string text = bformat(_("The document %1$s already exists.\n\n"
1894                         "Do you want to over-write that document?"), file);
1895                 int const ret = Alert::prompt(_("Over-write document?"),
1896                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1897
1898                 if (ret == 1) {
1899                         owner->message(_("Canceled."));
1900                         return;
1901                 }
1902         }
1903
1904         Importer::Import(owner, filename, format);
1905 }
1906
1907
1908 void LyXFunc::closeBuffer()
1909 {
1910         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1911                 if (bufferlist.empty()) {
1912                         // need this otherwise SEGV may occur while 
1913                         // trying to set variables that don't exist
1914                         // since there's no current buffer
1915                         owner->getDialogs().hideBufferDependent();
1916                 } else {
1917                         view()->buffer(bufferlist.first());
1918                 }
1919         }
1920 }
1921
1922
1923 // Each "owner" should have it's own message method. lyxview and
1924 // the minibuffer would use the minibuffer, but lyxserver would
1925 // send an ERROR signal to its client.  Alejandro 970603
1926 // This func is bit problematic when it comes to NLS, to make the
1927 // lyx servers client be language indepenent we must not translate
1928 // strings sent to this func.
1929 void LyXFunc::setErrorMessage(string const & m) const
1930 {
1931         dispatch_buffer = m;
1932         errorstat = true;
1933 }
1934
1935
1936 void LyXFunc::setMessage(string const & m) const
1937 {
1938         dispatch_buffer = m;
1939 }
1940
1941
1942 void LyXFunc::setStatusMessage(string const & m) const
1943 {
1944         status_buffer = m;
1945 }
1946
1947
1948 string const LyXFunc::view_status_message()
1949 {
1950         // When meta-fake key is pressed, show the key sequence so far + "M-".
1951         if (wasMetaKey()) {
1952                 return keyseq.print() + "M-";
1953         }
1954
1955         // Else, when a non-complete key sequence is pressed,
1956         // show the available options.
1957         if (keyseq.length() > 0 && !keyseq.deleted()) {
1958                 return keyseq.printOptions();
1959         }
1960
1961         if (!view()->available())
1962                 return _("Welcome to LyX!");
1963
1964         return currentState(view());
1965 }
1966
1967
1968 BufferView * LyXFunc::view() const
1969 {
1970         Assert(owner);
1971         return owner->view().get();
1972 }