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