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