]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
b1a737955eaa2cac3aad98bb2f8b0d3902fbee7e
[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_HTMLURL:
649         case LFUN_URL:
650                 code = Inset::URL_CODE;
651                 break;
652         case LFUN_QUOTE:
653                 // always allow this, since we will inset a raw quote
654                 // if an inset is not allowed.
655                 break;
656         case LFUN_HYPHENATION:
657         case LFUN_LIGATURE_BREAK:
658         case LFUN_HFILL:
659         case LFUN_MENU_SEPARATOR:
660         case LFUN_LDOTS:
661         case LFUN_END_OF_SENTENCE:
662                 code = Inset::SPECIALCHAR_CODE;
663                 break;
664         case LFUN_SPACE_INSERT:
665                 // slight hack: we know this is allowed in math mode
666                 if (!mathcursor)
667                         code = Inset::SPACE_CODE;
668                 break;
669         default:
670                 break;
671         }
672         if (code != Inset::NO_CODE && tli && !tli->insetAllowed(code))
673                 disable = true;
674
675         if (disable)
676                 flag.disabled(true);
677
678         // A few general toggles
679         switch (ev.action) {
680         case LFUN_TOOLTIPS_TOGGLE:
681                 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
682                 break;
683
684         case LFUN_READ_ONLY_TOGGLE:
685                 flag.setOnOff(buf->isReadonly());
686                 break;
687         case LFUN_APPENDIX:
688                 flag.setOnOff(TEXT(false)->cursor.par()->params().startOfAppendix());
689                 break;
690         case LFUN_SWITCHBUFFER:
691                 // toggle on the current buffer, but do not toggle off
692                 // the other ones (is that a good idea?)
693                 if (ev.argument == buf->fileName())
694                         flag.setOnOff(true);
695                 break;
696         case LFUN_TRACK_CHANGES:
697                 flag.setOnOff(buf->params.tracking_changes);
698                 break;
699         default:
700                 break;
701         }
702
703         // the font related toggles
704         if (!mathcursor) {
705                 LyXFont const & font = TEXT(false)->real_current_font;
706                 switch (ev.action) {
707                 case LFUN_EMPH:
708                         flag.setOnOff(font.emph() == LyXFont::ON);
709                         break;
710                 case LFUN_NOUN:
711                         flag.setOnOff(font.noun() == LyXFont::ON);
712                         break;
713                 case LFUN_BOLD:
714                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
715                         break;
716                 case LFUN_SANS:
717                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
718                         break;
719                 case LFUN_ROMAN:
720                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
721                         break;
722                 case LFUN_CODE:
723                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
724                         break;
725                 default:
726                         break;
727                 }
728         } else {
729                 string tc = mathcursor->getLastCode();
730                 switch (ev.action) {
731                 case LFUN_BOLD:
732                         flag.setOnOff(tc == "mathbf");
733                         break;
734                 case LFUN_SANS:
735                         flag.setOnOff(tc == "mathsf");
736                         break;
737                 case LFUN_EMPH:
738                         flag.setOnOff(tc == "mathcal");
739                         break;
740                 case LFUN_ROMAN:
741                         flag.setOnOff(tc == "mathrm");
742                         break;
743                 case LFUN_CODE:
744                         flag.setOnOff(tc == "mathtt");
745                         break;
746                 case LFUN_NOUN:
747                         flag.setOnOff(tc == "mathbb");
748                         break;
749                 case LFUN_DEFAULT:
750                         flag.setOnOff(tc == "mathnormal");
751                         break;
752                 default:
753                         break;
754                 }
755         }
756
757         // this one is difficult to get right. As a half-baked
758         // solution, we consider only the first action of the sequence
759         if (ev.action == LFUN_SEQUENCE) {
760                 // argument contains ';'-terminated commands
761                 flag = getStatus(lyxaction.LookupFunc(token(ev.argument, ';', 0)));
762         }
763
764         return flag;
765 }
766
767
768 void LyXFunc::dispatch(string const & s, bool verbose)
769 {
770         int const action = lyxaction.LookupFunc(s);
771
772         if (action == LFUN_UNKNOWN_ACTION) {
773                 owner->message(bformat(_("Unknown function (%1$s)"), s));
774                 return;
775         }
776
777         dispatch(action, verbose);
778 }
779
780
781 void LyXFunc::dispatch(int ac, bool verbose)
782 {
783         dispatch(lyxaction.retrieveActionArg(ac), verbose);
784 }
785
786
787
788 void LyXFunc::dispatch(FuncRequest const & ev, bool verbose)
789 {
790         lyxerr[Debug::ACTION] << "LyXFunc::dispatch: action[" << ev.action
791                               <<"] arg[" << ev.argument << ']' << endl;
792
793         // we have not done anything wrong yet.
794         errorstat = false;
795         dispatch_buffer.erase();
796
797 #ifdef NEW_DISPATCHER
798         // We try do call the most specific dispatcher first:
799         //  1. the lockinginset's dispatch
800         //  2. the bufferview's dispatch
801         //  3. the lyxview's dispatch
802 #endif
803
804         selection_possible = false;
805
806         string argument = ev.argument;
807         kb_action action = ev.action;
808
809         // We cannot use this function here
810         if (getStatus(ev).disabled()) {
811                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
812                        << lyxaction.getActionName(action)
813                        << " [" << action << "] is disabled at this location"
814                        << endl;
815                 setErrorMessage(getStatusMessage());
816                 goto exit_with_message;
817         }
818
819         if (view()->available())
820                 view()->hideCursor();
821
822         if (view()->available() && view()->theLockingInset()) {
823                 Inset::RESULT result;
824                 if ((action > 1) || ((action == LFUN_UNKNOWN_ACTION) &&
825                                      (!keyseq.deleted())))
826                 {
827                         UpdatableInset * inset = view()->theLockingInset();
828 #if 1
829                         int inset_x;
830                         int dummy_y;
831                         inset->getCursorPos(view(), inset_x, dummy_y);
832 #endif
833                         if ((action == LFUN_UNKNOWN_ACTION)
834                             && argument.empty()) {
835                                 argument = encoded_last_key;
836                         }
837
838                         // the insets can't try to handle this,
839                         // a table cell in the dummy position will
840                         // lock its insettext, the insettext will
841                         // pass it the bufferview, and succeed,
842                         // so it will stay not locked. Not good
843                         // if we've just done LFUN_ESCAPE (which
844                         // injects an LFUN_PARAGRAPH_UPDATE)
845                         if (action == LFUN_PARAGRAPH_UPDATE) {
846                                 view()->dispatch(ev);
847                                 goto exit_with_message;
848                         }
849
850                         // Undo/Redo is a bit tricky for insets.
851                         if (action == LFUN_UNDO) {
852                                 view()->undo();
853                                 goto exit_with_message;
854                         } else if (action == LFUN_REDO) {
855                                 view()->redo();
856                                 goto exit_with_message;
857                         } else if (((result=inset->
858                                      // Hand-over to inset's own dispatch:
859                                      localDispatch(FuncRequest(view(), action, argument))) ==
860                                     DISPATCHED) ||
861                                    (result == DISPATCHED_NOUPDATE))
862                                 goto exit_with_message;
863                                         // If UNDISPATCHED, just soldier on
864                         else if (result == FINISHED) {
865                                 owner->clearMessage();
866                                 goto exit_with_message;
867                                 // We do not need special RTL handling here:
868                                 // FINISHED means that the cursor should be
869                                 // one position after the inset.
870                         } else if (result == FINISHED_RIGHT) {
871                                 TEXT()->cursorRight(view());
872                                 moveCursorUpdate(true, false);
873                                 owner->clearMessage();
874                                 goto exit_with_message;
875                         } else if (result == FINISHED_UP) {
876                                 if (TEXT()->cursor.irow() != TEXT()->rows().begin()) {
877 #if 1
878                                         TEXT()->setCursorFromCoordinates(
879                                                 TEXT()->cursor.ix() + inset_x,
880                                                 TEXT()->cursor.iy() -
881                                                 TEXT()->cursor.irow()->baseline() - 1);
882                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
883 #else
884                                         TEXT()->cursorUp(view());
885 #endif
886                                         moveCursorUpdate(true, false);
887                                 } else {
888                                         view()->update(TEXT(), BufferView::SELECT);
889                                 }
890                                 owner->clearMessage();
891                                 goto exit_with_message;
892                         } else if (result == FINISHED_DOWN) {
893                                 if (boost::next(TEXT()->cursor.irow()) != TEXT()->rows().end()) {
894 #if 1
895                                         TEXT()->setCursorFromCoordinates(
896                                                 TEXT()->cursor.ix() + inset_x,
897                                                 TEXT()->cursor.iy() -
898                                                 TEXT()->cursor.irow()->baseline() +
899                                                 TEXT()->cursor.irow()->height() + 1);
900                                         TEXT()->cursor.x_fix(TEXT()->cursor.x());
901 #else
902                                         TEXT()->cursorDown(view());
903 #endif
904                                 } else {
905                                         TEXT()->cursorRight(view());
906                                 }
907                                 moveCursorUpdate(true, false);
908                                 owner->clearMessage();
909                                 goto exit_with_message;
910                         }
911 #warning I am not sure this is still right, please have a look! (Jug 20020417)
912                         else { // result == UNDISPATCHED
913                                 //setMessage(N_("Text mode"));
914                                 switch (action) {
915                                 case LFUN_UNKNOWN_ACTION:
916                                 case LFUN_BREAKPARAGRAPH:
917                                 case LFUN_BREAKLINE:
918                                         TEXT()->cursorRight(view());
919                                         view()->switchKeyMap();
920                                         owner->view_state_changed();
921                                         break;
922                                 case LFUN_RIGHT:
923                                         if (!TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
924                                                 TEXT()->cursorRight(view());
925                                                 moveCursorUpdate(true, false);
926                                                 owner->view_state_changed();
927                                         }
928                                         goto exit_with_message;
929                                 case LFUN_LEFT:
930                                         if (TEXT()->cursor.par()->isRightToLeftPar(owner->buffer()->params)) {
931                                                 TEXT()->cursorRight(view());
932                                                 moveCursorUpdate(true, false);
933                                                 owner->view_state_changed();
934                                         }
935                                         goto exit_with_message;
936                                 case LFUN_DOWN:
937                                         if (boost::next(TEXT()->cursor.row()) != TEXT()->rows().end())
938                                                 TEXT()->cursorDown(view());
939                                         else
940                                                 TEXT()->cursorRight(view());
941                                         moveCursorUpdate(true, false);
942                                         owner->view_state_changed();
943                                         goto exit_with_message;
944                                 default:
945                                         break;
946                                 }
947                         }
948                 }
949         }
950
951         switch (action) {
952
953         case LFUN_ESCAPE:
954         {
955                 if (!view()->available()) break;
956                 // this function should be used always [asierra060396]
957                 UpdatableInset * tli =
958                         view()->theLockingInset();
959                 if (tli) {
960                         UpdatableInset * lock = tli->getLockingInset();
961
962                         if (tli == lock) {
963                                 view()->unlockInset(tli);
964                                 TEXT()->cursorRight(view());
965                                 moveCursorUpdate(true, false);
966                                 owner->view_state_changed();
967                         } else {
968                                 tli->unlockInsetInInset(view(),
969                                                         lock,
970                                                         true);
971                         }
972                         finishUndo();
973                         // Tell the paragraph dialog that we changed paragraph
974                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
975                 }
976         }
977         break;
978
979                 // --- Misc -------------------------------------------
980         case LFUN_WORDFINDFORWARD  :
981         case LFUN_WORDFINDBACKWARD : {
982                 static string last_search;
983                 string searched_string;
984
985                 if (!argument.empty()) {
986                         last_search = argument;
987                         searched_string = argument;
988                 } else {
989                         searched_string = last_search;
990                 }
991                 bool fw = (action == LFUN_WORDFINDFORWARD);
992                 if (!searched_string.empty()) {
993                         lyxfind::LyXFind(view(), searched_string, fw);
994                 }
995         }
996         break;
997
998         case LFUN_PREFIX:
999         {
1000                 if (view()->available() && !view()->theLockingInset()) {
1001                         view()->update(TEXT(), BufferView::SELECT);
1002                 }
1003                 owner->message(keyseq.printOptions());
1004         }
1005         break;
1006
1007         // --- Misc -------------------------------------------
1008         case LFUN_EXEC_COMMAND:
1009                 owner->focus_command_buffer();
1010                 break;
1011
1012         case LFUN_CANCEL:                   // RVDK_PATCH_5
1013                 keyseq.reset();
1014                 meta_fake_bit = key_modifier::none;
1015                 if (view()->available())
1016                         // cancel any selection
1017                         dispatch(LFUN_MARK_OFF);
1018                 setMessage(N_("Cancel"));
1019                 break;
1020
1021         case LFUN_META_FAKE:                                 // RVDK_PATCH_5
1022         {
1023                 meta_fake_bit = key_modifier::alt;
1024                 setMessage(keyseq.print());
1025         }
1026         break;
1027
1028         case LFUN_READ_ONLY_TOGGLE:
1029                 if (owner->buffer()->lyxvc.inUse()) {
1030                         owner->buffer()->lyxvc.toggleReadOnly();
1031                 } else {
1032                         owner->buffer()->setReadonly(
1033                                 !owner->buffer()->isReadonly());
1034                 }
1035                 break;
1036
1037         case LFUN_CENTER: // this is center and redraw.
1038                 view()->center();
1039                 break;
1040
1041                 // --- Menus -----------------------------------------------
1042         case LFUN_MENUNEW:
1043                 menuNew(argument, false);
1044                 break;
1045
1046         case LFUN_MENUNEWTMPLT:
1047                 menuNew(argument, true);
1048                 break;
1049
1050         case LFUN_CLOSEBUFFER:
1051                 closeBuffer();
1052                 break;
1053
1054         case LFUN_MENUWRITE:
1055                 if (!owner->buffer()->isUnnamed()) {
1056                         string const str = bformat(_("Saving document %1$s..."),
1057                            MakeDisplayPath(owner->buffer()->fileName()));
1058                         owner->message(str);
1059                         MenuWrite(view(), owner->buffer());
1060                         owner->message(str + _(" done."));
1061                 } else
1062                         WriteAs(view(), owner->buffer());
1063                 break;
1064
1065         case LFUN_WRITEAS:
1066                 WriteAs(view(), owner->buffer(), argument);
1067                 break;
1068
1069         case LFUN_MENURELOAD: {
1070                 string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
1071                 string text = bformat(_("Any changes will be lost. Are you sure "
1072                         "you want to revert to the saved version of the document %1$s?"), file);
1073                 int const ret = Alert::prompt(_("Revert to saved document?"),
1074                         text, 0, 1, _("&Revert"), _("&Cancel"));
1075
1076                 if (ret == 0)
1077                         view()->reload();
1078                 break;
1079         }
1080
1081         case LFUN_UPDATE:
1082                 Exporter::Export(owner->buffer(), argument, true);
1083                 break;
1084
1085         case LFUN_PREVIEW:
1086                 Exporter::Preview(owner->buffer(), argument);
1087                 break;
1088
1089         case LFUN_BUILDPROG:
1090                 Exporter::Export(owner->buffer(), "program", true);
1091                 break;
1092
1093         case LFUN_RUNCHKTEX:
1094                 owner->buffer()->runChktex();
1095                 break;
1096
1097         case LFUN_MENUPRINT:
1098                 owner->getDialogs().showPrint();
1099                 break;
1100
1101         case LFUN_EXPORT:
1102                 if (argument == "custom")
1103                         owner->getDialogs().showSendto();
1104                 else
1105                         Exporter::Export(owner->buffer(), argument, false);
1106                 break;
1107
1108         case LFUN_IMPORT:
1109                 doImport(argument);
1110                 break;
1111
1112         case LFUN_QUIT:
1113                 QuitLyX();
1114                 break;
1115
1116         case LFUN_TOCVIEW:
1117         {
1118                 InsetCommandParams p("tableofcontents");
1119                 string const data = InsetCommandMailer::params2string("toc", p);
1120                 owner->getDialogs().show("toc", data, 0);
1121                 break;
1122         }
1123
1124         case LFUN_AUTOSAVE:
1125                 AutoSave(view());
1126                 break;
1127
1128         case LFUN_UNDO:
1129                 view()->undo();
1130                 break;
1131
1132         case LFUN_REDO:
1133                 view()->redo();
1134                 break;
1135
1136         case LFUN_MENUSEARCH:
1137                 owner->getDialogs().showSearch();
1138                 break;
1139
1140         case LFUN_DEPTH_MIN:
1141                 changeDepth(view(), TEXT(false), DEC_DEPTH, false);
1142                 owner->view_state_changed();
1143                 break;
1144
1145         case LFUN_DEPTH_PLUS:
1146                 changeDepth(view(), TEXT(false), INC_DEPTH, false);
1147                 owner->view_state_changed();
1148                 break;
1149
1150         case LFUN_FREEFONT_APPLY:
1151                 apply_freefont(view());
1152                 break;
1153
1154         case LFUN_FREEFONT_UPDATE:
1155                 update_and_apply_freefont(view(), argument);
1156                 break;
1157
1158         case LFUN_RECONFIGURE:
1159                 Reconfigure(view());
1160                 break;
1161
1162 #if 0
1163         case LFUN_FLOATSOPERATE:
1164                 if (argument == "openfoot")
1165                         view()->allFloats(1,0);
1166                 else if (argument == "closefoot")
1167                         view()->allFloats(0,0);
1168                 else if (argument == "openfig")
1169                         view()->allFloats(1,1);
1170                 else if (argument == "closefig")
1171                         view()->allFloats(0,1);
1172                 break;
1173 #else
1174 #ifdef WITH_WARNINGS
1175 //#warning Find another implementation here (or another lyxfunc)!
1176 #endif
1177 #endif
1178         case LFUN_HELP_ABOUTLYX:
1179                 owner->getDialogs().show("about");
1180                 break;
1181
1182         case LFUN_HELP_TEXINFO:
1183                 owner->getDialogs().showTexinfo();
1184                 break;
1185
1186         case LFUN_HELP_OPEN:
1187         {
1188                 string const arg = argument;
1189                 if (arg.empty()) {
1190                         setErrorMessage(N_("Missing argument"));
1191                         break;
1192                 }
1193                 string const fname = i18nLibFileSearch("doc", arg, "lyx");
1194                 if (fname.empty()) {
1195                         lyxerr << "LyX: unable to find documentation file `"
1196                                << arg << "'. Bad installation?" << endl;
1197                         break;
1198                 }
1199                 owner->message(bformat(_("Opening help file %1$s..."),
1200                         MakeDisplayPath(fname)));
1201                 view()->buffer(bufferlist.loadLyXFile(fname, false));
1202                 break;
1203         }
1204
1205                 // --- version control -------------------------------
1206         case LFUN_VC_REGISTER:
1207         {
1208                 if (!owner->buffer()->lyxvc.inUse())
1209                         owner->buffer()->lyxvc.registrer();
1210         }
1211         break;
1212
1213         case LFUN_VC_CHECKIN:
1214         {
1215                 if (owner->buffer()->lyxvc.inUse()
1216                     && !owner->buffer()->isReadonly())
1217                         owner->buffer()->lyxvc.checkIn();
1218         }
1219         break;
1220
1221         case LFUN_VC_CHECKOUT:
1222         {
1223                 if (owner->buffer()->lyxvc.inUse()
1224                     && owner->buffer()->isReadonly())
1225                         owner->buffer()->lyxvc.checkOut();
1226         }
1227         break;
1228
1229         case LFUN_VC_REVERT:
1230         {
1231                 owner->buffer()->lyxvc.revert();
1232         }
1233         break;
1234
1235         case LFUN_VC_UNDO:
1236         {
1237                 owner->buffer()->lyxvc.undoLast();
1238         }
1239         break;
1240
1241         case LFUN_VC_HISTORY:
1242         {
1243                 owner->getDialogs().show("vclog");
1244                 break;
1245         }
1246
1247         // --- buffers ----------------------------------------
1248
1249         case LFUN_SWITCHBUFFER:
1250                 view()->buffer(bufferlist.getBuffer(argument));
1251                 break;
1252
1253         case LFUN_FILE_NEW:
1254         {
1255                 // servercmd: argument must be <file>:<template>
1256                 Buffer * tmpbuf = NewFile(argument);
1257                 if (tmpbuf)
1258                         view()->buffer(tmpbuf);
1259         }
1260         break;
1261
1262         case LFUN_FILE_OPEN:
1263                 open(argument);
1264                 break;
1265
1266         case LFUN_LATEX_LOG:
1267                 owner->getDialogs().show("log");
1268                 break;
1269
1270         case LFUN_LAYOUT_DOCUMENT:
1271                 owner->getDialogs().showDocument();
1272                 break;
1273
1274         case LFUN_LAYOUT_CHARACTER: {
1275                 string data = freefont2string();
1276                 if (!data.empty())
1277                         owner->getDialogs().show("character", data);
1278                 break;
1279         }
1280
1281         case LFUN_LAYOUT_TABULAR:
1282             if (view()->theLockingInset()) {
1283                 if (view()->theLockingInset()->lyxCode()==Inset::TABULAR_CODE) {
1284                     InsetTabular * inset = static_cast<InsetTabular *>
1285                         (view()->theLockingInset());
1286                     inset->openLayoutDialog(view());
1287                 } else if (view()->theLockingInset()->
1288                            getFirstLockingInsetOfType(Inset::TABULAR_CODE)!=0) {
1289                     InsetTabular * inset = static_cast<InsetTabular *>(
1290                         view()->theLockingInset()->getFirstLockingInsetOfType(Inset::TABULAR_CODE));
1291                     inset->openLayoutDialog(view());
1292                 }
1293             }
1294             break;
1295
1296         case LFUN_LAYOUT_PREAMBLE:
1297                 owner->getDialogs().showPreamble();
1298                 break;
1299
1300         case LFUN_DROP_LAYOUTS_CHOICE:
1301                 owner->getToolbar().openLayoutList();
1302                 break;
1303
1304         case LFUN_MENU_OPEN_BY_NAME:
1305                 owner->getMenubar().openByName(argument);
1306                 break; // RVDK_PATCH_5
1307
1308         case LFUN_SPELLCHECK:
1309                 owner->getDialogs().showSpellchecker();
1310                 break;
1311
1312         // --- lyxserver commands ----------------------------
1313
1314
1315         case LFUN_GETNAME:
1316                 setMessage(owner->buffer()->fileName());
1317                 lyxerr[Debug::INFO] << "FNAME["
1318                                << owner->buffer()->fileName()
1319                                << "] " << endl;
1320                 break;
1321
1322         case LFUN_NOTIFY:
1323         {
1324                 dispatch_buffer = keyseq.print();
1325                 lyxserver->notifyClient(dispatch_buffer);
1326         }
1327         break;
1328
1329         case LFUN_GOTOFILEROW:
1330         {
1331                 string file_name;
1332                 int row;
1333                 istringstream istr(argument.c_str());
1334                 istr >> file_name >> row;
1335                 // Must replace extension of the file to be .lyx and get full path
1336                 string const s(ChangeExtension(file_name, ".lyx"));
1337
1338                 // Either change buffer or load the file
1339                 if (bufferlist.exists(s)) {
1340                         view()->buffer(bufferlist.getBuffer(s));
1341                 } else {
1342                         view()->buffer(bufferlist.loadLyXFile(s));
1343                 }
1344
1345                 view()->setCursorFromRow(row);
1346
1347                 view()->center();
1348                 // see BufferView_pimpl::center()
1349                 view()->updateScrollbar();
1350         }
1351         break;
1352
1353         case LFUN_GOTO_PARAGRAPH:
1354         {
1355                 istringstream istr(argument.c_str());
1356
1357                 int id;
1358                 istr >> id;
1359                 ParIterator par = owner->buffer()->getParFromID(id);
1360                 if (par == owner->buffer()->par_iterator_end()) {
1361                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
1362                                             << id << ']' << endl;
1363                         break;
1364                 } else {
1365                         lyxerr[Debug::INFO] << "Paragraph " << (*par)->id()
1366                                             << " found." << endl;
1367                 }
1368
1369                 if (view()->theLockingInset())
1370                         view()->unlockInset(view()->theLockingInset());
1371                 if ((*par)->inInset()) {
1372                         FuncRequest cmd(view(), LFUN_INSET_EDIT, "left");
1373                         (*par)->inInset()->localDispatch(cmd);
1374                 }
1375                 // Set the cursor
1376                 view()->getLyXText()->setCursor(*par, 0);
1377                 view()->switchKeyMap();
1378                 owner->view_state_changed();
1379
1380                 view()->center();
1381                 // see BufferView_pimpl::center()
1382                 view()->updateScrollbar();
1383         }
1384         break;
1385
1386         // --- insert characters ----------------------------------------
1387
1388         // ---  Mathed stuff. If we are here, there is no locked inset yet.
1389         case LFUN_MATH_EXTERN:
1390         case LFUN_MATH_NUMBER:
1391         case LFUN_MATH_NONUMBER:
1392         case LFUN_MATH_LIMITS:
1393         {
1394                 setErrorMessage(N_("This is only allowed in math mode!"));
1395         }
1396         break;
1397
1398         // passthrough hat and underscore outside mathed:
1399         case LFUN_SUBSCRIPT:
1400                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "_"));
1401                 break;
1402         case LFUN_SUPERSCRIPT:
1403                 dispatch(FuncRequest(view(), LFUN_SELFINSERT, "^"));
1404                 break;
1405
1406         case LFUN_MATH_PANEL:
1407                 owner->getDialogs().showMathPanel();
1408                 break;
1409
1410         case LFUN_DIALOG_SHOW_NEW_INSET: {
1411                 string const & name = argument;
1412                 string data;
1413                 if (name == "bibitem" ||
1414                     name == "bibtex" ||
1415                     name == "include" ||
1416                     name == "index" ||
1417                     name == "ref" ||
1418                     name == "toc" ||
1419                     name == "url") {
1420                         InsetCommandParams p(name);
1421                         data = InsetCommandMailer::params2string(name, p);
1422                 } else if (name == "citation") {
1423                         InsetCommandParams p("cite");
1424                         data = InsetCommandMailer::params2string(name, p);
1425                 }
1426                 owner->getDialogs().show(name, data, 0);
1427         }
1428         break;
1429
1430         case LFUN_DIALOG_SHOW_NEXT_INSET: {
1431         }
1432         break;
1433
1434         case LFUN_DIALOG_UPDATE: {
1435                 string const & name = argument;
1436                 // Can only update a dialog connected to an existing inset
1437                 InsetBase * inset = owner->getDialogs().getOpenInset(name);
1438                 if (inset) {
1439                         FuncRequest fr(view(), LFUN_INSET_DIALOG_UPDATE,
1440                                        ev.argument);
1441                         inset->localDispatch(fr);
1442                 } else if (name == "paragraph") {
1443                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1444                 }
1445         }
1446         break;
1447
1448         case LFUN_DIALOG_HIDE:
1449                 Dialogs::hide(argument, 0);
1450                 break;
1451
1452         case LFUN_DIALOG_DISCONNECT_INSET:
1453                 owner->getDialogs().disconnect(argument);
1454                 break;
1455
1456         case LFUN_CHILDOPEN:
1457         {
1458                 string const filename =
1459                         MakeAbsPath(argument,
1460                                     owner->buffer()->filePath());
1461                 setMessage(N_("Opening child document ") +
1462                            MakeDisplayPath(filename) + "...");
1463                 view()->savePosition(0);
1464                 if (bufferlist.exists(filename))
1465                         view()->buffer(bufferlist.getBuffer(filename));
1466                 else
1467                         view()->buffer(bufferlist.loadLyXFile(filename));
1468         }
1469         break;
1470
1471         case LFUN_TOGGLECURSORFOLLOW:
1472                 lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1473                 break;
1474
1475         case LFUN_KMAP_OFF:
1476                 owner->getIntl().KeyMapOn(false);
1477                 break;
1478
1479         case LFUN_KMAP_PRIM:
1480                 owner->getIntl().KeyMapPrim();
1481                 break;
1482
1483         case LFUN_KMAP_SEC:
1484                 owner->getIntl().KeyMapSec();
1485                 break;
1486
1487         case LFUN_KMAP_TOGGLE:
1488                 owner->getIntl().ToggleKeyMap();
1489                 break;
1490
1491         case LFUN_SEQUENCE:
1492         {
1493                 // argument contains ';'-terminated commands
1494                 while (!argument.empty()) {
1495                         string first;
1496                         argument = split(argument, first, ';');
1497                         dispatch(first);
1498                 }
1499         }
1500         break;
1501
1502         case LFUN_DIALOG_PREFERENCES:
1503                 owner->getDialogs().showPreferences();
1504                 break;
1505
1506         case LFUN_SAVEPREFERENCES:
1507         {
1508                 Path p(user_lyxdir);
1509                 lyxrc.write("preferences");
1510         }
1511         break;
1512
1513         case LFUN_SCREEN_FONT_UPDATE:
1514         {
1515                 // handle the screen font changes.
1516                 lyxrc.set_font_norm_type();
1517                 lyx_gui::update_fonts();
1518                 // We also need to empty the textcache so that
1519                 // the buffer will be formatted correctly after
1520                 // a zoom change.
1521                 textcache.clear();
1522                 // Of course we should only do the resize and the textcache.clear
1523                 // if values really changed...but not very important right now. (Lgb)
1524                 // All visible buffers will need resize
1525                 view()->resize();
1526                 view()->repaint();
1527         }
1528         break;
1529
1530         case LFUN_SET_COLOR:
1531         {
1532                 string lyx_name;
1533                 string const x11_name = split(argument, lyx_name, ' ');
1534                 if (lyx_name.empty() || x11_name.empty()) {
1535                         setErrorMessage(N_("Syntax: set-color <lyx_name>"
1536                                                 " <x11_name>"));
1537                         break;
1538                         }
1539
1540                 bool const graphicsbg_changed =
1541                         (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1542                          x11_name != lcolor.getX11Name(LColor::graphicsbg));
1543
1544                 if (!lcolor.setColor(lyx_name, x11_name)) {
1545                         setErrorMessage(
1546                                 bformat(_("Set-color \"%1$s\" failed "
1547                                                   "- color is undefined or "
1548                                                   "may not be redefined"), lyx_name));
1549                         break;
1550                 }
1551
1552                 lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1553
1554                 if (graphicsbg_changed) {
1555 #ifdef WITH_WARNINGS
1556 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1557 #endif
1558 #if 0
1559                         grfx::GCache & gc = grfx::GCache::get();
1560                         gc.changeDisplay(true);
1561 #endif
1562                 }
1563
1564                 view()->repaint();
1565                 break;
1566         }
1567
1568         case LFUN_MESSAGE:
1569                 owner->message(argument);
1570                 break;
1571
1572         case LFUN_FORKS_SHOW:
1573                 owner->getDialogs().showForks();
1574                 break;
1575
1576         case LFUN_FORKS_KILL:
1577         {
1578                 if (!isStrInt(argument))
1579                         break;
1580
1581                 pid_t const pid = strToInt(argument);
1582                 ForkedcallsController & fcc = ForkedcallsController::get();
1583                 fcc.kill(pid);
1584                 break;
1585         }
1586
1587         case LFUN_TOOLTIPS_TOGGLE:
1588                 owner->getDialogs().toggleTooltips();
1589                 break;
1590
1591         default:
1592                 // Then if it was none of the above
1593                 // Trying the BufferView::pimpl dispatch:
1594                 if (!view()->dispatch(ev))
1595                         lyxerr << "A truly unknown func ["
1596                                << lyxaction.getActionName(ev.action) << "]!"
1597                                << endl;
1598                 break;
1599         } // end of switch
1600
1601 exit_with_message:
1602
1603         view()->owner()->updateLayoutChoice();
1604
1605         if (view()->available()) {
1606                 view()->fitCursor();
1607
1608                 // If we executed a mutating lfun, mark the buffer as dirty
1609                 if (!lyxaction.funcHasFlag(ev.action, LyXAction::NoBuffer)
1610                     && !lyxaction.funcHasFlag(ev.action, LyXAction::ReadOnly))
1611                         view()->buffer()->markDirty();
1612         }
1613
1614         sendDispatchMessage(getMessage(), ev, verbose);
1615 }
1616
1617
1618 void LyXFunc::sendDispatchMessage(string const & msg, FuncRequest const & ev, bool verbose)
1619 {
1620         owner->updateMenubar();
1621         owner->updateToolbar();
1622
1623         if (ev.action == LFUN_SELFINSERT || !verbose) {
1624                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1625                 if (!msg.empty())
1626                         owner->message(msg);
1627                 return;
1628         }
1629
1630         string dispatch_msg = msg;
1631         if (!dispatch_msg.empty())
1632                 dispatch_msg += ' ';
1633
1634         string comname = lyxaction.getActionName(ev.action);
1635
1636         int pseudoaction = ev.action;
1637         bool argsadded = false;
1638
1639         if (!ev.argument.empty()) {
1640                 // the pseudoaction is useful for the bindings
1641                 pseudoaction = lyxaction.searchActionArg(ev.action, ev.argument);
1642
1643                 if (pseudoaction == LFUN_UNKNOWN_ACTION) {
1644                         pseudoaction = ev.action;
1645                 } else {
1646                         comname += ' ' + ev.argument;
1647                         argsadded = true;
1648                 }
1649         }
1650
1651         string const shortcuts = toplevel_keymap->findbinding(pseudoaction);
1652
1653         if (!shortcuts.empty()) {
1654                 comname += ": " + shortcuts;
1655         } else if (!argsadded && !ev.argument.empty()) {
1656                 comname += ' ' + ev.argument;
1657         }
1658
1659         if (!comname.empty()) {
1660                 comname = rtrim(comname);
1661                 dispatch_msg += '(' + comname + ')';
1662         }
1663
1664         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1665         if (!dispatch_msg.empty())
1666                 owner->message(dispatch_msg);
1667 }
1668
1669
1670 void LyXFunc::setupLocalKeymap()
1671 {
1672         keyseq.stdmap = keyseq.curmap = toplevel_keymap.get();
1673         cancel_meta_seq.stdmap = cancel_meta_seq.curmap = toplevel_keymap.get();
1674 }
1675
1676
1677 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1678 {
1679         string initpath = lyxrc.document_path;
1680         string filename(name);
1681
1682         if (view()->available()) {
1683                 string const trypath = owner->buffer()->filePath();
1684                 // If directory is writeable, use this as default.
1685                 if (IsDirWriteable(trypath))
1686                         initpath = trypath;
1687         }
1688
1689         static int newfile_number;
1690
1691         if (filename.empty()) {
1692                 filename = AddName(lyxrc.document_path,
1693                             "newfile" + tostr(++newfile_number) + ".lyx");
1694                 FileInfo fi(filename);
1695                 while (bufferlist.exists(filename) || fi.readable()) {
1696                         ++newfile_number;
1697                         filename = AddName(lyxrc.document_path,
1698                                     "newfile" + tostr(newfile_number) +
1699                                     ".lyx");
1700                         fi.newFile(filename);
1701                 }
1702         }
1703
1704         // The template stuff
1705         string templname;
1706         if (fromTemplate) {
1707                 FileDialog fileDlg(_("Select template file"),
1708                         LFUN_SELECT_FILE_SYNC,
1709                         make_pair(string(_("Documents|#o#O")),
1710                                   string(lyxrc.document_path)),
1711                         make_pair(string(_("Templates|#T#t")),
1712                                   string(lyxrc.template_path)));
1713
1714                 FileDialog::Result result =
1715                         fileDlg.open(lyxrc.template_path,
1716                                        _("*.lyx| LyX Documents (*.lyx)"));
1717
1718                 if (result.first == FileDialog::Later)
1719                         return;
1720
1721                 string const fname = result.second;
1722
1723                 if (fname.empty())
1724                         return;
1725                 templname = fname;
1726         }
1727
1728         view()->buffer(bufferlist.newFile(filename, templname, !name.empty()));
1729 }
1730
1731
1732 void LyXFunc::open(string const & fname)
1733 {
1734         string initpath = lyxrc.document_path;
1735
1736         if (view()->available()) {
1737                 string const trypath = owner->buffer()->filePath();
1738                 // If directory is writeable, use this as default.
1739                 if (IsDirWriteable(trypath))
1740                         initpath = trypath;
1741         }
1742
1743         string filename;
1744
1745         if (fname.empty()) {
1746                 FileDialog fileDlg(_("Select document to open"),
1747                         LFUN_FILE_OPEN,
1748                         make_pair(string(_("Documents|#o#O")),
1749                                   string(lyxrc.document_path)),
1750                         make_pair(string(_("Examples|#E#e")),
1751                                   string(AddPath(system_lyxdir, "examples"))));
1752
1753                 FileDialog::Result result =
1754                         fileDlg.open(initpath,
1755                                        _("*.lyx| LyX Documents (*.lyx)"));
1756
1757                 if (result.first == FileDialog::Later)
1758                         return;
1759
1760                 filename = result.second;
1761
1762                 // check selected filename
1763                 if (filename.empty()) {
1764                         owner->message(_("Canceled."));
1765                         return;
1766                 }
1767         } else
1768                 filename = fname;
1769
1770         // get absolute path of file and add ".lyx" to the filename if
1771         // necessary
1772         string const fullpath = FileSearch(string(), filename, "lyx");
1773         if (!fullpath.empty()) {
1774                 filename = fullpath;
1775         }
1776
1777         string const disp_fn(MakeDisplayPath(filename));
1778
1779         // if the file doesn't exist, let the user create one
1780         FileInfo const f(filename, true);
1781         if (!f.exist()) {
1782                 // the user specifically chose this name. Believe them.
1783                 Buffer * buffer =  bufferlist.newFile(filename, "", true);
1784                 view()->buffer(buffer);
1785                 return;
1786         }
1787
1788         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1789
1790         Buffer * openbuf = bufferlist.loadLyXFile(filename);
1791         string str2;
1792         if (openbuf) {
1793                 view()->buffer(openbuf);
1794                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1795         } else {
1796                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1797         }
1798         owner->message(str2);
1799 }
1800
1801
1802 void LyXFunc::doImport(string const & argument)
1803 {
1804         string format;
1805         string filename = split(argument, format, ' ');
1806
1807         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1808                             << " file: " << filename << endl;
1809
1810         // need user interaction
1811         if (filename.empty()) {
1812                 string initpath = lyxrc.document_path;
1813
1814                 if (view()->available()) {
1815                         string const trypath = owner->buffer()->filePath();
1816                         // If directory is writeable, use this as default.
1817                         if (IsDirWriteable(trypath))
1818                                 initpath = trypath;
1819                 }
1820
1821                 string const text = bformat(_("Select %1$s file to import"),
1822                         formats.prettyName(format));
1823
1824                 FileDialog fileDlg(text,
1825                         LFUN_IMPORT,
1826                         make_pair(string(_("Documents|#o#O")),
1827                                   string(lyxrc.document_path)),
1828                         make_pair(string(_("Examples|#E#e")),
1829                                   string(AddPath(system_lyxdir, "examples"))));
1830
1831                 string const extension = "*." + formats.extension(format)
1832                         + "| " + formats.prettyName(format)
1833                         + " (*." + formats.extension(format) + ')';
1834
1835                 FileDialog::Result result = fileDlg.open(initpath,
1836                                                            extension);
1837
1838                 if (result.first == FileDialog::Later)
1839                         return;
1840
1841                 filename = result.second;
1842
1843                 // check selected filename
1844                 if (filename.empty())
1845                         owner->message(_("Canceled."));
1846         }
1847
1848         if (filename.empty())
1849                 return;
1850
1851         // get absolute path of file
1852         filename = MakeAbsPath(filename);
1853
1854         string const lyxfile = ChangeExtension(filename, ".lyx");
1855
1856         // Check if the document already is open
1857         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1858                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1859                         owner->message(_("Canceled."));
1860                         return;
1861                 }
1862         }
1863
1864         // if the file exists already, and we didn't do
1865         // -i lyx thefile.lyx, warn
1866         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1867                 string const file = MakeDisplayPath(lyxfile, 30);
1868
1869                 string text = bformat(_("The document %1$s already exists.\n\n"
1870                         "Do you want to over-write that document?"), file);
1871                 int const ret = Alert::prompt(_("Over-write document?"),
1872                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1873
1874                 if (ret == 1) {
1875                         owner->message(_("Canceled."));
1876                         return;
1877                 }
1878         }
1879
1880         Importer::Import(owner, filename, format);
1881 }
1882
1883
1884 void LyXFunc::closeBuffer()
1885 {
1886         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1887                 if (bufferlist.empty()) {
1888                         // need this otherwise SEGV may occur while trying to
1889                         // set variables that don't exist
1890                         // since there's no current buffer
1891                         owner->getDialogs().hideBufferDependent();
1892                 } else {
1893                         view()->buffer(bufferlist.first());
1894                 }
1895         }
1896 }
1897
1898
1899 // Each "owner" should have it's own message method. lyxview and
1900 // the minibuffer would use the minibuffer, but lyxserver would
1901 // send an ERROR signal to its client.  Alejandro 970603
1902 // This func is bit problematic when it comes to NLS, to make the
1903 // lyx servers client be language indepenent we must not translate
1904 // strings sent to this func.
1905 void LyXFunc::setErrorMessage(string const & m) const
1906 {
1907         dispatch_buffer = m;
1908         errorstat = true;
1909 }
1910
1911
1912 void LyXFunc::setMessage(string const & m) const
1913 {
1914         dispatch_buffer = m;
1915 }
1916
1917
1918 void LyXFunc::setStatusMessage(string const & m) const
1919 {
1920         status_buffer = m;
1921 }
1922
1923
1924 string const LyXFunc::view_status_message()
1925 {
1926         // When meta-fake key is pressed, show the key sequence so far + "M-".
1927         if (wasMetaKey()) {
1928                 return keyseq.print() + "M-";
1929         }
1930
1931         // Else, when a non-complete key sequence is pressed,
1932         // show the available options.
1933         if (keyseq.length() > 0 && !keyseq.deleted()) {
1934                 return keyseq.printOptions();
1935         }
1936
1937         if (!view()->available())
1938                 return _("Welcome to LyX!");
1939
1940         return currentState(view());
1941 }
1942
1943
1944 BufferView * LyXFunc::view() const
1945 {
1946         lyx::Assert(owner);
1947         return owner->view().get();
1948 }