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