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