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