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