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