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