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