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