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