]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
Overhaul the branches code.
[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_MINIPAGE:
613                 code = InsetOld::BOX_CODE;
614                 break;
615         case LFUN_INSET_FLOAT:
616         case LFUN_INSET_WIDE_FLOAT:
617                 code = InsetOld::FLOAT_CODE;
618                 break;
619         case LFUN_INSET_WRAP:
620                 code = InsetOld::WRAP_CODE;
621                 break;
622         case LFUN_FLOAT_LIST:
623                 code = InsetOld::FLOAT_LIST_CODE;
624                 break;
625 #if 0
626         case LFUN_INSET_LIST:
627                 code = InsetOld::LIST_CODE;
628                 break;
629         case LFUN_INSET_THEOREM:
630                 code = InsetOld::THEOREM_CODE;
631                 break;
632 #endif
633         case LFUN_INSET_CAPTION:
634                 code = InsetOld::CAPTION_CODE;
635                 break;
636         case LFUN_INSERT_NOTE:
637                 code = InsetOld::NOTE_CODE;
638                 break;
639         case LFUN_INSERT_CHARSTYLE:
640                 code = InsetOld::CHARSTYLE_CODE;
641                 if (buf->params().getLyXTextClass().charstyles().empty())
642                         disable = true;
643                 break;
644         case LFUN_INSERT_BOX:
645                 code = InsetOld::BOX_CODE;
646                 break;
647         case LFUN_INSERT_BRANCH:
648                 code = InsetOld::BRANCH_CODE;
649                 if (buf->params().branchlist().empty())
650                         disable = true;
651                 break;
652         case LFUN_INSERT_LABEL:
653                 code = InsetOld::LABEL_CODE;
654                 break;
655         case LFUN_INSET_OPTARG:
656                 code = InsetOld::OPTARG_CODE;
657                 break;
658         case LFUN_ENVIRONMENT_INSERT:
659                 code = InsetOld::BOX_CODE;
660                 break;
661         case LFUN_INDEX_INSERT:
662                 code = InsetOld::INDEX_CODE;
663                 break;
664         case LFUN_INDEX_PRINT:
665                 code = InsetOld::INDEX_PRINT_CODE;
666                 break;
667         case LFUN_TOC_INSERT:
668                 code = InsetOld::TOC_CODE;
669                 break;
670         case LFUN_HTMLURL:
671         case LFUN_URL:
672                 code = InsetOld::URL_CODE;
673                 break;
674         case LFUN_QUOTE:
675                 // always allow this, since we will inset a raw quote
676                 // if an inset is not allowed.
677                 break;
678         case LFUN_HYPHENATION:
679         case LFUN_LIGATURE_BREAK:
680         case LFUN_HFILL:
681         case LFUN_MENU_SEPARATOR:
682         case LFUN_LDOTS:
683         case LFUN_END_OF_SENTENCE:
684                 code = InsetOld::SPECIALCHAR_CODE;
685                 break;
686         case LFUN_SPACE_INSERT:
687                 // slight hack: we know this is allowed in math mode
688                 if (!mathcursor)
689                         code = InsetOld::SPACE_CODE;
690                 break;
691         case LFUN_INSET_DIALOG_SHOW: {
692                 InsetOld * inset = view()->getLyXText()->getInset();
693                 disable = !inset;
694                 if (!disable) {
695                         code = inset->lyxCode();
696                         if (!(code == InsetOld::INCLUDE_CODE
697                                 || code == InsetOld::BIBTEX_CODE
698                                 || code == InsetOld::FLOAT_LIST_CODE
699                                 || code == InsetOld::TOC_CODE))
700                                 disable = true;
701                 }
702                 break;
703         }
704         default:
705                 break;
706         }
707         if (code != InsetOld::NO_CODE && tli && !tli->insetAllowed(code))
708                 disable = true;
709
710         if (disable)
711                 flag.disabled(true);
712
713         // A few general toggles
714         switch (ev.action) {
715         case LFUN_TOOLTIPS_TOGGLE:
716                 flag.setOnOff(owner->getDialogs().tooltipsEnabled());
717                 break;
718
719         case LFUN_READ_ONLY_TOGGLE:
720                 flag.setOnOff(buf->isReadonly());
721                 break;
722         case LFUN_APPENDIX:
723                 flag.setOnOff(view()->getLyXText()->cursorPar()->params().startOfAppendix());
724                 break;
725         case LFUN_SWITCHBUFFER:
726                 // toggle on the current buffer, but do not toggle off
727                 // the other ones (is that a good idea?)
728                 if (ev.argument == buf->fileName())
729                         flag.setOnOff(true);
730                 break;
731         case LFUN_TRACK_CHANGES:
732                 flag.setOnOff(buf->params().tracking_changes);
733                 break;
734         default:
735                 break;
736         }
737
738 #ifdef LOCK
739         // the font related toggles
740         if (!mathcursor) {
741                 LyXFont const & font = view()->getLyXText()->real_current_font;
742                 switch (ev.action) {
743                 case LFUN_EMPH:
744                         flag.setOnOff(font.emph() == LyXFont::ON);
745                         break;
746                 case LFUN_NOUN:
747                         flag.setOnOff(font.noun() == LyXFont::ON);
748                         break;
749                 case LFUN_BOLD:
750                         flag.setOnOff(font.series() == LyXFont::BOLD_SERIES);
751                         break;
752                 case LFUN_SANS:
753                         flag.setOnOff(font.family() == LyXFont::SANS_FAMILY);
754                         break;
755                 case LFUN_ROMAN:
756                         flag.setOnOff(font.family() == LyXFont::ROMAN_FAMILY);
757                         break;
758                 case LFUN_CODE:
759                         flag.setOnOff(font.family() == LyXFont::TYPEWRITER_FAMILY);
760                         break;
761                 default:
762                         break;
763                 }
764         } else {
765                 string tc = mathcursor->getLastCode();
766                 switch (ev.action) {
767                 case LFUN_BOLD:
768                         flag.setOnOff(tc == "mathbf");
769                         break;
770                 case LFUN_SANS:
771                         flag.setOnOff(tc == "mathsf");
772                         break;
773                 case LFUN_EMPH:
774                         flag.setOnOff(tc == "mathcal");
775                         break;
776                 case LFUN_ROMAN:
777                         flag.setOnOff(tc == "mathrm");
778                         break;
779                 case LFUN_CODE:
780                         flag.setOnOff(tc == "mathtt");
781                         break;
782                 case LFUN_NOUN:
783                         flag.setOnOff(tc == "mathbb");
784                         break;
785                 case LFUN_DEFAULT:
786                         flag.setOnOff(tc == "mathnormal");
787                         break;
788                 default:
789                         break;
790                 }
791         }
792 #endif
793
794         // this one is difficult to get right. As a half-baked
795         // solution, we consider only the first action of the sequence
796         if (ev.action == LFUN_SEQUENCE) {
797                 // argument contains ';'-terminated commands
798 #warning LyXAction arguments not handled here.
799                 flag = getStatus(FuncRequest(lyxaction.lookupFunc(token(ev.argument, ';', 0))));
800         }
801
802         return flag;
803 }
804
805
806 namespace {
807
808 bool ensureBufferClean(BufferView * bv)
809 {
810         Buffer & buf = *bv->buffer();
811         if (buf.isClean())
812                 return true;
813
814         string const file = MakeDisplayPath(buf.fileName(), 30);
815         string text = bformat(_("The document %1$s has unsaved "
816                                 "changes.\n\nDo you want to save "
817                                 "the document?"), file);
818         int const ret = Alert::prompt(_("Save changed document?"),
819                                       text, 0, 1, _("&Save"),
820                                       _("&Cancel"));
821
822         if (ret == 0)
823                 bv->owner()->dispatch(FuncRequest(LFUN_MENUWRITE));
824
825         return buf.isClean();
826 }
827
828 } //namespace anon
829
830
831 void LyXFunc::dispatch(FuncRequest const & func, bool verbose)
832 {
833         string argument = func.argument;
834         kb_action action = func.action;
835
836         //lyxerr[Debug::ACTION] << "LyXFunc::dispatch: cmd: " << func << endl;
837         lyxerr << "LyXFunc::dispatch: cmd: " << func << endl;
838
839         // we have not done anything wrong yet.
840         errorstat = false;
841         dispatch_buffer.erase();
842
843 #ifdef NEW_DISPATCHER
844         // We try do call the most specific dispatcher first:
845         //  1. the lockinginset's dispatch
846         //  2. the bufferview's dispatch
847         //  3. the lyxview's dispatch
848 #endif
849
850         selection_possible = false;
851
852         // We cannot use this function here
853         if (getStatus(func).disabled()) {
854                 lyxerr[Debug::ACTION] << "LyXFunc::dispatch: "
855                        << lyxaction.getActionName(action)
856                        << " [" << action << "] is disabled at this location"
857                        << endl;
858                 setErrorMessage(getStatusMessage());
859
860         } else {
861
862                 if (view()->available())
863                         view()->hideCursor();
864
865                 switch (action) {
866
867                 case LFUN_ESCAPE: {
868                         if (!view()->available())
869                                 break;
870                         view()->cursor().pop();
871                         // Tell the paragraph dialog that we changed paragraph
872                         dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
873                         break;
874                 }
875
876                 case LFUN_WORDFINDFORWARD:
877                 case LFUN_WORDFINDBACKWARD: {
878                         static string last_search;
879                         string searched_string;
880
881                         if (!argument.empty()) {
882                                 last_search = argument;
883                                 searched_string = argument;
884                         } else {
885                                 searched_string = last_search;
886                         }
887                         bool fw = (action == LFUN_WORDFINDFORWARD);
888                         if (!searched_string.empty())
889                                 lyx::find::find(view(), searched_string,
890                                                 true, false, fw);
891                         break;
892                 }
893
894                 case LFUN_PREFIX:
895                         owner->message(keyseq.printOptions());
896                         break;
897
898                 case LFUN_EXEC_COMMAND:
899                         owner->focus_command_buffer();
900                         break;
901
902                 case LFUN_CANCEL:
903                         keyseq.reset();
904                         meta_fake_bit = key_modifier::none;
905                         if (view()->available())
906                                 // cancel any selection
907                                 dispatch(FuncRequest(LFUN_MARK_OFF));
908                         setMessage(N_("Cancel"));
909                         break;
910
911                 case LFUN_META_FAKE:
912                         meta_fake_bit = key_modifier::alt;
913                         setMessage(keyseq.print());
914                         break;
915
916                 case LFUN_READ_ONLY_TOGGLE:
917                         if (owner->buffer()->lyxvc().inUse())
918                                 owner->buffer()->lyxvc().toggleReadOnly();
919                         else
920                                 owner->buffer()->setReadonly(
921                                         !owner->buffer()->isReadonly());
922                         break;
923
924                 case LFUN_CENTER: // this is center and redraw.
925                         view()->center();
926                         break;
927
928                 // --- Menus -----------------------------------------------
929                 case LFUN_MENUNEW:
930                         menuNew(argument, false);
931                         break;
932
933                 case LFUN_MENUNEWTMPLT:
934                         menuNew(argument, true);
935                         break;
936
937                 case LFUN_CLOSEBUFFER:
938                         closeBuffer();
939                         break;
940
941                 case LFUN_MENUWRITE:
942                         if (!owner->buffer()->isUnnamed()) {
943                                 string const str = bformat(_("Saving document %1$s..."),
944                                          MakeDisplayPath(owner->buffer()->fileName()));
945                                 owner->message(str);
946                                 MenuWrite(owner->buffer());
947                                 owner->message(str + _(" done."));
948                         } else
949                                 WriteAs(owner->buffer());
950                         break;
951
952                 case LFUN_WRITEAS:
953                         WriteAs(owner->buffer(), argument);
954                         break;
955
956                 case LFUN_MENURELOAD: {
957                         string const file = MakeDisplayPath(view()->buffer()->fileName(), 20);
958                         string text = bformat(_("Any changes will be lost. Are you sure "
959                                 "you want to revert to the saved version of the document %1$s?"), file);
960                         int const ret = Alert::prompt(_("Revert to saved document?"),
961                                 text, 0, 1, _("&Revert"), _("&Cancel"));
962
963                         if (ret == 0)
964                                 view()->reload();
965                         break;
966                 }
967
968                 case LFUN_UPDATE:
969                         Exporter::Export(owner->buffer(), argument, true);
970                         view()->showErrorList(BufferFormat(*owner->buffer()));
971                         break;
972
973                 case LFUN_PREVIEW:
974                         Exporter::Preview(owner->buffer(), argument);
975                         view()->showErrorList(BufferFormat(*owner->buffer()));
976                         break;
977
978                 case LFUN_BUILDPROG:
979                         Exporter::Export(owner->buffer(), "program", true);
980                         view()->showErrorList(_("Build"));
981                         break;
982
983                 case LFUN_RUNCHKTEX:
984                         owner->buffer()->runChktex();
985                         view()->showErrorList(_("ChkTeX"));
986                         break;
987
988                 case LFUN_EXPORT:
989                         if (argument == "custom")
990                                 owner->getDialogs().showSendto();
991                         else {
992                                 Exporter::Export(owner->buffer(), argument, false);
993                                 view()->showErrorList(BufferFormat(*owner->buffer()));
994                         }
995                         break;
996
997                 case LFUN_IMPORT:
998                         doImport(argument);
999                         break;
1000
1001                 case LFUN_QUIT:
1002                         QuitLyX();
1003                         break;
1004
1005                 case LFUN_TOCVIEW: {
1006                         InsetCommandParams p("tableofcontents");
1007                         string const data = InsetCommandMailer::params2string("toc", p);
1008                         owner->getDialogs().show("toc", data, 0);
1009                         break;
1010                 }
1011
1012                 case LFUN_AUTOSAVE:
1013                         AutoSave(view());
1014                         break;
1015
1016                 case LFUN_UNDO:
1017                         view()->undo();
1018                         break;
1019
1020                 case LFUN_REDO:
1021                         view()->redo();
1022                         break;
1023
1024                 case LFUN_RECONFIGURE:
1025                         Reconfigure(view());
1026                         break;
1027
1028                 case LFUN_HELP_OPEN: {
1029                         string const arg = argument;
1030                         if (arg.empty()) {
1031                                 setErrorMessage(N_("Missing argument"));
1032                                 break;
1033                         }
1034                         string const fname = i18nLibFileSearch("doc", arg, "lyx");
1035                         if (fname.empty()) {
1036                                 lyxerr << "LyX: unable to find documentation file `"
1037                                                          << arg << "'. Bad installation?" << endl;
1038                                 break;
1039                         }
1040                         owner->message(bformat(_("Opening help file %1$s..."),
1041                                 MakeDisplayPath(fname)));
1042                         view()->loadLyXFile(fname, false);
1043                         break;
1044                 }
1045
1046                 // --- version control -------------------------------
1047                 case LFUN_VC_REGISTER:
1048                         if (!ensureBufferClean(view()))
1049                                 break;
1050                         if (!owner->buffer()->lyxvc().inUse()) {
1051                                 owner->buffer()->lyxvc().registrer();
1052                                 view()->reload();
1053                         }
1054                         break;
1055
1056                 case LFUN_VC_CHECKIN:
1057                         if (!ensureBufferClean(view()))
1058                                 break;
1059                         if (owner->buffer()->lyxvc().inUse()
1060                                         && !owner->buffer()->isReadonly()) {
1061                                 owner->buffer()->lyxvc().checkIn();
1062                                 view()->reload();
1063                         }
1064                         break;
1065
1066                 case LFUN_VC_CHECKOUT:
1067                         if (!ensureBufferClean(view()))
1068                                 break;
1069                         if (owner->buffer()->lyxvc().inUse()
1070                                         && owner->buffer()->isReadonly()) {
1071                                 owner->buffer()->lyxvc().checkOut();
1072                                 view()->reload();
1073                         }
1074                         break;
1075
1076                 case LFUN_VC_REVERT:
1077                         owner->buffer()->lyxvc().revert();
1078                         view()->reload();
1079                         break;
1080
1081                 case LFUN_VC_UNDO:
1082                         owner->buffer()->lyxvc().undoLast();
1083                         view()->reload();
1084                         break;
1085
1086                 // --- buffers ----------------------------------------
1087                 case LFUN_SWITCHBUFFER:
1088                         view()->buffer(bufferlist.getBuffer(argument));
1089                         break;
1090
1091                 case LFUN_FILE_NEW:
1092                         NewFile(view(), argument);
1093                         break;
1094
1095                 case LFUN_FILE_OPEN:
1096                         open(argument);
1097                         break;
1098
1099                 case LFUN_LAYOUT_TABULAR:
1100                         if (InsetTabular * tab = view()->cursor().innerInsetTabular())
1101                                 tab->openLayoutDialog(view());
1102                         break;
1103
1104                 case LFUN_DROP_LAYOUTS_CHOICE:
1105                         owner->getToolbar().openLayoutList();
1106                         break;
1107
1108                 case LFUN_MENU_OPEN_BY_NAME:
1109                         owner->getMenubar().openByName(argument);
1110                         break;
1111
1112                 // --- lyxserver commands ----------------------------
1113                 case LFUN_GETNAME:
1114                         setMessage(owner->buffer()->fileName());
1115                         lyxerr[Debug::INFO] << "FNAME["
1116                                                          << owner->buffer()->fileName()
1117                                                          << "] " << endl;
1118                         break;
1119
1120                 case LFUN_NOTIFY:
1121                         dispatch_buffer = keyseq.print();
1122                         lyxserver->notifyClient(dispatch_buffer);
1123                         break;
1124
1125                 case LFUN_GOTOFILEROW: {
1126                         string file_name;
1127                         int row;
1128                         istringstream is(argument);
1129                         is >> file_name >> row;
1130                         if (prefixIs(file_name, getTmpDir())) {
1131                                 // Needed by inverse dvi search. If it is a file
1132                                 // in tmpdir, call the apropriated function
1133                                 view()->buffer(bufferlist.getBufferFromTmp(file_name));
1134                         } else {
1135                                 // Must replace extension of the file to be .lyx
1136                                 // and get full path
1137                                 string const s = ChangeExtension(file_name, ".lyx");
1138                                 // Either change buffer or load the file
1139                                 if (bufferlist.exists(s)) {
1140                                         view()->buffer(bufferlist.getBuffer(s));
1141                                 } else {
1142                                         view()->loadLyXFile(s);
1143                                 }
1144                         }
1145
1146                         view()->setCursorFromRow(row);
1147
1148                         view()->center();
1149                         // see BufferView_pimpl::center()
1150                         view()->updateScrollbar();
1151                         break;
1152                 }
1153
1154                 case LFUN_GOTO_PARAGRAPH: {
1155                         istringstream is(argument);
1156                         int id;
1157                         is >> id;
1158                         ParIterator par = owner->buffer()->getParFromID(id);
1159                         if (par == owner->buffer()->par_iterator_end()) {
1160                                 lyxerr[Debug::INFO] << "No matching paragraph found! ["
1161                                                                 << id << ']' << endl;
1162                                 break;
1163                         } else {
1164                                 lyxerr[Debug::INFO] << "Paragraph " << par->id()
1165                                                                 << " found." << endl;
1166                         }
1167
1168                         par.lockPath(view());
1169                         LyXText * lt = par.text(*view()->buffer());
1170
1171                         // Set the cursor
1172                         lt->setCursor(par.pit(), 0);
1173                         view()->switchKeyMap();
1174                         owner->view_state_changed();
1175
1176                         view()->center();
1177                         // see BufferView_pimpl::center()
1178                         view()->updateScrollbar();
1179                         break;
1180                 }
1181
1182                 // ---  Mathed stuff. If we are here, there is no locked inset yet.
1183                 case LFUN_MATH_EXTERN:
1184                 case LFUN_MATH_NUMBER:
1185                 case LFUN_MATH_NONUMBER:
1186                 case LFUN_MATH_LIMITS:
1187                         setErrorMessage(N_("This is only allowed in math mode!"));
1188                         break;
1189
1190                 case LFUN_DIALOG_SHOW: {
1191                         string const name = func.getArg(0);
1192                         string data = trim(func.argument.substr(name.size()));
1193
1194                         if (name == "character") {
1195                                 data = freefont2string();
1196                                 if (!data.empty())
1197                                         owner->getDialogs().show("character", data);
1198                         }
1199                         else if (name == "document")
1200                                 owner->getDialogs().showDocument();
1201                         else if (name == "findreplace")
1202                                 owner->getDialogs().showSearch();
1203                         else if (name == "forks")
1204                                 owner->getDialogs().showForks();
1205                         else if (name == "preamble")
1206                                 owner->getDialogs().showPreamble();
1207                         else if (name == "preferences")
1208                                 owner->getDialogs().showPreferences();
1209                         else if (name == "print")
1210                                 owner->getDialogs().showPrint();
1211                         else if (name == "spellchecker")
1212                                 owner->getDialogs().showSpellchecker();
1213
1214                         else if (name == "latexlog") {
1215                                 pair<Buffer::LogType, string> const logfile =
1216                                         owner->buffer()->getLogName();
1217                                 switch (logfile.first) {
1218                                 case Buffer::latexlog:
1219                                         data = "latex ";
1220                                         break;
1221                                 case Buffer::buildlog:
1222                                         data = "literate ";
1223                                         break;
1224                                 }
1225                                 data += logfile.second;
1226                                 owner->getDialogs().show("log", data);
1227                         }
1228                         else if (name == "vclog") {
1229                                 string const data = "vc " +
1230                                         owner->buffer()->lyxvc().getLogFile();
1231                                 owner->getDialogs().show("log", data);
1232                         }
1233                         else
1234                                 owner->getDialogs().show(name, data);
1235                         break;
1236                 }
1237
1238                 case LFUN_DIALOG_SHOW_NEW_INSET: {
1239                         string const name = func.getArg(0);
1240                         string data = trim(func.argument.substr(name.size()));
1241                         if (name == "bibitem" ||
1242                             name == "bibtex" ||
1243                             name == "include" ||
1244                             name == "index" ||
1245                             name == "label" ||
1246                             name == "ref" ||
1247                             name == "toc" ||
1248                             name == "url") {
1249                                 InsetCommandParams p(name);
1250                                 data = InsetCommandMailer::params2string(name, p);
1251                         } else if (name == "box") {
1252                                 // \c data == "Boxed" || "Frameless" etc
1253                                 InsetBoxParams p(data);
1254                                 data = InsetBoxMailer::params2string(p);
1255                         } else if (name == "branch") {
1256                                 InsetBranchParams p;
1257                                 data = InsetBranchMailer::params2string(p);
1258                         } else if (name == "citation") {
1259                                 InsetCommandParams p("cite");
1260                                 data = InsetCommandMailer::params2string(name, p);
1261                         } else if (name == "ert") {
1262                                 data = InsetERTMailer::params2string(InsetCollapsable::Open);
1263                         } else if (name == "external") {
1264                                 InsetExternalParams p;
1265                                 Buffer const & buffer = *owner->buffer();
1266                                 data = InsetExternalMailer::params2string(p, buffer);
1267                         } else if (name == "float") {
1268                                 InsetFloatParams p;
1269                                 data = InsetFloatMailer::params2string(p);
1270                         } else if (name == "graphics") {
1271                                 InsetGraphicsParams p;
1272                                 Buffer const & buffer = *owner->buffer();
1273                                 data = InsetGraphicsMailer::params2string(p, buffer);
1274                         } else if (name == "note") {
1275                                 InsetNoteParams p;
1276                                 data = InsetNoteMailer::params2string(p);
1277                         } else if (name == "vspace") {
1278                                 VSpace space;
1279                                 data = InsetVSpaceMailer::params2string(space);
1280                         } else if (name == "wrap") {
1281                                 InsetWrapParams p;
1282                                 data = InsetWrapMailer::params2string(p);
1283                         }
1284                         owner->getDialogs().show(name, data, 0);
1285                         break;
1286                 }
1287
1288                 case LFUN_DIALOG_SHOW_NEXT_INSET:
1289                         break;
1290
1291                 case LFUN_INSET_DIALOG_SHOW: {
1292                         InsetOld * inset = view()->getLyXText()->getInset();
1293                         if (inset)
1294                                 inset->dispatch(FuncRequest(view(), LFUN_INSET_DIALOG_SHOW));
1295                         break;
1296                 }
1297
1298                 case LFUN_DIALOG_UPDATE: {
1299                         string const & name = argument;
1300                         // Can only update a dialog connected to an existing inset
1301                         InsetBase * inset = owner->getDialogs().getOpenInset(name);
1302                         if (inset) {
1303                                 FuncRequest fr(view(), LFUN_INSET_DIALOG_UPDATE,
1304                                                                  func.argument);
1305                                 inset->dispatch(fr);
1306                         } else if (name == "paragraph") {
1307                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1308                         }
1309                         break;
1310                 }
1311
1312                 case LFUN_DIALOG_HIDE:
1313                         Dialogs::hide(argument, 0);
1314                         break;
1315
1316                 case LFUN_DIALOG_DISCONNECT_INSET:
1317                         owner->getDialogs().disconnect(argument);
1318                         break;
1319
1320                 case LFUN_CHILDOPEN: {
1321                         string const filename =
1322                                 MakeAbsPath(argument, owner->buffer()->filePath());
1323                         setMessage(N_("Opening child document ") +
1324                                          MakeDisplayPath(filename) + "...");
1325                         view()->savePosition(0);
1326                         string const parentfilename = owner->buffer()->fileName();
1327                         if (bufferlist.exists(filename))
1328                                 view()->buffer(bufferlist.getBuffer(filename));
1329                         else
1330                                 view()->loadLyXFile(filename);
1331                         // Set the parent name of the child document.
1332                         // This makes insertion of citations and references in the child work,
1333                         // when the target is in the parent or another child document.
1334                         owner->buffer()->setParentName(parentfilename);
1335                         break;
1336                 }
1337
1338                 case LFUN_TOGGLECURSORFOLLOW:
1339                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1340                         break;
1341
1342                 case LFUN_KMAP_OFF:
1343                         owner->getIntl().KeyMapOn(false);
1344                         break;
1345
1346                 case LFUN_KMAP_PRIM:
1347                         owner->getIntl().KeyMapPrim();
1348                         break;
1349
1350                 case LFUN_KMAP_SEC:
1351                         owner->getIntl().KeyMapSec();
1352                         break;
1353
1354                 case LFUN_KMAP_TOGGLE:
1355                         owner->getIntl().ToggleKeyMap();
1356                         break;
1357
1358                 case LFUN_REPEAT: {
1359                         // repeat command
1360                         string countstr;
1361                         argument = split(argument, countstr, ' ');
1362                         istringstream is(countstr);
1363                         int count = 0;
1364                         is >> count;
1365                         lyxerr << "repeat: count: " << count << " cmd: " << argument << endl;
1366                         for (int i = 0; i < count; ++i)
1367                                 dispatch(lyxaction.lookupFunc(argument));
1368                         break;
1369                 }
1370
1371                 case LFUN_SEQUENCE:
1372                         // argument contains ';'-terminated commands
1373                         while (!argument.empty()) {
1374                                 string first;
1375                                 argument = split(argument, first, ';');
1376                                 dispatch(lyxaction.lookupFunc(first));
1377                         }
1378                         break;
1379
1380                 case LFUN_SAVEPREFERENCES: {
1381                         Path p(user_lyxdir());
1382                         lyxrc.write("preferences");
1383                         break;
1384                 }
1385
1386                 case LFUN_SCREEN_FONT_UPDATE:
1387                         // handle the screen font changes.
1388                         lyxrc.set_font_norm_type();
1389                         lyx_gui::update_fonts();
1390                         // All visible buffers will need resize
1391                         view()->resize();
1392                         break;
1393
1394                 case LFUN_SET_COLOR: {
1395                         string lyx_name;
1396                         string const x11_name = split(argument, lyx_name, ' ');
1397                         if (lyx_name.empty() || x11_name.empty()) {
1398                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1399                                                         " <x11_name>"));
1400                                 break;
1401                         }
1402
1403                         bool const graphicsbg_changed =
1404                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1405                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1406
1407                         LColor::color col = lcolor.getFromLyXName(lyx_name);
1408                         if (!lcolor.setColor(col, x11_name)) {
1409                                 setErrorMessage(
1410                                         bformat(_("Set-color \"%1$s\" failed "
1411                                                                 "- color is undefined or "
1412                                                                 "may not be redefined"), lyx_name));
1413                                 break;
1414                         }
1415
1416                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1417
1418                         if (graphicsbg_changed) {
1419 #ifdef WITH_WARNINGS
1420 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1421 #endif
1422 #if 0
1423                                 lyx::graphics::GCache::get().changeDisplay(true);
1424 #endif
1425                         }
1426                         break;
1427                 }
1428
1429                 case LFUN_MESSAGE:
1430                         owner->message(argument);
1431                         break;
1432
1433                 case LFUN_FORKS_KILL:
1434                         if (isStrInt(argument))
1435                                 ForkedcallsController::get().kill(strToInt(argument));
1436                         break;
1437
1438                 case LFUN_TOOLTIPS_TOGGLE:
1439                         owner->getDialogs().toggleTooltips();
1440                         break;
1441
1442                 case LFUN_EXTERNAL_EDIT:
1443                         InsetExternal().dispatch(FuncRequest(view(), action, argument));
1444                         break;
1445
1446                 default: {
1447                                 DispatchResult result =
1448                                         view()->cursor().dispatch(FuncRequest(func, view()));
1449                                 if (result.dispatched())
1450                                         lyxerr << "dispatched by Cursor::dispatch()" << endl;
1451                                 else
1452                                         lyxerr << "### NOT DISPATCHED BY Cursor::dispatch() ###" << endl;
1453                                 break;
1454                         }
1455                 }
1456         }
1457
1458         view()->owner()->updateLayoutChoice();
1459
1460         if (view()->available()) {
1461                 view()->fitCursor();
1462                 view()->update();
1463                 view()->cursor().updatePos();
1464                 // if we executed a mutating lfun, mark the buffer as dirty
1465                 if (!getStatus(func).disabled()
1466                     && !lyxaction.funcHasFlag(func.action, LyXAction::NoBuffer)
1467                     && !lyxaction.funcHasFlag(func.action, LyXAction::ReadOnly))
1468                         view()->buffer()->markDirty();
1469         }
1470
1471         sendDispatchMessage(getMessage(), func, verbose);
1472 }
1473
1474
1475 void LyXFunc::sendDispatchMessage(string const & msg,
1476                                   FuncRequest const & func, bool verbose)
1477 {
1478         owner->updateMenubar();
1479         owner->updateToolbar();
1480
1481         if (func.action == LFUN_SELFINSERT || !verbose) {
1482                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1483                 if (!msg.empty())
1484                         owner->message(msg);
1485                 return;
1486         }
1487
1488         string dispatch_msg = msg;
1489         if (!dispatch_msg.empty())
1490                 dispatch_msg += ' ';
1491
1492         string comname = lyxaction.getActionName(func.action);
1493
1494         bool argsadded = false;
1495
1496         if (!func.argument.empty()) {
1497                 if (func.action != LFUN_UNKNOWN_ACTION) {
1498                         comname += ' ' + func.argument;
1499                         argsadded = true;
1500                 }
1501         }
1502
1503         string const shortcuts = toplevel_keymap->findbinding(func);
1504
1505         if (!shortcuts.empty()) {
1506                 comname += ": " + shortcuts;
1507         } else if (!argsadded && !func.argument.empty()) {
1508                 comname += ' ' + func.argument;
1509         }
1510
1511         if (!comname.empty()) {
1512                 comname = rtrim(comname);
1513                 dispatch_msg += '(' + comname + ')';
1514         }
1515
1516         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1517         if (!dispatch_msg.empty())
1518                 owner->message(dispatch_msg);
1519 }
1520
1521
1522 void LyXFunc::setupLocalKeymap()
1523 {
1524         keyseq.stdmap = toplevel_keymap.get();
1525         keyseq.curmap = toplevel_keymap.get();
1526         cancel_meta_seq.stdmap = toplevel_keymap.get();
1527         cancel_meta_seq.curmap = toplevel_keymap.get();
1528 }
1529
1530
1531 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1532 {
1533         string initpath = lyxrc.document_path;
1534         string filename(name);
1535
1536         if (view()->available()) {
1537                 string const trypath = owner->buffer()->filePath();
1538                 // If directory is writeable, use this as default.
1539                 if (IsDirWriteable(trypath))
1540                         initpath = trypath;
1541         }
1542
1543         static int newfile_number;
1544
1545         if (filename.empty()) {
1546                 filename = AddName(lyxrc.document_path,
1547                             "newfile" + tostr(++newfile_number) + ".lyx");
1548                 FileInfo fi(filename);
1549                 while (bufferlist.exists(filename) || fi.readable()) {
1550                         ++newfile_number;
1551                         filename = AddName(lyxrc.document_path,
1552                                     "newfile" + tostr(newfile_number) +
1553                                     ".lyx");
1554                         fi.newFile(filename);
1555                 }
1556         }
1557
1558         // The template stuff
1559         string templname;
1560         if (fromTemplate) {
1561                 FileDialog fileDlg(_("Select template file"),
1562                         LFUN_SELECT_FILE_SYNC,
1563                         make_pair(string(_("Documents|#o#O")),
1564                                   string(lyxrc.document_path)),
1565                         make_pair(string(_("Templates|#T#t")),
1566                                   string(lyxrc.template_path)));
1567
1568                 FileDialog::Result result =
1569                         fileDlg.open(lyxrc.template_path,
1570                                        _("*.lyx| LyX Documents (*.lyx)"));
1571
1572                 if (result.first == FileDialog::Later)
1573                         return;
1574                 if (result.second.empty())
1575                         return;
1576                 templname = result.second;
1577         }
1578
1579         view()->newFile(filename, templname, !name.empty());
1580 }
1581
1582
1583 void LyXFunc::open(string const & fname)
1584 {
1585         string initpath = lyxrc.document_path;
1586
1587         if (view()->available()) {
1588                 string const trypath = owner->buffer()->filePath();
1589                 // If directory is writeable, use this as default.
1590                 if (IsDirWriteable(trypath))
1591                         initpath = trypath;
1592         }
1593
1594         string filename;
1595
1596         if (fname.empty()) {
1597                 FileDialog fileDlg(_("Select document to open"),
1598                         LFUN_FILE_OPEN,
1599                         make_pair(string(_("Documents|#o#O")),
1600                                   string(lyxrc.document_path)),
1601                         make_pair(string(_("Examples|#E#e")),
1602                                   string(AddPath(system_lyxdir(), "examples"))));
1603
1604                 FileDialog::Result result =
1605                         fileDlg.open(initpath,
1606                                        _("*.lyx| LyX Documents (*.lyx)"));
1607
1608                 if (result.first == FileDialog::Later)
1609                         return;
1610
1611                 filename = result.second;
1612
1613                 // check selected filename
1614                 if (filename.empty()) {
1615                         owner->message(_("Canceled."));
1616                         return;
1617                 }
1618         } else
1619                 filename = fname;
1620
1621         // get absolute path of file and add ".lyx" to the filename if
1622         // necessary
1623         string const fullpath = FileSearch(string(), filename, "lyx");
1624         if (!fullpath.empty()) {
1625                 filename = fullpath;
1626         }
1627
1628         string const disp_fn(MakeDisplayPath(filename));
1629
1630         // if the file doesn't exist, let the user create one
1631         FileInfo const f(filename, true);
1632         if (!f.exist()) {
1633                 // the user specifically chose this name. Believe them.
1634                 view()->newFile(filename, "", true);
1635                 return;
1636         }
1637
1638         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1639
1640         string str2;
1641         if (view()->loadLyXFile(filename)) {
1642                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1643         } else {
1644                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1645         }
1646         owner->message(str2);
1647 }
1648
1649
1650 void LyXFunc::doImport(string const & argument)
1651 {
1652         string format;
1653         string filename = split(argument, format, ' ');
1654
1655         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1656                             << " file: " << filename << endl;
1657
1658         // need user interaction
1659         if (filename.empty()) {
1660                 string initpath = lyxrc.document_path;
1661
1662                 if (view()->available()) {
1663                         string const trypath = owner->buffer()->filePath();
1664                         // If directory is writeable, use this as default.
1665                         if (IsDirWriteable(trypath))
1666                                 initpath = trypath;
1667                 }
1668
1669                 string const text = bformat(_("Select %1$s file to import"),
1670                         formats.prettyName(format));
1671
1672                 FileDialog fileDlg(text,
1673                         LFUN_IMPORT,
1674                         make_pair(string(_("Documents|#o#O")),
1675                                   string(lyxrc.document_path)),
1676                         make_pair(string(_("Examples|#E#e")),
1677                                   string(AddPath(system_lyxdir(), "examples"))));
1678
1679                 string const extension = "*." + formats.extension(format)
1680                         + "| " + formats.prettyName(format)
1681                         + " (*." + formats.extension(format) + ')';
1682
1683                 FileDialog::Result result = fileDlg.open(initpath,
1684                                                            extension);
1685
1686                 if (result.first == FileDialog::Later)
1687                         return;
1688
1689                 filename = result.second;
1690
1691                 // check selected filename
1692                 if (filename.empty())
1693                         owner->message(_("Canceled."));
1694         }
1695
1696         if (filename.empty())
1697                 return;
1698
1699         // get absolute path of file
1700         filename = MakeAbsPath(filename);
1701
1702         string const lyxfile = ChangeExtension(filename, ".lyx");
1703
1704         // Check if the document already is open
1705         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1706                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1707                         owner->message(_("Canceled."));
1708                         return;
1709                 }
1710         }
1711
1712         // if the file exists already, and we didn't do
1713         // -i lyx thefile.lyx, warn
1714         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1715                 string const file = MakeDisplayPath(lyxfile, 30);
1716
1717                 string text = bformat(_("The document %1$s already exists.\n\n"
1718                         "Do you want to over-write that document?"), file);
1719                 int const ret = Alert::prompt(_("Over-write document?"),
1720                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1721
1722                 if (ret == 1) {
1723                         owner->message(_("Canceled."));
1724                         return;
1725                 }
1726         }
1727
1728         Importer::Import(owner, filename, format);
1729 }
1730
1731
1732 void LyXFunc::closeBuffer()
1733 {
1734         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1735                 if (bufferlist.empty()) {
1736                         // need this otherwise SEGV may occur while
1737                         // trying to set variables that don't exist
1738                         // since there's no current buffer
1739                         owner->getDialogs().hideBufferDependent();
1740                 } else {
1741                         view()->buffer(bufferlist.first());
1742                 }
1743         }
1744 }
1745
1746
1747 // Each "owner" should have it's own message method. lyxview and
1748 // the minibuffer would use the minibuffer, but lyxserver would
1749 // send an ERROR signal to its client.  Alejandro 970603
1750 // This func is bit problematic when it comes to NLS, to make the
1751 // lyx servers client be language indepenent we must not translate
1752 // strings sent to this func.
1753 void LyXFunc::setErrorMessage(string const & m) const
1754 {
1755         dispatch_buffer = m;
1756         errorstat = true;
1757 }
1758
1759
1760 void LyXFunc::setMessage(string const & m) const
1761 {
1762         dispatch_buffer = m;
1763 }
1764
1765
1766 void LyXFunc::setStatusMessage(string const & m) const
1767 {
1768         status_buffer = m;
1769 }
1770
1771
1772 string const LyXFunc::view_status_message()
1773 {
1774         // When meta-fake key is pressed, show the key sequence so far + "M-".
1775         if (wasMetaKey()) {
1776                 return keyseq.print() + "M-";
1777         }
1778
1779         // Else, when a non-complete key sequence is pressed,
1780         // show the available options.
1781         if (keyseq.length() > 0 && !keyseq.deleted()) {
1782                 return keyseq.printOptions();
1783         }
1784
1785         if (!view()->available())
1786                 return _("Welcome to LyX!");
1787
1788         return currentState(view());
1789 }
1790
1791
1792 BufferView * LyXFunc::view() const
1793 {
1794         BOOST_ASSERT(owner);
1795         return owner->view().get();
1796 }
1797
1798
1799 bool LyXFunc::wasMetaKey() const
1800 {
1801         return (meta_fake_bit != key_modifier::none);
1802 }