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