]> git.lyx.org Git - lyx.git/blob - src/lyxfunc.C
mathed uglyfication
[lyx.git] / src / lyxfunc.C
1 /**
2  * \file lyxfunc.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Allan Rae
13  * \author Dekel Tsur
14  * \author Martin Vermeer
15  * \author Jürgen Vigna
16  *
17  * Full author contact details are available in file CREDITS.
18  */
19
20 #include <config.h>
21
22 #include "lyxfunc.h"
23
24 #include "BranchList.h"
25 #include "buffer.h"
26 #include "buffer_funcs.h"
27 #include "bufferlist.h"
28 #include "bufferparams.h"
29 #include "BufferView.h"
30 #include "cursor.h"
31 #include "debug.h"
32 #include "dispatchresult.h"
33 #include "encoding.h"
34 #include "exporter.h"
35 #include "format.h"
36 #include "funcrequest.h"
37 #include "gettext.h"
38 #include "importer.h"
39 #include "intl.h"
40 #include "iterators.h"
41 #include "kbmap.h"
42 #include "LColor.h"
43 #include "lyx_cb.h"
44 #include "LyXAction.h"
45 #include "lyxfind.h"
46 #include "lyxrc.h"
47 #include "lyxrow.h"
48 #include "lyxserver.h"
49 #include "lyxvc.h"
50 #include "paragraph.h"
51 #include "ParagraphParameters.h"
52 #include "undo.h"
53
54 #include "insets/insetbox.h"
55 #include "insets/insetbranch.h"
56 #include "insets/insetcommand.h"
57 #include "insets/insetert.h"
58 #include "insets/insetexternal.h"
59 #include "insets/insetfloat.h"
60 #include "insets/insetgraphics.h"
61 #include "insets/insetnote.h"
62 #include "insets/insettabular.h"
63 #include "insets/insetvspace.h"
64 #include "insets/insetwrap.h"
65
66 #include "mathed/math_cursor.h"
67
68 #include "frontends/Alert.h"
69 #include "frontends/Dialogs.h"
70 #include "frontends/FileDialog.h"
71 #include "frontends/lyx_gui.h"
72 #include "frontends/LyXKeySym.h"
73 #include "frontends/LyXView.h"
74 #include "frontends/Menubar.h"
75 #include "frontends/Toolbar.h"
76
77 #include "support/FileInfo.h"
78 #include "support/filetools.h"
79 #include "support/forkedcontr.h"
80 #include "support/globbing.h"
81 #include "support/path.h"
82 #include "support/path_defines.h"
83 #include "support/tostr.h"
84 #include "support/std_sstream.h"
85 #include "support/os.h"
86
87 using bv_funcs::changeDepth;
88 using bv_funcs::currentState;
89 using bv_funcs::DEC_DEPTH;
90 using bv_funcs::freefont2string;
91 using bv_funcs::INC_DEPTH;
92
93 using lyx::support::AddName;
94 using lyx::support::AddPath;
95 using lyx::support::bformat;
96 using lyx::support::ChangeExtension;
97 using lyx::support::FileFilterList;
98 using lyx::support::FileInfo;
99 using lyx::support::FileSearch;
100 using lyx::support::ForkedcallsController;
101 using lyx::support::i18nLibFileSearch;
102 using lyx::support::IsDirWriteable;
103 using lyx::support::IsFileReadable;
104 using lyx::support::isStrInt;
105 using lyx::support::MakeAbsPath;
106 using lyx::support::MakeDisplayPath;
107 using lyx::support::Path;
108 using lyx::support::rtrim;
109 using lyx::support::split;
110 using lyx::support::strToInt;
111 using lyx::support::strToUnsignedInt;
112 using lyx::support::system_lyxdir;
113 using lyx::support::token;
114 using lyx::support::trim;
115 using lyx::support::user_lyxdir;
116 using lyx::support::prefixIs;
117 using lyx::support::os::getTmpDir;
118
119 using std::endl;
120 using std::make_pair;
121 using std::pair;
122 using std::string;
123 using std::istringstream;
124
125
126 extern BufferList bufferlist;
127 extern LyXServer * lyxserver;
128 extern bool selection_possible;
129
130 extern boost::scoped_ptr<kb_keymap> toplevel_keymap;
131
132 // (alkis)
133 extern tex_accent_struct get_accent(kb_action action);
134
135
136 LyXFunc::LyXFunc(LyXView * lv)
137         : owner(lv),
138         encoded_last_key(0),
139         keyseq(toplevel_keymap.get(), toplevel_keymap.get()),
140         cancel_meta_seq(toplevel_keymap.get(), toplevel_keymap.get()),
141         meta_fake_bit(key_modifier::none)
142 {
143 }
144
145
146 void LyXFunc::handleKeyFunc(kb_action action)
147 {
148         char c = encoded_last_key;
149
150         if (keyseq.length()) {
151                 c = 0;
152         }
153
154         owner->getIntl().getTransManager()
155                 .deadkey(c, get_accent(action).accent, view()->getLyXText());
156         // Need to clear, in case the minibuffer calls these
157         // actions
158         keyseq.clear();
159         // copied verbatim from do_accent_char
160         view()->resetAnchor();
161         view()->update();
162 }
163
164
165 void LyXFunc::processKeySym(LyXKeySymPtr keysym,
166                             key_modifier::state state)
167 {
168         string argument;
169
170         if (lyxerr.debugging(Debug::KEY)) {
171                 lyxerr << "KeySym is "
172                        << keysym->getSymbolName()
173                        << endl;
174         }
175
176         // Do nothing if we have nothing (JMarc)
177         if (!keysym->isOK()) {
178                 lyxerr[Debug::KEY] << "Empty kbd action (probably composing)"
179                                    << endl;
180                 return;
181         }
182
183         if (keysym->isModifier()) {
184                 lyxerr[Debug::KEY] << "isModifier true" << endl;
185                 return;
186         }
187
188         Encoding const * encoding = view()->getEncoding();
189
190         encoded_last_key = keysym->getISOEncoded(encoding ? encoding->Name() : "");
191
192         // Do a one-deep top-level lookup for
193         // cancel and meta-fake keys. RVDK_PATCH_5
194         cancel_meta_seq.reset();
195
196         FuncRequest func = cancel_meta_seq.addkey(keysym, state);
197         lyxerr[Debug::KEY] << "action first set to [" << func.action << ']' << endl;
198
199         // When not cancel or meta-fake, do the normal lookup.
200         // Note how the meta_fake Mod1 bit is OR-ed in and reset afterwards.
201         // Mostly, meta_fake_bit = key_modifier::none. RVDK_PATCH_5.
202         if ((func.action != LFUN_CANCEL) && (func.action != LFUN_META_FAKE)) {
203                 // remove Caps Lock and Mod2 as a modifiers
204                 func = keyseq.addkey(keysym, (state | meta_fake_bit));
205                 lyxerr[Debug::KEY] << "action now set to ["
206                         << func.action << ']' << endl;
207         }
208
209         // Dont remove this unless you know what you are doing.
210         meta_fake_bit = key_modifier::none;
211
212         // can this happen now ?
213         if (func.action == LFUN_NOACTION) {
214                 func = FuncRequest(LFUN_PREFIX);
215         }
216
217         if (lyxerr.debugging(Debug::KEY)) {
218                 lyxerr << "Key [action="
219                        << func.action << "]["
220                        << keyseq.print() << ']'
221                        << endl;
222         }
223
224         // already here we know if it any point in going further
225         // why not return already here if action == -1 and
226         // num_bytes == 0? (Lgb)
227
228         if (keyseq.length() > 1) {
229                 owner->message(keyseq.print());
230         }
231
232
233         // Maybe user can only reach the key via holding down shift.
234         // Let's see. But only if shift is the only modifier
235         if (func.action == LFUN_UNKNOWN_ACTION &&
236             state == key_modifier::shift) {
237                 lyxerr[Debug::KEY] << "Trying without shift" << endl;
238                 func = keyseq.addkey(keysym, key_modifier::none);
239                 lyxerr[Debug::KEY] << "Action now " << func.action << endl;
240         }
241
242         if (func.action == LFUN_UNKNOWN_ACTION) {
243                 // Hmm, we didn't match any of the keysequences. See
244                 // if it's normal insertable text not already covered
245                 // by a binding
246                 if (keysym->isText() && keyseq.length() == 1) {
247                         lyxerr[Debug::KEY] << "isText() is true, inserting." << endl;
248                         func = FuncRequest(LFUN_SELFINSERT);
249                 } else {
250                         lyxerr[Debug::KEY] << "Unknown, !isText() - giving up" << endl;
251                         owner->message(_("Unknown function."));
252                         return;
253                 }
254         }
255
256         if (func.action == LFUN_SELFINSERT) {
257                 if (encoded_last_key != 0) {
258                         string arg;
259                         arg += encoded_last_key;
260                         dispatch(FuncRequest(LFUN_SELFINSERT, arg));
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()->fullCursor().innerInset();
324         InsetTabular * tab = view()->fullCursor().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()->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()->fullCursor().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()->fullCursor().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()->fullCursor().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()->fullCursor().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, true, false, fw);
890                         view()->dispatch(FuncRequest(LFUN_WORD_FIND, data));
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()->fullCursor().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(*view(), FuncRequest(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(LFUN_INSET_DIALOG_UPDATE, func.argument);
1304                                 inset->dispatch(*view(), fr);
1305                         } else if (name == "paragraph") {
1306                                 dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1307                         }
1308                         break;
1309                 }
1310
1311                 case LFUN_DIALOG_HIDE:
1312                         Dialogs::hide(argument, 0);
1313                         break;
1314
1315                 case LFUN_DIALOG_DISCONNECT_INSET:
1316                         owner->getDialogs().disconnect(argument);
1317                         break;
1318
1319                 case LFUN_CHILDOPEN: {
1320                         string const filename =
1321                                 MakeAbsPath(argument, owner->buffer()->filePath());
1322                         setMessage(N_("Opening child document ") +
1323                                          MakeDisplayPath(filename) + "...");
1324                         view()->savePosition(0);
1325                         string const parentfilename = owner->buffer()->fileName();
1326                         if (bufferlist.exists(filename))
1327                                 view()->buffer(bufferlist.getBuffer(filename));
1328                         else
1329                                 view()->loadLyXFile(filename);
1330                         // Set the parent name of the child document.
1331                         // This makes insertion of citations and references in the child work,
1332                         // when the target is in the parent or another child document.
1333                         owner->buffer()->setParentName(parentfilename);
1334                         break;
1335                 }
1336
1337                 case LFUN_TOGGLECURSORFOLLOW:
1338                         lyxrc.cursor_follows_scrollbar = !lyxrc.cursor_follows_scrollbar;
1339                         break;
1340
1341                 case LFUN_KMAP_OFF:
1342                         owner->getIntl().KeyMapOn(false);
1343                         break;
1344
1345                 case LFUN_KMAP_PRIM:
1346                         owner->getIntl().KeyMapPrim();
1347                         break;
1348
1349                 case LFUN_KMAP_SEC:
1350                         owner->getIntl().KeyMapSec();
1351                         break;
1352
1353                 case LFUN_KMAP_TOGGLE:
1354                         owner->getIntl().ToggleKeyMap();
1355                         break;
1356
1357                 case LFUN_REPEAT: {
1358                         // repeat command
1359                         string countstr;
1360                         argument = split(argument, countstr, ' ');
1361                         istringstream is(countstr);
1362                         int count = 0;
1363                         is >> count;
1364                         lyxerr << "repeat: count: " << count << " cmd: " << argument << endl;
1365                         for (int i = 0; i < count; ++i)
1366                                 dispatch(lyxaction.lookupFunc(argument));
1367                         break;
1368                 }
1369
1370                 case LFUN_SEQUENCE:
1371                         // argument contains ';'-terminated commands
1372                         while (!argument.empty()) {
1373                                 string first;
1374                                 argument = split(argument, first, ';');
1375                                 dispatch(lyxaction.lookupFunc(first));
1376                         }
1377                         break;
1378
1379                 case LFUN_SAVEPREFERENCES: {
1380                         Path p(user_lyxdir());
1381                         lyxrc.write("preferences");
1382                         break;
1383                 }
1384
1385                 case LFUN_SCREEN_FONT_UPDATE:
1386                         // handle the screen font changes.
1387                         lyxrc.set_font_norm_type();
1388                         lyx_gui::update_fonts();
1389                         // All visible buffers will need resize
1390                         view()->resize();
1391                         break;
1392
1393                 case LFUN_SET_COLOR: {
1394                         string lyx_name;
1395                         string const x11_name = split(argument, lyx_name, ' ');
1396                         if (lyx_name.empty() || x11_name.empty()) {
1397                                 setErrorMessage(N_("Syntax: set-color <lyx_name>"
1398                                                         " <x11_name>"));
1399                                 break;
1400                         }
1401
1402                         bool const graphicsbg_changed =
1403                                 (lyx_name == lcolor.getLyXName(LColor::graphicsbg) &&
1404                                  x11_name != lcolor.getX11Name(LColor::graphicsbg));
1405
1406                         LColor::color col = lcolor.getFromLyXName(lyx_name);
1407                         if (!lcolor.setColor(col, x11_name)) {
1408                                 setErrorMessage(
1409                                         bformat(_("Set-color \"%1$s\" failed "
1410                                                                 "- color is undefined or "
1411                                                                 "may not be redefined"), lyx_name));
1412                                 break;
1413                         }
1414
1415                         lyx_gui::update_color(lcolor.getFromLyXName(lyx_name));
1416
1417                         if (graphicsbg_changed) {
1418 #ifdef WITH_WARNINGS
1419 #warning FIXME!! The graphics cache no longer has a changeDisplay method.
1420 #endif
1421 #if 0
1422                                 lyx::graphics::GCache::get().changeDisplay(true);
1423 #endif
1424                         }
1425                         break;
1426                 }
1427
1428                 case LFUN_MESSAGE:
1429                         owner->message(argument);
1430                         break;
1431
1432                 case LFUN_FORKS_KILL:
1433                         if (isStrInt(argument))
1434                                 ForkedcallsController::get().kill(strToInt(argument));
1435                         break;
1436
1437                 case LFUN_TOOLTIPS_TOGGLE:
1438                         owner->getDialogs().toggleTooltips();
1439                         break;
1440
1441                 case LFUN_EXTERNAL_EDIT:
1442                         InsetExternal().dispatch(*view(), FuncRequest(action, argument));
1443                         break;
1444
1445                 default:
1446                         view()->fullCursor().dispatch(FuncRequest(func));
1447                         break;
1448                 }
1449         }
1450
1451         view()->owner()->updateLayoutChoice();
1452
1453         if (view()->available()) {
1454                 view()->fitCursor();
1455                 view()->update();
1456                 view()->fullCursor().updatePos();
1457                 // if we executed a mutating lfun, mark the buffer as dirty
1458                 if (!getStatus(func).disabled()
1459                     && !lyxaction.funcHasFlag(func.action, LyXAction::NoBuffer)
1460                     && !lyxaction.funcHasFlag(func.action, LyXAction::ReadOnly))
1461                         view()->buffer()->markDirty();
1462         }
1463
1464         sendDispatchMessage(getMessage(), func, verbose);
1465 }
1466
1467
1468 void LyXFunc::sendDispatchMessage(string const & msg,
1469                                   FuncRequest const & func, bool verbose)
1470 {
1471         owner->updateMenubar();
1472         owner->updateToolbar();
1473
1474         if (func.action == LFUN_SELFINSERT || !verbose) {
1475                 lyxerr[Debug::ACTION] << "dispatch msg is " << msg << endl;
1476                 if (!msg.empty())
1477                         owner->message(msg);
1478                 return;
1479         }
1480
1481         string dispatch_msg = msg;
1482         if (!dispatch_msg.empty())
1483                 dispatch_msg += ' ';
1484
1485         string comname = lyxaction.getActionName(func.action);
1486
1487         bool argsadded = false;
1488
1489         if (!func.argument.empty()) {
1490                 if (func.action != LFUN_UNKNOWN_ACTION) {
1491                         comname += ' ' + func.argument;
1492                         argsadded = true;
1493                 }
1494         }
1495
1496         string const shortcuts = toplevel_keymap->findbinding(func);
1497
1498         if (!shortcuts.empty()) {
1499                 comname += ": " + shortcuts;
1500         } else if (!argsadded && !func.argument.empty()) {
1501                 comname += ' ' + func.argument;
1502         }
1503
1504         if (!comname.empty()) {
1505                 comname = rtrim(comname);
1506                 dispatch_msg += '(' + comname + ')';
1507         }
1508
1509         lyxerr[Debug::ACTION] << "verbose dispatch msg " << dispatch_msg << endl;
1510         if (!dispatch_msg.empty())
1511                 owner->message(dispatch_msg);
1512 }
1513
1514
1515 void LyXFunc::setupLocalKeymap()
1516 {
1517         keyseq.stdmap = toplevel_keymap.get();
1518         keyseq.curmap = toplevel_keymap.get();
1519         cancel_meta_seq.stdmap = toplevel_keymap.get();
1520         cancel_meta_seq.curmap = toplevel_keymap.get();
1521 }
1522
1523
1524 void LyXFunc::menuNew(string const & name, bool fromTemplate)
1525 {
1526         string initpath = lyxrc.document_path;
1527         string filename(name);
1528
1529         if (view()->available()) {
1530                 string const trypath = owner->buffer()->filePath();
1531                 // If directory is writeable, use this as default.
1532                 if (IsDirWriteable(trypath))
1533                         initpath = trypath;
1534         }
1535
1536         static int newfile_number;
1537
1538         if (filename.empty()) {
1539                 filename = AddName(lyxrc.document_path,
1540                             "newfile" + tostr(++newfile_number) + ".lyx");
1541                 FileInfo fi(filename);
1542                 while (bufferlist.exists(filename) || fi.readable()) {
1543                         ++newfile_number;
1544                         filename = AddName(lyxrc.document_path,
1545                                     "newfile" + tostr(newfile_number) +
1546                                     ".lyx");
1547                         fi.newFile(filename);
1548                 }
1549         }
1550
1551         // The template stuff
1552         string templname;
1553         if (fromTemplate) {
1554                 FileDialog fileDlg(_("Select template file"),
1555                         LFUN_SELECT_FILE_SYNC,
1556                         make_pair(string(_("Documents|#o#O")),
1557                                   string(lyxrc.document_path)),
1558                         make_pair(string(_("Templates|#T#t")),
1559                                   string(lyxrc.template_path)));
1560
1561                 FileDialog::Result result =
1562                         fileDlg.open(lyxrc.template_path,
1563                                      FileFilterList(_("LyX Documents (*.lyx)")),
1564                                      string());
1565
1566                 if (result.first == FileDialog::Later)
1567                         return;
1568                 if (result.second.empty())
1569                         return;
1570                 templname = result.second;
1571         }
1572
1573         view()->newFile(filename, templname, !name.empty());
1574 }
1575
1576
1577 void LyXFunc::open(string const & fname)
1578 {
1579         string initpath = lyxrc.document_path;
1580
1581         if (view()->available()) {
1582                 string const trypath = owner->buffer()->filePath();
1583                 // If directory is writeable, use this as default.
1584                 if (IsDirWriteable(trypath))
1585                         initpath = trypath;
1586         }
1587
1588         string filename;
1589
1590         if (fname.empty()) {
1591                 FileDialog fileDlg(_("Select document to open"),
1592                         LFUN_FILE_OPEN,
1593                         make_pair(string(_("Documents|#o#O")),
1594                                   string(lyxrc.document_path)),
1595                         make_pair(string(_("Examples|#E#e")),
1596                                   string(AddPath(system_lyxdir(), "examples"))));
1597
1598                 FileDialog::Result result =
1599                         fileDlg.open(initpath,
1600                                      FileFilterList(_("LyX Documents (*.lyx)")),
1601                                      string());
1602
1603                 if (result.first == FileDialog::Later)
1604                         return;
1605
1606                 filename = result.second;
1607
1608                 // check selected filename
1609                 if (filename.empty()) {
1610                         owner->message(_("Canceled."));
1611                         return;
1612                 }
1613         } else
1614                 filename = fname;
1615
1616         // get absolute path of file and add ".lyx" to the filename if
1617         // necessary
1618         string const fullpath = FileSearch(string(), filename, "lyx");
1619         if (!fullpath.empty()) {
1620                 filename = fullpath;
1621         }
1622
1623         string const disp_fn(MakeDisplayPath(filename));
1624
1625         // if the file doesn't exist, let the user create one
1626         FileInfo const f(filename, true);
1627         if (!f.exist()) {
1628                 // the user specifically chose this name. Believe them.
1629                 view()->newFile(filename, "", true);
1630                 return;
1631         }
1632
1633         owner->message(bformat(_("Opening document %1$s..."), disp_fn));
1634
1635         string str2;
1636         if (view()->loadLyXFile(filename)) {
1637                 str2 = bformat(_("Document %1$s opened."), disp_fn);
1638         } else {
1639                 str2 = bformat(_("Could not open document %1$s"), disp_fn);
1640         }
1641         owner->message(str2);
1642 }
1643
1644
1645 void LyXFunc::doImport(string const & argument)
1646 {
1647         string format;
1648         string filename = split(argument, format, ' ');
1649
1650         lyxerr[Debug::INFO] << "LyXFunc::doImport: " << format
1651                             << " file: " << filename << endl;
1652
1653         // need user interaction
1654         if (filename.empty()) {
1655                 string initpath = lyxrc.document_path;
1656
1657                 if (view()->available()) {
1658                         string const trypath = owner->buffer()->filePath();
1659                         // If directory is writeable, use this as default.
1660                         if (IsDirWriteable(trypath))
1661                                 initpath = trypath;
1662                 }
1663
1664                 string const text = bformat(_("Select %1$s file to import"),
1665                         formats.prettyName(format));
1666
1667                 FileDialog fileDlg(text,
1668                         LFUN_IMPORT,
1669                         make_pair(string(_("Documents|#o#O")),
1670                                   string(lyxrc.document_path)),
1671                         make_pair(string(_("Examples|#E#e")),
1672                                   string(AddPath(system_lyxdir(), "examples"))));
1673
1674                 string const filter = formats.prettyName(format)
1675                         + " (*." + formats.extension(format) + ')';
1676
1677                 FileDialog::Result result =
1678                         fileDlg.open(initpath,
1679                                      FileFilterList(filter),
1680                                      string());
1681
1682                 if (result.first == FileDialog::Later)
1683                         return;
1684
1685                 filename = result.second;
1686
1687                 // check selected filename
1688                 if (filename.empty())
1689                         owner->message(_("Canceled."));
1690         }
1691
1692         if (filename.empty())
1693                 return;
1694
1695         // get absolute path of file
1696         filename = MakeAbsPath(filename);
1697
1698         string const lyxfile = ChangeExtension(filename, ".lyx");
1699
1700         // Check if the document already is open
1701         if (lyx_gui::use_gui && bufferlist.exists(lyxfile)) {
1702                 if (!bufferlist.close(bufferlist.getBuffer(lyxfile), true)) {
1703                         owner->message(_("Canceled."));
1704                         return;
1705                 }
1706         }
1707
1708         // if the file exists already, and we didn't do
1709         // -i lyx thefile.lyx, warn
1710         if (FileInfo(lyxfile, true).exist() && filename != lyxfile) {
1711                 string const file = MakeDisplayPath(lyxfile, 30);
1712
1713                 string text = bformat(_("The document %1$s already exists.\n\n"
1714                         "Do you want to over-write that document?"), file);
1715                 int const ret = Alert::prompt(_("Over-write document?"),
1716                         text, 0, 1, _("&Over-write"), _("&Cancel"));
1717
1718                 if (ret == 1) {
1719                         owner->message(_("Canceled."));
1720                         return;
1721                 }
1722         }
1723
1724         Importer::Import(owner, filename, format);
1725 }
1726
1727
1728 void LyXFunc::closeBuffer()
1729 {
1730         if (bufferlist.close(owner->buffer(), true) && !quitting) {
1731                 if (bufferlist.empty()) {
1732                         // need this otherwise SEGV may occur while
1733                         // trying to set variables that don't exist
1734                         // since there's no current buffer
1735                         owner->getDialogs().hideBufferDependent();
1736                 } else {
1737                         view()->buffer(bufferlist.first());
1738                 }
1739         }
1740 }
1741
1742
1743 // Each "owner" should have it's own message method. lyxview and
1744 // the minibuffer would use the minibuffer, but lyxserver would
1745 // send an ERROR signal to its client.  Alejandro 970603
1746 // This func is bit problematic when it comes to NLS, to make the
1747 // lyx servers client be language indepenent we must not translate
1748 // strings sent to this func.
1749 void LyXFunc::setErrorMessage(string const & m) const
1750 {
1751         dispatch_buffer = m;
1752         errorstat = true;
1753 }
1754
1755
1756 void LyXFunc::setMessage(string const & m) const
1757 {
1758         dispatch_buffer = m;
1759 }
1760
1761
1762 void LyXFunc::setStatusMessage(string const & m) const
1763 {
1764         status_buffer = m;
1765 }
1766
1767
1768 string const LyXFunc::view_status_message()
1769 {
1770         // When meta-fake key is pressed, show the key sequence so far + "M-".
1771         if (wasMetaKey()) {
1772                 return keyseq.print() + "M-";
1773         }
1774
1775         // Else, when a non-complete key sequence is pressed,
1776         // show the available options.
1777         if (keyseq.length() > 0 && !keyseq.deleted()) {
1778                 return keyseq.printOptions();
1779         }
1780
1781         if (!view()->available())
1782                 return _("Welcome to LyX!");
1783
1784         return currentState(view());
1785 }
1786
1787
1788 BufferView * LyXFunc::view() const
1789 {
1790         BOOST_ASSERT(owner);
1791         return owner->view().get();
1792 }
1793
1794
1795 bool LyXFunc::wasMetaKey() const
1796 {
1797         return (meta_fake_bit != key_modifier::none);
1798 }