]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
d079a8970b8c0a54a1b052f9e4be572ab5c75486
[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                         par.lockPath(view());
1168                         LyXText * lt = par.text(*view()->buffer());
1169
1170                         // Set the cursor
1171                         lt->setCursor(par.pit(), 0);
1172                         view()->switchKeyMap();
1173                         owner->view_state_changed();
1174
1175                         view()->center();
1176                         // see BufferView_pimpl::center()
1177                         view()->updateScrollbar();
1178                         break;
1179                 }
1180
1181                 // ---  Mathed stuff. If we are here, there is no locked inset yet.
1182                 case LFUN_MATH_EXTERN:
1183                 case LFUN_MATH_NUMBER:
1184                 case LFUN_MATH_NONUMBER:
1185                 case LFUN_MATH_LIMITS:
1186                         setErrorMessage(N_("This is only allowed in math mode!"));
1187                         break;
1188
1189                 case LFUN_DIALOG_SHOW: {
1190                         string const name = cmd.getArg(0);
1191                         string data = trim(cmd.argument.substr(name.size()));
1192
1193                         if (name == "character") {
1194                                 data = freefont2string();
1195                                 if (!data.empty())
1196                                         owner->getDialogs().show("character", data);
1197                         }
1198                         else if (name == "document")
1199                                 owner->getDialogs().showDocument();
1200                         else if (name == "forks")
1201                                 owner->getDialogs().showForks();
1202                         else if (name == "preamble")
1203                                 owner->getDialogs().showPreamble();
1204                         else if (name == "preferences")
1205                                 owner->getDialogs().showPreferences();
1206                         else if (name == "print")
1207                                 owner->getDialogs().showPrint();
1208                         else if (name == "spellchecker")
1209                                 owner->getDialogs().showSpellchecker();
1210
1211                         else if (name == "latexlog") {
1212                                 pair<Buffer::LogType, string> const logfile =
1213                                         owner->buffer()->getLogName();
1214                                 switch (logfile.first) {
1215                                 case Buffer::latexlog:
1216                                         data = "latex ";
1217                                         break;
1218                                 case Buffer::buildlog:
1219                                         data = "literate ";
1220                                         break;
1221                                 }
1222                                 data += logfile.second;
1223                                 owner->getDialogs().show("log", data);
1224                         }
1225                         else if (name == "vclog") {
1226                                 string const data = "vc " +
1227                                         owner->buffer()->lyxvc().getLogFile();
1228                                 owner->getDialogs().show("log", data);
1229                         }
1230                         else
1231                                 owner->getDialogs().show(name, data);
1232                         break;
1233                 }
1234
1235                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1236                         string const name = cmd.getArg(0);
1237                         string data = trim(cmd.argument.substr(name.size()));
1238                         if (name == "bibitem" ||
1239                             name == "bibtex" ||
1240                             name == "include" ||
1241                             name == "index" ||
1242                             name == "label" ||
1243                             name == "ref" ||
1244                             name == "toc" ||
1245                             name == "url") {
1246                                 InsetCommandParams p(name);
1247                                 data = InsetCommandMailer::params2string(name, p);
1248                         } else if (name == "box") {
1249                                 // \c data == "Boxed" || "Frameless" etc
1250                                 InsetBoxParams p(data);
1251                                 data = InsetBoxMailer::params2string(p);
1252                         } else if (name == "branch") {
1253                                 InsetBranchParams p;
1254                                 data = InsetBranchMailer::params2string(p);
1255                         } else if (name == "citation") {
1256                                 InsetCommandParams p("cite");
1257                                 data = InsetCommandMailer::params2string(name, p);
1258                         } else if (name == "ert") {
1259                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1260                         } else if (name == "external") {
1261                                 InsetExternalParams p;
1262                                 Buffer const & buffer = *owner->buffer();
1263                                 data = InsetExternalMailer::params2string(p, buffer);
1264                         } else if (name == "float") {
1265                                 InsetFloatParams p;
1266                                 data = InsetFloatMailer::params2string(p);
1267                         } else if (name == "graphics") {
1268                                 InsetGraphicsParams p;
1269                                 Buffer const & buffer = *owner->buffer();
1270                                 data = InsetGraphicsMailer::params2string(p, buffer);
1271                         } else if (name == "note") {
1272                                 InsetNoteParams p;
1273                                 data = InsetNoteMailer::params2string(p);
1274                         } else if (name == "vspace") {
1275                                 VSpace space;
1276                                 data = InsetVSpaceMailer::params2string(space);
1277                         } else if (name == "wrap") {
1278                                 InsetWrapParams p;
1279                                 data = InsetWrapMailer::params2string(p);
1280                         }
1281                         owner->getDialogs().show(name, data, 0);
1282                         break;
1283                 }
1284
1285                 case LFUN_DIALOG_SHOW_NEXT_INSET:
1286                         break;
1287
1288                 case LFUN_INSET_DIALOG_SHOW: {
1289                         InsetBase * inset = view()->getLyXText()->getInset();
1290                         if (inset)
1291                                 inset->dispatch(view()->cursor(), FuncRequest(LFUN_INSET_DIALOG_SHOW));
1292                         break;
1293                 }
1294
1295                 case LFUN_DIALOG_UPDATE: {
1296                         string const & name = argument;
1297                         // Can only update a dialog connected to an existing inset
1298                         InsetBase * inset = owner->getDialogs().getOpenInset(name);
1299                         if (inset) {
1300                                 FuncRequest fr(LFUN_INSET_DIALOG_UPDATE, cmd.argument);
1301                                 inset->dispatch(view()->cursor(), fr);
1302                         } else if (name == "paragraph") {
1303                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1304                         }
1305                         break;
1306                 }
1307
1308                 case LFUN_DIALOG_HIDE:
1309                         Dialogs::hide(argument, 0);
1310                         break;
1311
1312                 case LFUN_DIALOG_DISCONNECT_INSET:
1313                         owner->getDialogs().disconnect(argument);
1314                         break;
1315
1316                 case LFUN_CHILDOPEN: {
1317                         string const filename =
1318                                 MakeAbsPath(argument, owner->buffer()->filePath());
1319                         setMessage(N_("Opening child document ") +
1320                                          MakeDisplayPath(filename) + "...");
1321                         view()->savePosition(0);
1322                         string const parentfilename = owner->buffer()->fileName();
1323                         if (bufferlist.exists(filename))
1324                                 view()->buffer(bufferlist.getBuffer(filename));
1325                         else
1326                                 view()->loadLyXFile(filename);
1327                         // Set the parent name of the child document.
1328                         // This makes insertion of citations and references in the child work,
1329                         // when the target is in the parent or another child document.
1330                         owner->buffer()->setParentName(parentfilename);
1331                         break;
1332                 }
1333
1334                 case LFUN_TOGGLECURSORFOLLOW:
1335                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1336                         break;
1337
1338                 case LFUN_KMAP_OFF:
1339                         owner->getIntl().KeyMapOn(false);
1340                         break;
1341
1342                 case LFUN_KMAP_PRIM:
1343                         owner->getIntl().KeyMapPrim();
1344                         break;
1345
1346                 case LFUN_KMAP_SEC:
1347                         owner->getIntl().KeyMapSec();
1348                         break;
1349
1350                 case LFUN_KMAP_TOGGLE:
1351                         owner->getIntl().ToggleKeyMap();
1352                         break;
1353
1354                 case LFUN_REPEAT: {
1355                         // repeat command
1356                         string countstr;
1357                         argument = split(argument, countstr, ' ');
1358                         istringstream is(countstr);
1359                         int count = 0;
1360                         is >> count;
1361                         lyxerr << "repeat: count: " << count << " cmd: " << argument << endl;
1362                         for (int i = 0; i < count; ++i)
1363                                 dispatch(lyxaction.lookupFunc(argument));
1364                         break;
1365                 }
1366
1367                 case LFUN_SEQUENCE:
1368                         // argument contains ';'-terminated commands
1369                         while (!argument.empty()) {
1370                                 string first;
1371                                 argument = split(argument, first, ';');
1372                                 dispatch(lyxaction.lookupFunc(first));
1373                         }
1374                         break;
1375
1376                 case LFUN_SAVEPREFERENCES: {
1377                         Path p(user_lyxdir());
1378                         lyxrc.write("preferences");
1379                         break;
1380                 }
1381
1382                 case LFUN_SCREEN_FONT_UPDATE:
1383                         // handle the screen font changes.
1384                         lyxrc.set_font_norm_type();
1385                         lyx_gui::update_fonts();
1386                         // All visible buffers will need resize
1387                         view()->resize();
1388                         break;
1389
1390                 case LFUN_SET_COLOR: {
1391                         string lyx_name;
1392                         string const x11_name = split(argument, lyx_name, ' ');
1393                         if (lyx_name.empty() || x11_name.empty()) {
1394                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1395                                                         " <x11_name>"));
1396                                 break;
1397                         }
1398
1399                         bool const graphicsbg_changed =
1400                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1401                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1402
1403                         LColor::color col = lcolor.getFromLyXName(lyx_name);
1404                         if (!lcolor.setColor(col, x11_name)) {
1405                                 setErrorMessage(
1406                                         bformat(_("Set-color \"%1$s\" failed "
1407                                                                 "- color is undefined or "
1408                                                                 "may not be redefined"), lyx_name));
1409                                 break;
1410                         }
1411
1412                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1413
1414                         if (graphicsbg_changed) {
1415 #ifdef WITH_WARNINGS
1416 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1417 #endif
1418 #if 0
1419                                 lyx::graphics::GCache::get().changeDisplay(true);
1420 #endif
1421                         }
1422                         break;
1423                 }
1424
1425                 case LFUN_MESSAGE:
1426                         owner->message(argument);
1427                         break;
1428
1429                 case LFUN_FORKS_KILL:
1430                         if (isStrInt(argument))
1431                                 ForkedcallsController::get().kill(strToInt(argument));
1432                         break;
1433
1434                 case LFUN_TOOLTIPS_TOGGLE:
1435                         owner->getDialogs().toggleTooltips();
1436                         break;
1437
1438                 case LFUN_EXTERNAL_EDIT:
1439                         InsetExternal().dispatch(view()->cursor(), FuncRequest(action, argument));
1440                         break;
1441
1442                 default:
1443                         view()->cursor().dispatch(cmd);
1444                         break;
1445                 }
1446         }
1447
1448         view()->owner()->updateLayoutChoice();
1449
1450         if (view()->available()) {
1451                 view()->fitCursor();
1452                 view()->update();
1453                 view()->cursor().updatePos();
1454                 // if we executed a mutating lfun, mark the buffer as dirty
1455                 if (!getStatus(cmd).disabled()
1456                     && !lyxaction.funcHasFlag(cmd.action, LyXAction::NoBuffer)
1457                     && !lyxaction.funcHasFlag(cmd.action, LyXAction::ReadOnly))
1458                         view()->buffer()->markDirty();
1459         }
1460
1461         sendDispatchMessage(getMessage(), cmd, verbose);
1462 }
1463
1464
1465 void LyXFunc::sendDispatchMessage(string const & msg,
1466                                   FuncRequest const & cmd, bool verbose)
1467 {
1468         owner->updateMenubar();
1469         owner->updateToolbar();
1470
1471         if (cmd.action == LFUN_SELFINSERT || !verbose) {
1472                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1473                 if (!msg.empty())
1474                         owner->message(msg);
1475                 return;
1476         }
1477
1478         string dispatch_msg = msg;
1479         if (!dispatch_msg.empty())
1480                 dispatch_msg += ' ';
1481
1482         string comname = lyxaction.getActionName(cmd.action);
1483
1484         bool argsadded = false;
1485
1486         if (!cmd.argument.empty()) {
1487                 if (cmd.action != LFUN_UNKNOWN_ACTION) {
1488                         comname += ' ' + cmd.argument;
1489                         argsadded = true;
1490                 }
1491         }
1492
1493         string const shortcuts = toplevel_keymap->findbinding(cmd);
1494
1495         if (!shortcuts.empty()) {
1496                 comname += ": " + shortcuts;
1497         } else if (!argsadded && !cmd.argument.empty()) {
1498                 comname += ' ' + cmd.argument;
1499         }
1500
1501         if (!comname.empty()) {
1502                 comname = rtrim(comname);
1503                 dispatch_msg += '(' + comname + ')';
1504         }
1505
1506         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1507         if (!dispatch_msg.empty())
1508                 owner->message(dispatch_msg);
1509 }
1510
1511
1512 void LyXFunc::setupLocalKeymap()
1513 {
1514         keyseq.stdmap = toplevel_keymap.get();
1515         keyseq.curmap = toplevel_keymap.get();
1516         cancel_meta_seq.stdmap = toplevel_keymap.get();
1517         cancel_meta_seq.curmap = toplevel_keymap.get();
1518 }
1519
1520
1521 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1522 {
1523         string initpath = lyxrc.document_path;
1524         string filename(name);
1525
1526         if (view()->available()) {
1527                 string const trypath = owner->buffer()->filePath();
1528                 // If directory is writeable, use this as default.
1529                 if (IsDirWriteable(trypath))
1530                         initpath = trypath;
1531         }
1532
1533         static int newfile_number;
1534
1535         if (filename.empty()) {
1536                 filename = AddName(lyxrc.document_path,
1537                             "newfile" + tostr(++newfile_number) + ".lyx");
1538                 FileInfo fi(filename);
1539                 while (bufferlist.exists(filename) || fi.readable()) {
1540                         ++newfile_number;
1541                         filename = AddName(lyxrc.document_path,
1542                                     "newfile" + tostr(newfile_number) +
1543                                     ".lyx");
1544                         fi.newFile(filename);
1545                 }
1546         }
1547
1548         // The template stuff
1549         string templname;
1550         if (fromTemplate) {
1551                 FileDialog fileDlg(_("Select template file"),
1552                         LFUN_SELECT_FILE_SYNC,
1553                         make_pair(string(_("Documents|#o#O")),
1554                                   string(lyxrc.document_path)),
1555                         make_pair(string(_("Templates|#T#t")),
1556                                   string(lyxrc.template_path)));
1557
1558                 FileDialog::Result result =
1559                         fileDlg.open(lyxrc.template_path,
1560                                      FileFilterList(_("LyX Documents (*.lyx)")),
1561                                      string());
1562
1563                 if (result.first == FileDialog::Later)
1564                         return;
1565                 if (result.second.empty())
1566                         return;
1567                 templname = result.second;
1568         }
1569
1570         view()->newFile(filename, templname, !name.empty());
1571 }
1572
1573
1574 void LyXFunc::open(string const & fname)
1575 {
1576         string initpath = lyxrc.document_path;
1577
1578         if (view()->available()) {
1579                 string const trypath = owner->buffer()->filePath();
1580                 // If directory is writeable, use this as default.
1581                 if (IsDirWriteable(trypath))
1582                         initpath = trypath;
1583         }
1584
1585         string filename;
1586
1587         if (fname.empty()) {
1588                 FileDialog fileDlg(_("Select document to open"),
1589                         LFUN_FILE_OPEN,
1590                         make_pair(string(_("Documents|#o#O")),
1591                                   string(lyxrc.document_path)),
1592                         make_pair(string(_("Examples|#E#e")),
1593                                   string(AddPath(system_lyxdir(), "examples"))));
1594
1595                 FileDialog::Result result =
1596                         fileDlg.open(initpath,
1597                                      FileFilterList(_("LyX Documents (*.lyx)")),
1598                                      string());
1599
1600                 if (result.first == FileDialog::Later)
1601                         return;
1602
1603                 filename = result.second;
1604
1605                 // check selected filename
1606                 if (filename.empty()) {
1607                         owner->message(_("Canceled."));
1608                         return;
1609                 }
1610         } else
1611                 filename = fname;
1612
1613         // get absolute path of file and add ".lyx" to the filename if
1614         // necessary
1615         string const fullpath = FileSearch(string(), filename, "lyx");
1616         if (!fullpath.empty()) {
1617                 filename = fullpath;
1618         }
1619
1620         string const disp_fn(MakeDisplayPath(filename));
1621
1622         // if the file doesn't exist, let the user create one
1623         FileInfo const f(filename, true);
1624         if (!f.exist()) {
1625                 // the user specifically chose this name. Believe them.
1626                 view()->newFile(filename, "", true);
1627                 return;
1628         }
1629
1630         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1631
1632         string str2;
1633         if (view()->loadLyXFile(filename)) {
1634                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1635         } else {
1636                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1637         }
1638         owner->message(str2);
1639 }
1640
1641
1642 void LyXFunc::doImport(string const & argument)
1643 {
1644         string format;
1645         string filename = split(argument, format, ' ');
1646
1647         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1648                             << " file: " << filename << endl;
1649
1650         // need user interaction
1651         if (filename.empty()) {
1652                 string initpath = lyxrc.document_path;
1653
1654                 if (view()->available()) {
1655                         string const trypath = owner->buffer()->filePath();
1656                         // If directory is writeable, use this as default.
1657                         if (IsDirWriteable(trypath))
1658                                 initpath = trypath;
1659                 }
1660
1661                 string const text = bformat(_("Select %1$s file to import"),
1662                         formats.prettyName(format));
1663
1664                 FileDialog fileDlg(text,
1665                         LFUN_IMPORT,
1666                         make_pair(string(_("Documents|#o#O")),
1667                                   string(lyxrc.document_path)),
1668                         make_pair(string(_("Examples|#E#e")),
1669                                   string(AddPath(system_lyxdir(), "examples"))));
1670
1671                 string const filter = formats.prettyName(format)
1672                         + " (*." + formats.extension(format) + ')';
1673
1674                 FileDialog::Result result =
1675                         fileDlg.open(initpath,
1676                                      FileFilterList(filter),
1677                                      string());
1678
1679                 if (result.first == FileDialog::Later)
1680                         return;
1681
1682                 filename = result.second;
1683
1684                 // check selected filename
1685                 if (filename.empty())
1686                         owner->message(_("Canceled."));
1687         }
1688
1689         if (filename.empty())
1690                 return;
1691
1692         // get absolute path of file
1693         filename = MakeAbsPath(filename);
1694
1695         string const lyxfile = ChangeExtension(filename, ".lyx");
1696
1697         // Check if the document already is open
1698         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1699                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1700                         owner->message(_("Canceled."));
1701                         return;
1702                 }
1703         }
1704
1705         // if the file exists already, and we didn't do
1706         // -i lyx thefile.lyx, warn
1707         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1708                 string const file = MakeDisplayPath(lyxfile, 30);
1709
1710                 string text = bformat(_("The document %1$s already exists.\n\n"
1711                         "Do you want to over-write that document?"), file);
1712                 int const ret = Alert::prompt(_("Over-write document?"),
1713                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1714
1715                 if (ret == 1) {
1716                         owner->message(_("Canceled."));
1717                         return;
1718                 }
1719         }
1720
1721         Importer::Import(owner, filename, format);
1722 }
1723
1724
1725 void LyXFunc::closeBuffer()
1726 {
1727         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1728                 if (bufferlist.empty()) {
1729                         // need this otherwise SEGV may occur while
1730                         // trying to set variables that don't exist
1731                         // since there's no current buffer
1732                         owner->getDialogs().hideBufferDependent();
1733                 } else {
1734                         view()->buffer(bufferlist.first());
1735                 }
1736         }
1737 }
1738
1739
1740 // Each "owner" should have it's own message method. lyxview and
1741 // the minibuffer would use the minibuffer, but lyxserver would
1742 // send an ERROR signal to its client.  Alejandro 970603
1743 // This function is bit problematic when it comes to NLS, to make the
1744 // lyx servers client be language indepenent we must not translate
1745 // strings sent to this func.
1746 void LyXFunc::setErrorMessage(string const & m) const
1747 {
1748         dispatch_buffer = m;
1749         errorstat = true;
1750 }
1751
1752
1753 void LyXFunc::setMessage(string const & m) const
1754 {
1755         dispatch_buffer = m;
1756 }
1757
1758
1759 void LyXFunc::setStatusMessage(string const & m) const
1760 {
1761         status_buffer = m;
1762 }
1763
1764
1765 string const LyXFunc::view_status_message()
1766 {
1767         // When meta-fake key is pressed, show the key sequence so far + "M-".
1768         if (wasMetaKey()) {
1769                 return keyseq.print() + "M-";
1770         }
1771
1772         // Else, when a non-complete key sequence is pressed,
1773         // show the available options.
1774         if (keyseq.length() > 0 && !keyseq.deleted()) {
1775                 return keyseq.printOptions();
1776         }
1777
1778         if (!view()->available())
1779                 return _("Welcome to LyX!");
1780
1781         return currentState(view());
1782 }
1783
1784
1785 BufferView * LyXFunc::view() const
1786 {
1787         BOOST_ASSERT(owner);
1788         return owner->view().get();
1789 }
1790
1791
1792 bool LyXFunc::wasMetaKey() const
1793 {
1794         return (meta_fake_bit != key_modifier::none);
1795 }