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