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