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