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