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