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