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