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