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