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