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