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