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