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