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