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