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